diff --git a/CMakeLists.txt b/CMakeLists.txt index 70a5284..2a21694 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,10 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) find_package(PkgConfig REQUIRED) -pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil) +pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET + libswresample>=4 + libavutil>=57 +) pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) @@ -22,6 +25,7 @@ add_executable(EchoionStandalone src/AudioEncoder.cpp src/MessageChunker.cpp src/ReleaseManifest.cpp + src/RuntimePaths.cpp src/EventCallbackGate.cpp ) @@ -92,6 +96,17 @@ if(BUILD_TESTS) add_test(NAME echoion_release_manifest_tests COMMAND echoion_release_manifest_tests) + add_executable(echoion_runtime_paths_tests + tests/test_runtime_paths.cpp + src/RuntimePaths.cpp + ) + target_include_directories(echoion_runtime_paths_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + target_compile_features(echoion_runtime_paths_tests PRIVATE cxx_std_26) + add_test(NAME echoion_runtime_paths_tests + COMMAND echoion_runtime_paths_tests) + add_executable(echoion_event_callback_gate_tests tests/test_event_callback_gate.cpp src/EventCallbackGate.cpp diff --git a/include/echoion/standalone/ReleaseManifest.hpp b/include/echoion/standalone/ReleaseManifest.hpp index d68c675..553230d 100644 --- a/include/echoion/standalone/ReleaseManifest.hpp +++ b/include/echoion/standalone/ReleaseManifest.hpp @@ -2,20 +2,40 @@ #include +#include #include #include +#include namespace Echoion::Standalone { - struct ReleaseManifest { - std::string version; - std::filesystem::path executable; - std::filesystem::path core; - std::string executableSha256; - std::string coreSha256; - - [[nodiscard]] static Api::Result - load(const std::filesystem::path& manifestPath); - [[nodiscard]] Api::Result validate() const; + enum class ReleaseFileType : std::uint8_t { + Regular, + Symlink, }; -} + + struct ReleaseFileEntry { + std::filesystem::path path; + ReleaseFileType type{ReleaseFileType::Regular}; + std::uintmax_t size{}; + std::filesystem::perms mode{std::filesystem::perms::unknown}; + std::string sha256; + std::filesystem::path target; + }; + + struct ReleaseManifest { + std::uint32_t schemaVersion{1}; + std::string version; + std::filesystem::path root; + std::filesystem::path executable; + std::filesystem::path core; + std::string executableSha256; + std::string coreSha256; + std::vector files; + + [[nodiscard]] static Api::Result + load(const std::filesystem::path& manifestPath); + [[nodiscard]] Api::Result validate() const; + [[nodiscard]] Api::Result validateInstallLayout() const; + }; +} // namespace Echoion::Standalone diff --git a/include/echoion/standalone/RuntimePaths.hpp b/include/echoion/standalone/RuntimePaths.hpp new file mode 100644 index 0000000..88122a1 --- /dev/null +++ b/include/echoion/standalone/RuntimePaths.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + [[nodiscard]] std::expected + runningExecutablePath(); + + [[nodiscard]] std::filesystem::path deriveInstallRoot( + const std::filesystem::path& executablePath, + const std::optional& homeOverride = + std::nullopt); + + [[nodiscard]] std::filesystem::path resolveCorePath( + const std::filesystem::path& installRoot, + const std::filesystem::path& executableDirectory, + const std::optional& coreOverride = + std::nullopt); + + [[nodiscard]] std::filesystem::path resolveStateDirectory( + const std::optional& commandLineOverride, + const std::optional& environmentOverride, + const std::optional& xdgStateHome, + const std::optional& userHome, + const std::filesystem::path& fallback); + + [[nodiscard]] std::optional runtimeWorkingDirectory( + const std::filesystem::path& installRoot, + const std::filesystem::path& executableDirectory); + + [[nodiscard]] std::expected + resolveAvatarCacheDirectory( + const std::filesystem::path& configuredDirectory, + const std::filesystem::path& requestedDirectory = {}); +} // namespace Echoion::Standalone diff --git a/src/ReleaseManifest.cpp b/src/ReleaseManifest.cpp index 9775af5..f39ff7a 100644 --- a/src/ReleaseManifest.cpp +++ b/src/ReleaseManifest.cpp @@ -5,123 +5,646 @@ #include -#include #include +#include +#include #include #include #include +#include #include +#include +#include namespace Echoion::Standalone { namespace { + constexpr auto kExecutablePermissions = + std::filesystem::perms::owner_exec | + std::filesystem::perms::group_exec | + std::filesystem::perms::others_exec; + constexpr auto kUnsafeWritablePermissions = + std::filesystem::perms::group_write | + std::filesystem::perms::others_write; + constexpr std::array kImmutableRoots{ + "bin", "lib", "service", "share"}; + constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0; + Api::Result sha256(const std::filesystem::path& path) { std::ifstream input(path, std::ios::binary); if (!input) { return Api::fail(Api::ErrorCode::NotFound, - "release artifact not found: " + path.string()); + "release artifact not found: " + + path.string()); } - using Context = std::unique_ptr; + using Context = + std::unique_ptr; Context context(EVP_MD_CTX_new(), &EVP_MD_CTX_free); - if (!context || EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) { + if (!context || + EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) { return Api::fail(Api::ErrorCode::UnknownError, - "cannot initialize SHA-256"); + "cannot initialize SHA-256"); } std::array buffer{}; while (input) { - input.read(buffer.data(), static_cast(buffer.size())); - if (const auto count = input.gcount(); count > 0 && + input.read(buffer.data(), + static_cast(buffer.size())); + if (const auto count = input.gcount(); + count > 0 && EVP_DigestUpdate(context.get(), buffer.data(), - static_cast(count)) != 1) { + static_cast(count)) != 1) { return Api::fail(Api::ErrorCode::UnknownError, - "cannot hash release artifact"); + "cannot hash release artifact"); } } std::array digest{}; - unsigned int size = 0; + unsigned int size{}; if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) { return Api::fail(Api::ErrorCode::UnknownError, - "cannot finalize release hash"); + "cannot finalize release hash"); } std::ostringstream output; output << std::hex << std::setfill('0'); for (unsigned int index = 0; index < size; ++index) { - output << std::setw(2) << static_cast(digest[index]); + output << std::setw(2) + << static_cast(digest[index]); } return output.str(); } - } + + bool isSafeRelativePath(const std::filesystem::path& path) + { + if (path.empty() || path.is_absolute() || path.has_root_name() || + path.filename().empty() || + std::ranges::contains(path.native(), '\0')) { + return false; + } + if (path.generic_string() != + path.lexically_normal().generic_string()) { + return false; + } + return std::ranges::none_of(path, [](const auto& component) { + return component == "." || component == ".."; + }); + } + + bool isSha256(std::string_view value) + { + return value.size() == 64 && + std::ranges::all_of( + value, [](const unsigned char character) { + return (character >= '0' && character <= '9') || + (character >= 'a' && character <= 'f'); + }); + } + + std::optional parseMode(std::string_view value) + { + if (value.size() != 4 || value.front() != '0' || + !std::ranges::all_of(value.substr(1), [](const char character) { + return character >= '0' && character <= '7'; + })) { + return std::nullopt; + } + unsigned int result{}; + for (const char character : value.substr(1)) { + result = + result * 8U + static_cast(character - '0'); + } + return static_cast(result); + } + + std::optional parseSize(const Void::Json::Value& entry) + { + const auto* value = entry.find("size"); + if (!value || !value->is_number()) { + return std::nullopt; + } + const double number = value->as_number(); + if (!std::isfinite(number) || number < 0.0 || + number > kMaximumExactJsonInteger || + std::trunc(number) != number) { + return std::nullopt; + } + return static_cast(number); + } + + std::filesystem::path + normalizedAbsolute(const std::filesystem::path& path) + { + std::error_code error; + auto absolute = std::filesystem::absolute(path, error); + return (error ? path : absolute).lexically_normal(); + } + + bool isWithin(const std::filesystem::path& root, + const std::filesystem::path& candidate) + { + const auto relative = candidate.lexically_relative(root); + return !relative.empty() && !relative.is_absolute() && + std::ranges::none_of(relative, [](const auto& component) { + return component == ".."; + }); + } + + bool hasUnsafeWritablePermissions( + const std::filesystem::file_status& status) + { + return (status.permissions() & kUnsafeWritablePermissions) != + std::filesystem::perms::none; + } + + std::optional + relativeToPayload(const std::filesystem::path& path, + const std::filesystem::path& prefix) + { + if (prefix.empty()) { + return path; + } + const auto relative = path.lexically_relative(prefix); + if (!isSafeRelativePath(relative)) { + return std::nullopt; + } + return relative; + } + + bool isImmutablePayloadPath(const std::filesystem::path& path, + const std::filesystem::path& prefix) + { + const auto relative = relativeToPayload(path, prefix); + if (!relative || relative->empty()) { + return false; + } + return std::ranges::contains(kImmutableRoots, + relative->begin()->generic_string()); + } + + Api::Result + payloadPrefix(const ReleaseManifest& manifest) + { + const auto executable = + manifest.executable.lexically_relative(manifest.root); + if (!isSafeRelativePath(executable) || + executable.filename() != "echoiond" || + executable.parent_path().filename() != "bin") { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "v2 release executable must use the payload " + "bin/echoiond layout"); + } + + const auto prefix = executable.parent_path().parent_path(); + const auto expectedCore = + (manifest.root / prefix / "lib" / "Echoion.ts") + .lexically_normal(); + if (manifest.core.lexically_normal() != expectedCore) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "v2 release Core must use the payload " + "lib/Echoion.ts layout"); + } + return prefix; + } + + Api::Result + validateImmutableCoverage(const ReleaseManifest& manifest) + { + auto prefix = payloadPrefix(manifest); + if (!prefix) { + return std::unexpected(prefix.error()); + } + + std::unordered_set declared; + declared.reserve(manifest.files.size()); + for (const auto& entry : manifest.files) { + if (!isImmutablePayloadPath(entry.path, *prefix)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "release manifest entry is outside the immutable " + "payload roots: " + + entry.path.string()); + } + declared.insert(entry.path.generic_string()); + } + + const auto payloadRoot = manifest.root / *prefix; + std::error_code payloadError; + const auto payloadStatus = + std::filesystem::symlink_status(payloadRoot, payloadError); + if (payloadError || + payloadStatus.type() != std::filesystem::file_type::directory) { + return Api::fail(Api::ErrorCode::NotFound, + "immutable payload root is missing or has an " + "unexpected type: " + + payloadRoot.string()); + } + if (hasUnsafeWritablePermissions(payloadStatus)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "immutable payload directory is group- or " + "world-writable: " + + payloadRoot.string()); + } + + for (const auto name : kImmutableRoots) { + const auto directory = manifest.root / *prefix / name; + std::error_code error; + const auto rootStatus = + std::filesystem::symlink_status(directory, error); + if (error || rootStatus.type() != + std::filesystem::file_type::directory) { + return Api::fail( + Api::ErrorCode::NotFound, + "immutable payload directory is missing or has an " + "unexpected type: " + + directory.string()); + } + if (hasUnsafeWritablePermissions(rootStatus)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "immutable payload directory is group- or " + "world-writable: " + + directory.string()); + } + + std::filesystem::recursive_directory_iterator iterator{ + directory, std::filesystem::directory_options::none, error}; + const std::filesystem::recursive_directory_iterator end; + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "cannot inspect immutable payload directory: " + + directory.string()); + } + while (iterator != end) { + const auto status = iterator->symlink_status(error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "cannot inspect immutable payload entry: " + + iterator->path().string()); + } + if (status.type() == + std::filesystem::file_type::directory) { + if (hasUnsafeWritablePermissions(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "immutable payload directory is group- or " + "world-writable: " + + iterator->path().string()); + } + } else { + const auto relative = + iterator->path().lexically_relative(manifest.root); + if (status.type() != + std::filesystem::file_type::regular && + status.type() != + std::filesystem::file_type::symlink) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "special file is not allowed in " + "immutable payload: " + + relative.string()); + } + if (!declared.contains(relative.generic_string())) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "undeclared immutable payload entry: " + + relative.string()); + } + } + + iterator.increment(error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "cannot traverse immutable payload directory: " + + directory.string()); + } + } + } + return {}; + } + + Api::Result + loadVersionOne(const Void::Json::Value& json, + const std::filesystem::path& root) + { + ReleaseManifest manifest; + manifest.root = root; + manifest.version = json.get_str("version"); + const auto executableEntry = + std::filesystem::path(json.get_str("executable")); + const auto coreEntry = std::filesystem::path(json.get_str("core")); + if (!isSafeRelativePath(executableEntry) || + !isSafeRelativePath(coreEntry)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "release artifact paths must stay within the " + "manifest directory"); + } + manifest.executable = root / executableEntry; + manifest.core = root / coreEntry; + if (const auto* hashes = json.find("sha256"); + hashes && hashes->is_object()) { + manifest.executableSha256 = hashes->get_str("executable"); + manifest.coreSha256 = hashes->get_str("core"); + } + if (manifest.version.empty() || + !isSha256(manifest.executableSha256) || + !isSha256(manifest.coreSha256)) { + return Api::fail(Api::ErrorCode::ParseError, + "release manifest is missing version, " + "artifacts, or hashes"); + } + return manifest; + } + + Api::Result + loadVersionTwo(const Void::Json::Value& json, + const std::filesystem::path& root) + { + ReleaseManifest manifest; + manifest.schemaVersion = 2; + manifest.root = root; + manifest.version = json.get_str("version"); + const auto executableEntry = + std::filesystem::path(json.get_str("executable")); + const auto coreEntry = std::filesystem::path(json.get_str("core")); + const auto* files = json.child_array("files"); + if (manifest.version.empty() || + !isSafeRelativePath(executableEntry) || + !isSafeRelativePath(coreEntry) || !files || + files->as_array().empty()) { + return Api::fail(Api::ErrorCode::ParseError, + "v2 release manifest is missing version, " + "artifacts, or files"); + } + + std::unordered_set paths; + manifest.files.reserve(files->as_array().size()); + for (const auto& value : files->as_array()) { + if (!value.is_object()) { + return Api::fail(Api::ErrorCode::ParseError, + "release file entries must be objects"); + } + ReleaseFileEntry entry; + entry.path = value.get_str("path"); + if (!isSafeRelativePath(entry.path)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "release file path is absolute, " + "traversing, or not normalized"); + } + if (!paths.insert(entry.path.generic_string()).second) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "duplicate release file path: " + + entry.path.string()); + } + + const auto type = value.get_str("type"); + if (type == "file") { + entry.type = ReleaseFileType::Regular; + const auto size = parseSize(value); + const auto mode = parseMode(value.get_str("mode")); + entry.sha256 = value.get_str("sha256"); + if (!size || !mode || !isSha256(entry.sha256) || + value.has("target")) { + return Api::fail(Api::ErrorCode::ParseError, + "regular release file entry has " + "invalid metadata: " + + entry.path.string()); + } + entry.size = *size; + entry.mode = *mode; + if ((entry.mode & kUnsafeWritablePermissions) != + std::filesystem::perms::none) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "release file is group- or " + "world-writable: " + + entry.path.string()); + } + } else if (type == "symlink") { + entry.type = ReleaseFileType::Symlink; + entry.target = value.get_str("target"); + if (!isSafeRelativePath(entry.target) || + value.has("size") || value.has("sha256") || + value.has("mode")) { + return Api::fail( + Api::ErrorCode::ParseError, + "symbolic link entry has invalid metadata: " + + entry.path.string()); + } + } else { + return Api::fail(Api::ErrorCode::ParseError, + "unknown release file type: " + type); + } + manifest.files.push_back(std::move(entry)); + } + + const auto executable = std::ranges::find( + manifest.files, executableEntry, &ReleaseFileEntry::path); + const auto core = std::ranges::find(manifest.files, coreEntry, + &ReleaseFileEntry::path); + if (executable == manifest.files.end() || + core == manifest.files.end() || + executable->type != ReleaseFileType::Regular || + core->type != ReleaseFileType::Regular) { + return Api::fail(Api::ErrorCode::ParseError, + "release executable and Core must reference " + "regular file entries"); + } + if ((executable->mode & kExecutablePermissions) == + std::filesystem::perms::none) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "release executable entry is not executable"); + } + + manifest.executable = root / executableEntry; + manifest.core = root / coreEntry; + manifest.executableSha256 = executable->sha256; + manifest.coreSha256 = core->sha256; + return manifest; + } + } // namespace Api::Result - ReleaseManifest::load(const std::filesystem::path& manifestPath) + ReleaseManifest::load(const std::filesystem::path& manifestPath) { auto contents = Void::FileSystem::read_file(manifestPath); if (!contents) { - return Api::fail(Api::ErrorCode::NotFound, contents.error().message()); + return Api::fail(Api::ErrorCode::NotFound, + contents.error().message()); } auto json = Void::Json::parse(*contents); if (!json || !json->is_object()) { return Api::fail(Api::ErrorCode::ParseError, - json ? "release manifest must be an object" - : "invalid release manifest: " + json.error().message); + json ? "release manifest must be an object" + : "invalid release manifest: " + + json.error().message); } - ReleaseManifest manifest; - manifest.version = json->get_str("version"); - const auto base = manifestPath.parent_path(); - const auto executableEntry = std::filesystem::path( - json->get_str("executable")); - const auto coreEntry = std::filesystem::path(json->get_str("core")); - const auto unsafe = [](const std::filesystem::path& path) { - return path.empty() || path.is_absolute() || - std::ranges::contains(path, std::filesystem::path{".."}); - }; - if (unsafe(executableEntry) || unsafe(coreEntry)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "release artifact paths must stay within the manifest directory"); + + std::error_code error; + auto root = std::filesystem::weakly_canonical( + normalizedAbsolute(manifestPath).parent_path(), error); + if (error) { + return Api::fail(Api::ErrorCode::NotFound, + "cannot resolve release root: " + error.message()); } - manifest.executable = (base / executableEntry).lexically_normal(); - manifest.core = (base / coreEntry).lexically_normal(); - if (const auto* hashes = json->find("sha256")) { - manifest.executableSha256 = hashes->get_str("executable"); - manifest.coreSha256 = hashes->get_str("core"); + + const auto* schema = json->find("schemaVersion"); + if (!schema) { + return loadVersionOne(*json, root); } - if (manifest.version.empty() || manifest.executable.filename().empty() || - manifest.core.filename().empty() || manifest.executableSha256.empty() || - manifest.coreSha256.empty()) { - return Api::fail(Api::ErrorCode::ParseError, - "release manifest is missing version, artifacts, or hashes"); + if (!schema->is_number() || schema->as_number() != 2.0) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "unsupported release manifest schema version"); } - return manifest; + return loadVersionTwo(*json, root); } Api::Result ReleaseManifest::validate() const { - if (!std::filesystem::is_regular_file(executable) || - !std::filesystem::is_regular_file(core)) { + if (schemaVersion == 1) { + std::error_code rootError; + const auto canonicalRoot = + std::filesystem::weakly_canonical(root, rootError); + if (rootError) { + return Api::fail(Api::ErrorCode::NotFound, + "cannot resolve release root: " + + rootError.message()); + } + for (const auto& [path, expected, executableFile] : + {std::tuple{executable, executableSha256, true}, + std::tuple{core, coreSha256, false}}) { + std::error_code error; + const auto status = + std::filesystem::symlink_status(path, error); + if (error || + status.type() != std::filesystem::file_type::regular) { + return Api::fail( + Api::ErrorCode::NotFound, + "release executable and Core must be regular files"); + } + const auto resolved = std::filesystem::canonical(path, error); + if (error || !isWithin(canonicalRoot, resolved)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "release artifact resolves outside the release root: " + + path.string()); + } + if (executableFile && + (status.permissions() & kExecutablePermissions) == + std::filesystem::perms::none) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "release executable is not executable"); + } + auto actual = sha256(path); + if (!actual) { + return std::unexpected(actual.error()); + } + if (*actual != expected) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "SHA-256 mismatch for " + path.string()); + } + } + return {}; + } + + std::error_code rootError; + const auto canonicalRoot = + std::filesystem::weakly_canonical(root, rootError); + if (rootError) { return Api::fail(Api::ErrorCode::NotFound, - "release executable and Core must be regular files"); + "cannot resolve release root: " + + rootError.message()); } - const auto permissions = std::filesystem::status(executable).permissions(); - if ((permissions & (std::filesystem::perms::owner_exec | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_exec)) == std::filesystem::perms::none) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "release executable is not executable"); - } - for (const auto& [path, expected] : - {std::pair{executable, executableSha256}, - std::pair{core, coreSha256}}) { + for (const auto& entry : files) { + const auto path = root / entry.path; + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error || + status.type() == std::filesystem::file_type::not_found) { + return Api::fail(Api::ErrorCode::NotFound, + "release payload entry is missing: " + + entry.path.string()); + } + const auto expectedType = entry.type == ReleaseFileType::Regular + ? std::filesystem::file_type::regular + : std::filesystem::file_type::symlink; + if (status.type() != expectedType) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "unexpected file type for release payload entry: " + + entry.path.string()); + } + + const auto resolved = std::filesystem::canonical(path, error); + if (error || !isWithin(canonicalRoot, resolved)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "release payload entry resolves outside the " + "release root: " + + entry.path.string()); + } + + if (entry.type == ReleaseFileType::Symlink) { + const auto actualTarget = + std::filesystem::read_symlink(path, error); + if (error || actualTarget.generic_string() != + entry.target.generic_string()) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "symbolic link target mismatch for " + + entry.path.string()); + } + continue; + } + + const auto size = std::filesystem::file_size(path, error); + if (error || size != entry.size) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "file size mismatch for " + + entry.path.string()); + } + if ((status.permissions() & std::filesystem::perms::mask) != + entry.mode) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "file mode mismatch for " + + entry.path.string()); + } auto actual = sha256(path); if (!actual) { return std::unexpected(actual.error()); } - if (*actual != expected) { + if (*actual != entry.sha256) { return Api::fail(Api::ErrorCode::IncompatibleVersion, - "SHA-256 mismatch for " + path.string()); + "SHA-256 mismatch for " + entry.path.string()); } } + return validateImmutableCoverage(*this); + } + + Api::Result ReleaseManifest::validateInstallLayout() const + { + if (schemaVersion != 2) { + return Api::fail( + Api::ErrorCode::IncompatibleVersion, + "installation validation requires a v2 release manifest"); + } + if (auto result = validate(); !result) { + return result; + } + + const std::filesystem::path expectedExecutable{"bin/echoiond"}; + const std::filesystem::path expectedCore{"lib/Echoion.ts"}; + const std::filesystem::path expectedWeb{"share/echoion/web/index.html"}; + if (executable.lexically_normal() != (root / expectedExecutable) || + core.lexically_normal() != (root / expectedCore)) { + return Api::fail(Api::ErrorCode::IncompatibleVersion, + "installation manifest does not describe the " + "canonical runtime layout"); + } + const auto web = + std::ranges::find(files, expectedWeb, &ReleaseFileEntry::path); + if (web == files.end() || web->type != ReleaseFileType::Regular) { + return Api::fail(Api::ErrorCode::NotFound, + "installation manifest is missing the web " + "dashboard entry point"); + } return {}; } -} +} // namespace Echoion::Standalone diff --git a/src/RuntimePaths.cpp b/src/RuntimePaths.cpp new file mode 100644 index 0000000..7996086 --- /dev/null +++ b/src/RuntimePaths.cpp @@ -0,0 +1,178 @@ +#include "echoion/standalone/RuntimePaths.hpp" + +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + namespace + { + std::filesystem::path absoluteNormalized(std::filesystem::path path) + { + std::error_code error; + auto absolute = std::filesystem::absolute(path, error); + if (error) { + return path.lexically_normal(); + } + return absolute.lexically_normal(); + } + + bool isWithinOrEqual(const std::filesystem::path& root, + const std::filesystem::path& candidate) + { + const auto relative = candidate.lexically_relative(root); + return !relative.empty() && !relative.is_absolute() && + std::ranges::none_of(relative, [](const auto& component) { + return component == ".."; + }); + } + } // namespace + + std::expected runningExecutablePath() + { + std::error_code error; + auto executable = + std::filesystem::read_symlink("/proc/self/exe", error); + if (error || executable.empty()) { + return std::unexpected("cannot resolve /proc/self/exe: " + + error.message()); + } + auto canonical = std::filesystem::weakly_canonical(executable, error); + if (error) { + return absoluteNormalized(std::move(executable)); + } + return canonical; + } + + std::filesystem::path deriveInstallRoot( + const std::filesystem::path& executablePath, + const std::optional& homeOverride) + { + if (homeOverride && !homeOverride->empty()) { + return absoluteNormalized(*homeOverride); + } + + const auto executableDirectory = + absoluteNormalized(executablePath).parent_path(); + if (executableDirectory.filename() == "bin") { + return executableDirectory.parent_path(); + } + return executableDirectory; + } + + std::filesystem::path resolveCorePath( + const std::filesystem::path& installRoot, + const std::filesystem::path& executableDirectory, + const std::optional& coreOverride) + { + if (coreOverride && !coreOverride->empty()) { + return coreOverride->is_absolute() + ? coreOverride->lexically_normal() + : (installRoot / *coreOverride).lexically_normal(); + } + + const std::array candidates{ + installRoot / "lib" / "Echoion.ts", + executableDirectory / "Echoion.ts", + installRoot / "bin" / "Echoion.ts", + installRoot / "plugins" / "Echoion.ts", + }; + for (const auto& candidate : candidates) { + std::error_code error; + if (std::filesystem::is_regular_file(candidate, error) && !error) { + return candidate.lexically_normal(); + } + } + return candidates.front().lexically_normal(); + } + + std::filesystem::path resolveStateDirectory( + const std::optional& commandLineOverride, + const std::optional& environmentOverride, + const std::optional& xdgStateHome, + const std::optional& userHome, + const std::filesystem::path& fallback) + { + if (commandLineOverride && !commandLineOverride->empty()) { + return absoluteNormalized(*commandLineOverride); + } + if (environmentOverride && !environmentOverride->empty()) { + return absoluteNormalized(*environmentOverride); + } + if (xdgStateHome && !xdgStateHome->empty()) { + return absoluteNormalized(*xdgStateHome / "echoion"); + } + if (userHome && !userHome->empty()) { + return absoluteNormalized(*userHome / ".local" / "state" / + "echoion"); + } + return absoluteNormalized(fallback); + } + + std::optional runtimeWorkingDirectory( + const std::filesystem::path& installRoot, + const std::filesystem::path& executableDirectory) + { + const auto packagedDirectory = installRoot / "share" / "echoion"; + std::error_code error; + if (std::filesystem::is_regular_file( + packagedDirectory / "web" / "index.html", error) && + !error) { + return packagedDirectory; + } + + error.clear(); + if (std::filesystem::is_regular_file( + executableDirectory / "web" / "index.html", error) && + !error) { + return executableDirectory; + } + return std::nullopt; + } + + std::expected + resolveAvatarCacheDirectory( + const std::filesystem::path& configuredDirectory, + const std::filesystem::path& requestedDirectory) + { + if (configuredDirectory.empty()) { + return std::unexpected("avatar cache directory is not configured"); + } + + std::error_code error; + const auto configured = std::filesystem::weakly_canonical( + absoluteNormalized(configuredDirectory), error); + if (error) { + return std::unexpected("cannot resolve avatar cache directory: " + + error.message()); + } + + if (!requestedDirectory.empty() && !requestedDirectory.is_absolute() && + (requestedDirectory != requestedDirectory.lexically_normal() || + std::ranges::any_of(requestedDirectory, [](const auto& component) { + return component == "." || component == ".."; + }))) { + return std::unexpected("avatar cache subdirectory must be " + "normalized and non-traversing"); + } + + const auto requested = requestedDirectory.empty() ? configured + : requestedDirectory.is_absolute() + ? requestedDirectory + : configured / requestedDirectory; + const auto resolved = std::filesystem::weakly_canonical( + absoluteNormalized(requested), error); + if (error) { + return std::unexpected( + "cannot resolve requested avatar directory: " + + error.message()); + } + if (!isWithinOrEqual(configured, resolved)) { + return std::unexpected("requested avatar directory is outside the " + "configured state cache"); + } + return resolved; + } +} // namespace Echoion::Standalone diff --git a/src/StandaloneClientInterface.cpp b/src/StandaloneClientInterface.cpp index 8a3b809..915d6be 100644 --- a/src/StandaloneClientInterface.cpp +++ b/src/StandaloneClientInterface.cpp @@ -1,5 +1,6 @@ #include "echoion/standalone/AudioEncoder.hpp" #include "echoion/standalone/MessageChunker.hpp" +#include "echoion/standalone/RuntimePaths.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" #include @@ -659,16 +660,19 @@ namespace Echoion::Standalone return Api::fail(Api::ErrorCode::ParseError, "server returned an unsafe avatar hash"); } - const auto directory = - destDir.empty() ? settings_.avatarCachePath : destDir; + const auto directory = resolveAvatarCacheDirectory( + settings_.avatarCachePath, std::filesystem::path{destDir}); + if (!directory) { + return Api::fail(Api::ErrorCode::InvalidArgument, + directory.error()); + } std::error_code directoryError; - std::filesystem::create_directories(directory, directoryError); + std::filesystem::create_directories(*directory, directoryError); if (directoryError) { return Api::fail(Api::ErrorCode::PluginError, "cannot create avatar cache directory"); } - const auto destination = - (std::filesystem::path(directory) / ("avatar_" + hash)).string(); + const auto destination = (*directory / ("avatar_" + hash)).string(); if (!std::filesystem::exists(destination)) { const auto result = client_->download("/avatar_" + hash, destination); diff --git a/src/main.cpp b/src/main.cpp index 2acb628..983cc14 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,6 +3,7 @@ #include "echoion/host/CoreLoader.hpp" #include "echoion/standalone/ReleaseManifest.hpp" +#include "echoion/standalone/RuntimePaths.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" #include @@ -25,6 +26,8 @@ #include #include #include +#include +#include namespace { @@ -56,6 +59,48 @@ namespace return std::nullopt; } + bool hasArgument(int argc, char** argv, std::string_view name) + { + for (int index = 1; index < argc; ++index) { + if (std::string_view{argv[index]} == name) { + return true; + } + } + return false; + } + + std::optional + optionalArgumentPath(int argc, char** argv, std::string_view name) + { + for (int index = 1; index < argc; ++index) { + if (std::string_view{argv[index]} != name) { + continue; + } + if (index + 1 < argc && + !std::string_view{argv[index + 1]}.starts_with("--")) { + return std::filesystem::path{argv[index + 1]}; + } + return std::nullopt; + } + return std::nullopt; + } + + std::optional environmentPath(const char* name) + { + const char* value = std::getenv(name); + if (!value || std::string_view{value}.empty()) { + return std::nullopt; + } + return std::filesystem::path{value}; + } + + std::filesystem::path absolutePath(const std::filesystem::path& path) + { + std::error_code error; + auto absolute = std::filesystem::absolute(path, error); + return (error ? path : absolute).lexically_normal(); + } + std::filesystem::path configDir() { if (const char* x = std::getenv("XDG_CONFIG_HOME")) { @@ -67,6 +112,60 @@ namespace return std::filesystem::path(".") / "echoion"; } + bool prepareStateDirectory(const std::filesystem::path& stateDirectory, + bool explicitlySelected) + { + std::error_code error; + std::filesystem::create_directories(stateDirectory, error); + if (error) { + std::cerr << "Cannot create state directory " << stateDirectory + << ": " << error.message() << '\n'; + return false; + } + + const auto setPath = [](const char* name, + const std::filesystem::path& path, + bool overwrite) { + const auto value = path.string(); + return ::setenv(name, value.c_str(), overwrite ? 1 : 0) == 0; + }; + const auto temporaryDirectory = stateDirectory / "tmp"; + std::filesystem::create_directories(temporaryDirectory, error); + if (error) { + std::cerr << "Cannot create temporary directory " + << temporaryDirectory << ": " << error.message() << '\n'; + return false; + } + if (!setPath("ECHOION_STATE_DIR", stateDirectory, true) || + !setPath("XDG_CACHE_HOME", stateDirectory / "cache", + explicitlySelected) || + !setPath("XDG_STATE_HOME", stateDirectory / "state", + explicitlySelected) || + !setPath("XDG_DATA_HOME", stateDirectory / "data", + explicitlySelected) || + !setPath("TMPDIR", temporaryDirectory, explicitlySelected)) { + std::cerr << "Cannot export runtime state paths\n"; + return false; + } + return true; + } + + int validateInstall(const std::filesystem::path& installRoot) + { + auto manifest = Echoion::Standalone::ReleaseManifest::load( + installRoot / "manifest.json"); + if (!manifest) { + std::cerr << manifest.error().message << '\n'; + return 2; + } + if (auto result = manifest->validateInstallLayout(); !result) { + std::cerr << result.error().message << '\n'; + return 2; + } + std::cout << "Echoion installation is valid: " << installRoot << '\n'; + return 0; + } + void recordInterruptedRelease(const std::filesystem::path& directory) { const auto transaction = directory / "release-transaction"; @@ -105,21 +204,6 @@ namespace } } - // Locate the Core shared library ("Echoion.ts"). - std::filesystem::path corePath() - { - if (const char* p = std::getenv("ECHOION_CORE_PATH")) { - return p; - } - for (const char* c : - {"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) { - if (std::filesystem::exists(c)) { - return c; - } - } - return "./Echoion.ts"; - } - int importIdentity(int argc, char** argv, const std::filesystem::path& defaultIdentityPath) { @@ -130,9 +214,11 @@ namespace for (int i = 1; i < argc; ++i) { const std::string_view argument{argv[i]}; if (argument == "--help") { - std::cout << "Usage: echoiond [--config PATH]\n" - " echoiond --import-identity EXPORT.ini " - "[--identity-path PATH] [--force]\n"; + std::cout + << "Usage: echoiond [--config PATH] [--state-dir PATH]\n" + " echoiond --import-identity EXPORT.ini " + "[--identity-path PATH] [--force]\n" + " echoiond --validate-install [ROOT]\n"; return 0; } if (argument == "--import-identity") { @@ -184,8 +270,14 @@ int main(int argc, char** argv) std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n'; std::abort(); }); - if (const auto validationPath = - argumentValue(argc, argv, "--validate-release")) { + + if (hasArgument(argc, argv, "--validate-release")) { + const auto validationPath = + argumentValue(argc, argv, "--validate-release"); + if (!validationPath || validationPath->starts_with("--")) { + std::cerr << "--validate-release requires a manifest path\n"; + return 2; + } auto manifest = Echoion::Standalone::ReleaseManifest::load(*validationPath); if (!manifest) { @@ -199,25 +291,70 @@ int main(int argc, char** argv) return 0; } - std::filesystem::path cfgDir = configDir(); - recordInterruptedRelease(cfgDir); + const auto runningExecutable = Echoion::Standalone::runningExecutablePath(); + if (!runningExecutable) { + std::cerr << runningExecutable.error() << '\n'; + return 2; + } + const auto installRoot = Echoion::Standalone::deriveInstallRoot( + *runningExecutable, environmentPath("ECHOION_HOME")); + if (hasArgument(argc, argv, "--validate-install")) { + const auto requestedRoot = + optionalArgumentPath(argc, argv, "--validate-install"); + return validateInstall(requestedRoot ? absolutePath(*requestedRoot) + : installRoot); + } + const auto installRootString = installRoot.string(); + if (::setenv("ECHOION_HOME", installRootString.c_str(), 1) != 0) { + std::cerr << "Cannot export ECHOION_HOME\n"; + return 2; + } + for (const std::string_view requiredValue : {"--config", "--state-dir"}) { + if (hasArgument(argc, argv, requiredValue) && + !optionalArgumentPath(argc, argv, requiredValue)) { + std::cerr << requiredValue << " requires a path\n"; + return 2; + } + } + + const auto cfgDir = absolutePath(configDir()); std::filesystem::path cfgPath = cfgDir / "config.json"; - const auto identityPath = std::filesystem::path( - envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string())); + if (const auto requestedConfig = + optionalArgumentPath(argc, argv, "--config")) { + cfgPath = absolutePath(*requestedConfig); + } + const auto commandLineState = + optionalArgumentPath(argc, argv, "--state-dir"); + const auto environmentState = environmentPath("ECHOION_STATE_DIR"); + const auto stateDirectory = Echoion::Standalone::resolveStateDirectory( + commandLineState, environmentState, environmentPath("XDG_STATE_HOME"), + environmentPath("HOME"), cfgDir); + if (!prepareStateDirectory(stateDirectory, + commandLineState.has_value() || + environmentState.has_value())) { + return 2; + } + recordInterruptedRelease(stateDirectory); + + const auto identityPath = absolutePath(std::filesystem::path(envOr( + "ECHOION_IDENTITY_PATH", (stateDirectory / "identity.txt").string()))); if (const auto importResult = importIdentity(argc, argv, identityPath); importResult >= 0) { return importResult; } - // Optional CLI: --config - for (int i = 1; i + 1 < argc; ++i) { - if (std::string(argv[i]) == "--config") { - cfgPath = argv[i + 1]; - } - } + const auto requestedRestore = + optionalArgumentPath(argc, argv, "--restore-state"); + const std::optional restorePath = + requestedRestore ? std::optional{absolutePath(*requestedRestore)} + : std::nullopt; + const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST"); + const std::optional releaseManifestPath = + requestedManifest ? std::optional{absolutePath(*requestedManifest)} + : std::nullopt; Echoion::Standalone::StandaloneSettings settings; settings.identityPath = identityPath.string(); - settings.avatarCachePath = (cfgDir / "avatars").string(); + settings.avatarCachePath = (stateDirectory / "avatars").string(); settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); @@ -233,13 +370,27 @@ int main(int argc, char** argv) Echoion::Host::CoreLoader loader; loader.setConfigPath(cfgPath); - auto corePathResolved = corePath(); + const auto executableDirectory = runningExecutable->parent_path(); + const auto corePathResolved = Echoion::Standalone::resolveCorePath( + installRoot, executableDirectory, environmentPath("ECHOION_CORE_PATH")); + if (const auto workingDirectory = + Echoion::Standalone::runtimeWorkingDirectory(installRoot, + executableDirectory)) { + std::error_code error; + std::filesystem::current_path(*workingDirectory, error); + if (error) { + Void::Log::error("main", + "cannot select runtime asset directory {}: {}", + workingDirectory->string(), error.message()); + return 1; + } + } Void::Log::info("main", "Loading Core from {}", corePathResolved.string()); if (auto r = loader.load(corePathResolved); !r) { Void::Log::error("main", "failed to load Core: {}", r.error().message); return 1; } - if (const auto restorePath = argumentValue(argc, argv, "--restore-state")) { + if (restorePath) { if (auto result = loader.restoreCheckpoint(*restorePath); !result) { Void::Log::error("main", "failed to restore restart checkpoint: {}", result.error().message); @@ -274,9 +425,7 @@ int main(int argc, char** argv) core->triggerAutoConnect(); std::unique_ptr releaseWatcher; - std::optional releaseManifestPath; - if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) { - releaseManifestPath = manifest; + if (releaseManifestPath) { releaseWatcher = std::make_unique(); releaseWatcher->watch( *releaseManifestPath, @@ -287,21 +436,27 @@ int main(int argc, char** argv) }); Void::Log::info("main", "Watching release manifest {}", releaseManifestPath->string()); - } else { + } else if (!std::filesystem::is_regular_file(installRoot / + "manifest.json")) { // Compatibility mode for development. Production release bundles use // transactional daemon re-exec instead of replacing Core in isolation. loader.enableAutoReload(); + } else { + Void::Log::info( + "main", "{}", + "Core auto-reload is disabled for an installed release payload"); } std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { + std::ignore = Void::FileSystem::atomic_write( + stateDirectory / "release-health", version); + std::ignore = Void::FileSystem::remove_path(stateDirectory / + "release-transaction"); std::ignore = - Void::FileSystem::atomic_write(cfgDir / "release-health", version); - std::ignore = - Void::FileSystem::remove_path(cfgDir / "release-transaction"); - std::ignore = Void::FileSystem::remove_path(cfgDir / "failed-release"); + Void::FileSystem::remove_path(stateDirectory / "failed-release"); ::unsetenv("ECHOION_REEXEC_VERSION"); Void::Log::info("main", "Release {} passed startup health check", version); @@ -327,7 +482,7 @@ int main(int argc, char** argv) continue; } if (auto failed = - Void::FileSystem::read_file(cfgDir / "failed-release"); + Void::FileSystem::read_file(stateDirectory / "failed-release"); failed && *failed == manifest->version) { Void::Log::error("main", "Release {} was previously rolled back; publish a " @@ -335,17 +490,17 @@ int main(int argc, char** argv) manifest->version); continue; } - auto executable = std::filesystem::canonical("/proc/self/exe"); auto validation = Void::Process::run( - executable, {"--validate-release", releaseManifestPath->string()}, - {}, std::chrono::seconds{30}); + *runningExecutable, + {"--validate-release", releaseManifestPath->string()}, {}, + std::chrono::seconds{30}); if (!validation || validation->exit_code != 0) { Void::Log::error("main", "release validation failed: {}", validation ? validation->err : validation.error().message()); continue; } - checkpointPath = configDir() / "restart-state.bin"; + checkpointPath = stateDirectory / "restart-state.bin"; if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) { Void::Log::error("main", "release checkpoint failed: {}", checkpoint.error().message); @@ -365,14 +520,24 @@ int main(int argc, char** argv) (void)interface->shutdown(); if (pendingRelease) { if (auto transaction = Void::FileSystem::atomic_write( - cfgDir / "release-transaction", pendingRelease->version); + stateDirectory / "release-transaction", + pendingRelease->version); !transaction) { Void::Log::error("main", "cannot record release transaction: {}", transaction.error().message()); return 1; } - ::setenv("ECHOION_CORE_PATH", pendingRelease->core.c_str(), 1); - ::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(), 1); + const auto pendingRoot = + Echoion::Standalone::deriveInstallRoot(pendingRelease->executable); + const auto pendingRootString = pendingRoot.string(); + const auto pendingCoreString = pendingRelease->core.string(); + if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 || + ::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 || + ::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(), + 1) != 0) { + Void::Log::error("main", "cannot export pending release paths"); + return 1; + } std::vector arguments; arguments.reserve(static_cast(argc) + 2); for (int index = 1; index < argc; ++index) { diff --git a/tests/test_core_loader_reload.cpp b/tests/test_core_loader_reload.cpp index 6461392..f3b75ef 100644 --- a/tests/test_core_loader_reload.cpp +++ b/tests/test_core_loader_reload.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace @@ -13,21 +14,26 @@ namespace std::cerr << message << '\n'; return 1; } -} +} // namespace int main() { const auto root = std::filesystem::temp_directory_path() / - ("echoion-core-reload-" + std::to_string(::getpid())); + ("echoion-core-reload-" + std::to_string(::getpid())); std::filesystem::create_directories(root); const auto cleanup = [&root] { std::error_code ec; + std::filesystem::permissions(root / "immutable-lib", + std::filesystem::perms::owner_all, + std::filesystem::perm_options::add, ec); std::filesystem::remove_all(root, ec); }; ::setenv("XDG_CONFIG_HOME", root.c_str(), 1); ::setenv("XDG_CACHE_HOME", root.c_str(), 1); ::setenv("HOME", root.c_str(), 1); + const auto stateDirectory = root / "runtime-state"; + ::setenv("ECHOION_STATE_DIR", stateDirectory.c_str(), 1); const auto ytDlp = root / ".local/share/echoion/yt-dlp/yt-dlp"; std::filesystem::create_directories(ytDlp.parent_path()); { @@ -35,9 +41,9 @@ int main() output << "#!/bin/sh\necho 2026.01.01\n"; } std::filesystem::permissions(ytDlp, - std::filesystem::perms::owner_read | - std::filesystem::perms::owner_write | - std::filesystem::perms::owner_exec); + std::filesystem::perms::owner_read | + std::filesystem::perms::owner_write | + std::filesystem::perms::owner_exec); const auto config = root / "config.json"; { std::ofstream output{config}; @@ -49,8 +55,27 @@ int main() })"; } - const auto corePath = root / "Echoion.ts"; + const auto coreDirectory = root / "immutable-lib"; + std::filesystem::create_directories(coreDirectory); + const auto corePath = coreDirectory / "Echoion.ts"; std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath); + const auto directoryEntries = [&coreDirectory] { + std::set entries; + for (const auto& entry : + std::filesystem::directory_iterator{coreDirectory}) { + entries.insert(entry.path().filename()); + } + return entries; + }; + const auto entriesBeforeLoad = directoryEntries(); + std::filesystem::permissions(coreDirectory, + std::filesystem::perms::owner_read | + std::filesystem::perms::owner_exec | + std::filesystem::perms::group_read | + std::filesystem::perms::group_exec | + std::filesystem::perms::others_read | + std::filesystem::perms::others_exec, + std::filesystem::perm_options::replace); Echoion::Host::CoreLoader loader; loader.setConfigPath(config); @@ -58,11 +83,41 @@ int main() cleanup(); return fail(result.error().message.c_str()); } + if (directoryEntries() != entriesBeforeLoad) { + cleanup(); + return fail( + "initial Core load wrote into the immutable library directory"); + } + loader.enableAutoReload(); + if (loader.isAutoReloadEnabled()) { + cleanup(); + return fail("auto-reload was enabled for a read-only Core directory"); + } + std::filesystem::permissions(coreDirectory, + std::filesystem::perms::owner_all | + std::filesystem::perms::group_read | + std::filesystem::perms::group_exec | + std::filesystem::perms::others_read | + std::filesystem::perms::others_exec, + std::filesystem::perm_options::replace); + loader.enableAutoReload(); + if (!loader.isAutoReloadEnabled()) { + cleanup(); + return fail( + "auto-reload was not enabled for a writable development Core"); + } + loader.disableAutoReload(); const auto before = loader.getCore(); if (!before) { cleanup(); return fail("Core missing after initial load"); } + if (!std::filesystem::is_regular_file(stateDirectory / "echoion.db") || + std::filesystem::exists(root / "echoion.db") || + !std::filesystem::is_directory(stateDirectory / "logs")) { + cleanup(); + return fail("Core mutable files did not use ECHOION_STATE_DIR"); + } if (auto result = loader.hotReload(corePath); !result) { cleanup(); return fail(result.error().message.c_str()); @@ -84,7 +139,8 @@ int main() return fail("invalid replacement unexpectedly activated"); } const auto retained = loader.getCore(); - if (!retained || retained.get() != after.get() || !retained->isInitialized()) { + if (!retained || retained.get() != after.get() || + !retained->isInitialized()) { cleanup(); return fail("running Core was not retained after failed activation"); } diff --git a/tests/test_release_manifest.cpp b/tests/test_release_manifest.cpp index 64ce918..43de15c 100644 --- a/tests/test_release_manifest.cpp +++ b/tests/test_release_manifest.cpp @@ -3,36 +3,287 @@ #include #include +#include +#include #include +#include +#include +#include +#include + +namespace +{ + constexpr std::string_view kAbcSha256 = + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + std::string fileEntry(std::string_view path, std::uintmax_t size, + std::string_view mode, + std::string_view sha256 = kAbcSha256) + { + return "{\"path\":\"" + std::string(path) + + "\",\"type\":\"file\",\"size\":" + std::to_string(size) + + ",\"mode\":\"" + std::string(mode) + "\",\"sha256\":\"" + + std::string(sha256) + "\"}"; + } + + std::string symlinkEntry(std::string_view path, std::string_view target) + { + return "{\"path\":\"" + std::string(path) + + "\",\"type\":\"symlink\",\"target\":\"" + std::string(target) + + "\"}"; + } + + std::string manifest(std::vector entries, + std::string_view executable = "bin/echoiond", + std::string_view core = "lib/Echoion.ts") + { + std::string files; + for (const auto& entry : entries) { + if (!files.empty()) { + files += ','; + } + files += entry; + } + return "{\"schemaVersion\":2,\"version\":\"1.2.3\"," + "\"executable\":\"" + + std::string(executable) + "\",\"core\":\"" + std::string(core) + + "\",\"files\":[" + files + "]}"; + } + + bool writeFile(const std::filesystem::path& path, std::string_view contents, + std::filesystem::perms permissions) + { + std::filesystem::create_directories(path.parent_path()); + if (auto result = Void::FileSystem::atomic_write(path, contents); + !result) { + std::cerr << result.error().message() << '\n'; + return false; + } + std::error_code error; + std::filesystem::permissions( + path, permissions, std::filesystem::perm_options::replace, error); + if (error) { + std::cerr << error.message() << '\n'; + return false; + } + return true; + } +} // namespace int main() { + int failures{}; + const auto check = [&failures](bool condition, std::string_view message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + auto directory = Void::FileSystem::TempDir::open("echoion-manifest-test"); if (!directory) { std::cerr << directory.error().message() << '\n'; return 1; } - const auto manifestPath = directory->path() / "pending.json"; - const std::string traversal = R"({ - "version":"bad", - "executable":"../echoiond", - "core":"release/Echoion.ts", - "sha256":{"executable":"x","core":"y"} - })"; - if (auto written = Void::FileSystem::atomic_write(manifestPath, traversal); - !written) { - std::cerr << written.error().message() << '\n'; + const auto root = directory->path(); + const auto manifestPath = root / "manifest.json"; + const auto executablePath = root / "bin" / "echoiond"; + const auto corePath = root / "lib" / "Echoion.ts"; + const auto webPath = root / "share" / "echoion" / "web" / "index.html"; + const auto servicePath = root / "service" / "echoion.service.in"; + const auto aliasPath = root / "lib" / "libEchoionCore.so"; + const auto otherPath = root / "lib" / "Other.so"; + const auto executableMode = std::filesystem::perms::owner_read | + std::filesystem::perms::owner_write | + std::filesystem::perms::owner_exec | + std::filesystem::perms::group_read | + std::filesystem::perms::group_exec | + std::filesystem::perms::others_read | + std::filesystem::perms::others_exec; + const auto regularMode = std::filesystem::perms::owner_read | + std::filesystem::perms::owner_write | + std::filesystem::perms::group_read | + std::filesystem::perms::others_read; + + if (!writeFile(executablePath, "abc", executableMode) || + !writeFile(corePath, "abc", regularMode) || + !writeFile(webPath, "abc", regularMode) || + !writeFile(servicePath, "abc", regularMode) || + !writeFile(otherPath, "abc", regularMode)) { return 1; } - if (Echoion::Standalone::ReleaseManifest::load(manifestPath)) { - std::cerr << "path traversal manifest was accepted\n"; + std::error_code error; + std::filesystem::create_symlink("Echoion.ts", aliasPath, error); + if (error) { + std::cerr << error.message() << '\n'; return 1; } - if (auto written = Void::FileSystem::atomic_write(manifestPath, "{}"); - !written) return 1; - if (Echoion::Standalone::ReleaseManifest::load(manifestPath)) { - std::cerr << "incomplete manifest was accepted\n"; + + const auto validManifest = manifest({ + fileEntry("bin/echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0644"), + fileEntry("lib/Other.so", 3, "0644"), + fileEntry("service/echoion.service.in", 3, "0644"), + fileEntry("share/echoion/web/index.html", 3, "0644"), + symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"), + }); + check( + Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(), + "failed to write valid manifest"); + auto loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath); + check(loaded.has_value(), "valid v2 manifest was rejected while loading"); + if (loaded) { + check(loaded->validate().has_value(), + "valid v2 manifest payload was rejected"); + check(loaded->validateInstallLayout().has_value(), + "valid canonical install layout was rejected"); + + const auto undeclaredFile = root / "lib" / "undeclared.so"; + check(writeFile(undeclaredFile, "abc", regularMode), + "failed to create undeclared regular-file fixture"); + check(!loaded->validate(), + "undeclared regular file in immutable payload was accepted"); + std::filesystem::remove(undeclaredFile, error); + + const auto undeclaredLink = root / "lib" / "undeclared-link.so"; + std::filesystem::create_symlink("Echoion.ts", undeclaredLink, error); + check(!error, "failed to create undeclared symbolic-link fixture"); + check(!loaded->validate(), + "undeclared symbolic link in immutable payload was accepted"); + std::filesystem::remove(undeclaredLink, error); + + const auto specialFile = root / "lib" / "unexpected.fifo"; + check(::mkfifo(specialFile.c_str(), 0600) == 0, + "failed to create special-file fixture"); + check(!loaded->validate(), + "special file in immutable payload was accepted"); + std::filesystem::remove(specialFile, error); + + check(writeFile(root / "data" / "mutable-state", "abc", regularMode), + "failed to create mutable-root fixture"); + check(loaded->validate().has_value(), + "mutable file outside immutable payload roots was rejected"); + + std::filesystem::permissions(root / "lib", std::filesystem::perms::all, + std::filesystem::perm_options::replace, + error); + check(!error, "failed to make immutable directory writable"); + check(!loaded->validate(), + "world-writable immutable directory was accepted"); + std::filesystem::permissions(root / "lib", + std::filesystem::perms::owner_all | + std::filesystem::perms::group_read | + std::filesystem::perms::group_exec | + std::filesystem::perms::others_read | + std::filesystem::perms::others_exec, + std::filesystem::perm_options::replace, + error); + check(!error, "failed to restore immutable directory mode"); + } + + const auto expectLoadFailure = [&](const std::string& contents, + std::string_view message) { + check( + Void::FileSystem::atomic_write(manifestPath, contents).has_value(), + "failed to write invalid manifest fixture"); + check(!Echoion::Standalone::ReleaseManifest::load(manifestPath), + message); + }; + expectLoadFailure(manifest({fileEntry("../echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0644")}, + "../echoiond"), + "path traversal manifest was accepted"); + expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"), + fileEntry("bin/echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0644")}), + "duplicate payload path was accepted"); + expectLoadFailure( + manifest({fileEntry("bin/echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0644"), + symlinkEntry("lib/escape.so", "../outside.so")}), + "traversing symbolic link target was accepted"); + expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0777"), + fileEntry("lib/Echoion.ts", 3, "0644")}), + "world-writable executable metadata was accepted"); + expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0666")}), + "world-writable non-executable metadata was accepted"); + check(writeFile(root / "outside.dat", "abc", regularMode), + "failed to create outside-root manifest fixture"); + const auto outsideManifest = manifest({ + fileEntry("bin/echoiond", 3, "0755"), + fileEntry("lib/Echoion.ts", 3, "0644"), + fileEntry("lib/Other.so", 3, "0644"), + fileEntry("service/echoion.service.in", 3, "0644"), + fileEntry("share/echoion/web/index.html", 3, "0644"), + symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"), + fileEntry("outside.dat", 3, "0644"), + }); + check(Void::FileSystem::atomic_write(manifestPath, outsideManifest) + .has_value(), + "failed to write outside-root manifest"); + const auto outside = + Echoion::Standalone::ReleaseManifest::load(manifestPath); + check(outside.has_value() && !outside->validate(), + "manifest entry outside immutable roots was accepted"); + expectLoadFailure("{\"schemaVersion\":3,\"version\":\"future\"}", + "unsupported schema version was accepted"); + + check( + Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(), + "failed to restore valid manifest"); + loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath); + if (!loaded) { + std::cerr << "could not reload valid manifest\n"; return 1; } - return 0; + { + std::ofstream output(corePath, std::ios::trunc); + output << "xyz"; + } + check(!loaded->validate(), "tampered payload hash was accepted"); + check(writeFile(corePath, "abc", regularMode), + "failed to restore Core fixture"); + + std::filesystem::permissions(corePath, std::filesystem::perms::owner_read, + std::filesystem::perm_options::replace, error); + check(!error, "failed to modify Core permissions fixture"); + check(!loaded->validate(), "payload mode mismatch was accepted"); + std::filesystem::permissions(corePath, regularMode, + std::filesystem::perm_options::replace, error); + + std::filesystem::remove(aliasPath, error); + std::filesystem::create_symlink("Other.so", aliasPath, error); + check(!error, "failed to replace symbolic link fixture"); + check(!loaded->validate(), "symbolic link target mismatch was accepted"); + std::filesystem::remove(aliasPath, error); + check(writeFile(aliasPath, "abc", regularMode), + "failed to create wrong-type fixture"); + check(!loaded->validate(), "unexpected regular-file type was accepted"); + std::filesystem::remove(aliasPath, error); + std::filesystem::create_symlink("Echoion.ts", aliasPath, error); + + std::filesystem::remove(webPath, error); + check(!loaded->validate(), "missing payload entry was accepted"); + check(writeFile(webPath, "abc", regularMode), + "failed to restore web fixture"); + + const std::string legacyManifest = + "{\"version\":\"legacy\",\"executable\":\"bin/echoiond\"," + "\"core\":\"lib/Echoion.ts\",\"sha256\":{\"executable\":\"" + + std::string(kAbcSha256) + "\",\"core\":\"" + std::string(kAbcSha256) + + "\"}}"; + check(Void::FileSystem::atomic_write(manifestPath, legacyManifest) + .has_value(), + "failed to write legacy manifest"); + auto legacy = Echoion::Standalone::ReleaseManifest::load(manifestPath); + check(legacy.has_value(), "legacy release manifest was rejected"); + if (legacy) { + check(legacy->validate().has_value(), + "legacy release payload was rejected"); + check(!legacy->validateInstallLayout(), + "legacy manifest was accepted for full install validation"); + } + + return failures == 0 ? 0 : 1; } diff --git a/tests/test_runtime_paths.cpp b/tests/test_runtime_paths.cpp new file mode 100644 index 0000000..053451f --- /dev/null +++ b/tests/test_runtime_paths.cpp @@ -0,0 +1,144 @@ +#include "echoion/standalone/RuntimePaths.hpp" + +#include +#include +#include +#include +#include + +namespace +{ + class TemporaryTree + { + public: + + TemporaryTree() + { + std::random_device random; + path_ = + std::filesystem::temp_directory_path() / + ("echoion-runtime-paths-" + + std::to_string(static_cast(random()))); + std::filesystem::create_directories(path_); + } + + ~TemporaryTree() + { + std::error_code error; + std::filesystem::remove_all(path_, error); + } + + TemporaryTree(const TemporaryTree&) = delete; + TemporaryTree& operator=(const TemporaryTree&) = delete; + + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return path_; + } + + private: + + std::filesystem::path path_; + }; + + bool writeFile(const std::filesystem::path& path) + { + std::filesystem::create_directories(path.parent_path()); + std::ofstream output(path); + output << "test\n"; + return output.good(); + } +} // namespace + +int main() +{ + int failures{}; + const auto check = [&failures](bool condition, const std::string& message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + + TemporaryTree tree; + const auto installRoot = tree.path() / "echoion"; + const auto executable = installRoot / "bin" / "echoiond"; + const auto executableDirectory = executable.parent_path(); + check(Echoion::Standalone::deriveInstallRoot(executable) == installRoot, + "bin/echoiond did not resolve to its installation root"); + check(Echoion::Standalone::deriveInstallRoot( + executable, tree.path() / "override") == tree.path() / "override", + "ECHOION_HOME-style override was not preferred"); + + const auto state = Echoion::Standalone::resolveStateDirectory( + tree.path() / "cli-state", tree.path() / "environment-state", + tree.path() / "xdg-state", tree.path() / "home", + tree.path() / "fallback"); + check(state == tree.path() / "cli-state", + "command-line state directory did not win precedence"); + check(Echoion::Standalone::resolveStateDirectory( + std::nullopt, tree.path() / "environment-state", + tree.path() / "xdg-state", tree.path() / "home", + tree.path() / "fallback") == tree.path() / "environment-state", + "environment state directory did not win precedence"); + check(Echoion::Standalone::resolveStateDirectory( + std::nullopt, std::nullopt, tree.path() / "xdg-state", + tree.path() / "home", tree.path() / "fallback") == + tree.path() / "xdg-state" / "echoion", + "XDG state directory fallback is incorrect"); + + const auto packagedCore = installRoot / "lib" / "Echoion.ts"; + check(writeFile(packagedCore), "failed to create packaged Core fixture"); + check(Echoion::Standalone::resolveCorePath( + installRoot, executableDirectory) == packagedCore, + "packaged Core was not resolved from install-root/lib"); + check(Echoion::Standalone::resolveCorePath( + installRoot, executableDirectory, + std::filesystem::path{"custom/Echoion.ts"}) == + installRoot / "custom" / "Echoion.ts", + "relative Core override was not anchored at the install root"); + + const auto packagedIndex = + installRoot / "share" / "echoion" / "web" / "index.html"; + check(writeFile(packagedIndex), "failed to create packaged web fixture"); + check( + Echoion::Standalone::runtimeWorkingDirectory(installRoot, + executableDirectory) == + installRoot / "share" / "echoion", + "packaged web root did not select share/echoion as working directory"); + std::filesystem::remove_all(installRoot / "share"); + const auto developmentIndex = executableDirectory / "web" / "index.html"; + check(writeFile(developmentIndex), + "failed to create development web fixture"); + check(Echoion::Standalone::runtimeWorkingDirectory( + installRoot, executableDirectory) == executableDirectory, + "development web root did not select the executable directory"); + + const auto avatarCache = tree.path() / "state" / "avatars"; + std::filesystem::create_directories(avatarCache); + check(Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache) == + avatarCache, + "empty avatar directory request did not select the state cache"); + check(Echoion::Standalone::resolveAvatarCacheDirectory( + avatarCache, "legacy") == avatarCache / "legacy", + "relative avatar directory was not rooted below state"); + check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache, + "../escape"), + "traversing avatar directory was accepted"); + check(!Echoion::Standalone::resolveAvatarCacheDirectory( + avatarCache, tree.path() / "outside"), + "absolute avatar directory outside state was accepted"); + const auto avatarEscape = avatarCache / "escape"; + std::error_code avatarError; + std::filesystem::create_symlink(tree.path(), avatarEscape, avatarError); + check(!avatarError, "failed to create avatar symlink escape fixture"); + check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache, + "escape/cache"), + "avatar directory escaped state through a symbolic link"); + + const auto runningExecutable = Echoion::Standalone::runningExecutablePath(); + check(runningExecutable.has_value() && + std::filesystem::is_regular_file(*runningExecutable), + "running executable could not be resolved through /proc/self/exe"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_stage_release.sh b/tests/test_stage_release.sh index 02cd823..be3c8e2 100755 --- a/tests/test_stage_release.sh +++ b/tests/test_stage_release.sh @@ -3,32 +3,46 @@ set -euo pipefail stage_script=$1 validator=$2 +generator=$(dirname -- "$stage_script")/generate-release-manifest.py root=$(mktemp -d) trap 'rm -rf -- "$root"' EXIT -printf '#!/bin/sh\nexit 0\n' > "$root/source-echoiond" -chmod 0755 "$root/source-echoiond" -printf 'test core\n' > "$root/source-core.ts" +bundle=$root/bundle +mkdir -p -- \ + "$bundle/bin" \ + "$bundle/lib" \ + "$bundle/service" \ + "$bundle/share/echoion/web" +printf '#!/bin/sh\nexit 0\n' > "$bundle/bin/echoiond" +chmod 0755 "$bundle/bin/echoiond" +printf 'test core\n' > "$bundle/lib/Echoion.ts" +printf '[Service]\nExecStart=@ECHOION_EXECUTABLE@\n' \ + > "$bundle/service/echoion.service.in" +printf '\n' > "$bundle/share/echoion/web/index.html" +ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so" -"$stage_script" "$root/releases" 1.2.3 \ - "$root/source-echoiond" "$root/source-core.ts" +python3 "$generator" --root "$bundle" --version 1.2.3 +"$validator" --validate-install "$bundle" -manifest="$root/releases/pending-release.json" -test -x "$root/releases/1.2.3/echoiond" -test -f "$root/releases/1.2.3/Echoion.ts" +bash "$stage_script" "$root/releases" 1.2.3 "$bundle" + +manifest=$root/releases/pending-release.json +test -x "$root/releases/1.2.3/bin/echoiond" +test -f "$root/releases/1.2.3/lib/Echoion.ts" +test -L "$root/releases/1.2.3/lib/libEchoionCore.so" grep -q '"version": "1.2.3"' "$manifest" -grep -q '"executable": "1.2.3/echoiond"' "$manifest" -grep -q "$(sha256sum "$root/releases/1.2.3/echoiond" | cut -d' ' -f1)" "$manifest" +grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest" +grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest" "$validator" --validate-release "$manifest" -printf 'tampered\n' >> "$root/releases/1.2.3/Echoion.ts" +printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts" if "$validator" --validate-release "$manifest" >/dev/null 2>&1; then echo "tampered Core artifact was accepted" >&2 exit 1 fi -if "$stage_script" "$root/releases" '../unsafe' \ - "$root/source-echoiond" "$root/source-core.ts" >/dev/null 2>&1; then +if bash "$stage_script" "$root/releases" '../unsafe' "$bundle" \ + >/dev/null 2>&1; then echo "unsafe version was accepted" >&2 exit 1 fi