diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e2694b4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +build* +dist +release +EchoionWeb/frontend/node_modules +EchoionWeb/frontend/web-dist +docs diff --git a/.gitignore b/.gitignore index 6b24400..50cfbb9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,11 @@ *build* release +/dist/ +__pycache__/ +*.py[cod] .claude .cache .idea AGENTS.md .vscode -.opencode/ \ No newline at end of file +.opencode/ diff --git a/CMakeLists.txt b/CMakeLists.txt index ed18f3e..09e8dd0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,8 @@ cmake_minimum_required(VERSION 4.0.0) project(Echoion VERSION 1.0.0 LANGUAGES CXX) +include(GNUInstallDirs) + # Default to a Release build when the developer/CI did not pick a config. # Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC # falls back to -O0, so "production" builds shipped unoptimised. Set this before @@ -30,12 +32,12 @@ endif() # must be part of the validated echoiond artifact in production, otherwise a # release could pair a new daemon with an old/incompatible shared library. option(BUILD_SHARED_LIBS "Build shared libraries" ON) -option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON) +option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF) if(ECHOION_STATIC_LINK) set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE) set(BUILD_SHARED_LIBS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) - message(STATUS "Static linking enabled - building standalone distribution") + message(STATUS "Static GCC runtime linking enabled") endif() # Include CPM @@ -63,7 +65,9 @@ CPMAddPackage( CPMAddPackage( NAME Void GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git - GIT_TAG main + # Keep clean/container releases reproducible. CPM_Void_SOURCE still + # overrides this revision for local dependency development. + GIT_TAG 8583a479dda93be3394dfadefd7875ddd9e376dc OPTIONS "VOID_ENABLE_TESTING OFF" ) @@ -74,7 +78,8 @@ CPMAddPackage( CPMAddPackage( NAME VoidTeamspeak GIT_REPOSITORY http://git.faumaray.ru/void/voidteamspeak.git - GIT_TAG main + # This revision supplies the typed administration API used by Standalone. + GIT_TAG 89911ff107bc57347e3f91c9e0544265d64de5df OPTIONS "VOID_TEAMSPEAK_BUILD_TESTS OFF" "VOID_ENABLE_TESTING OFF" @@ -175,35 +180,58 @@ if(BUILD_DESKTOP) add_subdirectory(EchoionDesktop) endif() -# Packaging configuration -include(CPack) -set(CPACK_PACKAGE_NAME "Echoion") -set(CPACK_PACKAGE_VENDOR "Echoion") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak") -set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") -set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") +# The release install component is deliberately runtime-only. Nested projects +# keep their normal SDK/development install rules, while scripts/release.sh uses +# this component as the single input to dependency collection and packaging. +option(ECHOION_INSTALL_RUNTIME_BUNDLE + "Provide the relocatable Echoion Runtime install component" ON) +if(ECHOION_INSTALL_RUNTIME_BUNDLE) + if(TARGET EchoionStandalone) + if(UNIX AND NOT APPLE) + set_target_properties(EchoionStandalone PROPERTIES + INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" + INSTALL_RPATH_USE_LINK_PATH FALSE) + endif() + install(TARGETS EchoionStandalone + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + COMPONENT Runtime) + endif() -# Platform-specific packaging -if(WIN32) - set(CPACK_GENERATOR "ZIP;NSIS") - set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot") - set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion") - set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion") -elseif(APPLE) - set(CPACK_GENERATOR "DragNDMGZ") - set(CPACK_DMG_VOLUME_NAME "Echoion") -else() - set(CPACK_GENERATOR "TGZ;DEB;RPM") - set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0") - set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite") + if(TARGET EchoionCore) + if(UNIX AND NOT APPLE) + set_target_properties(EchoionCore PROPERTIES + INSTALL_RPATH "$ORIGIN" + INSTALL_RPATH_USE_LINK_PATH FALSE) + endif() + install(TARGETS EchoionCore + RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Runtime) + endif() + + if(TARGET EchoionWeb) + install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web" + COMPONENT Runtime) + endif() + + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion" + COMPONENT Runtime) + install(FILES + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in" + DESTINATION service + COMPONENT Runtime) + + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses" + RENAME Echoion-LICENSE + COMPONENT Runtime) + endif() endif() # Bundling and deployment helpers -include(GNUInstallDirs) - # Function to bundle Qt dependencies function(bundle_qt_dependencies target) if(NOT TARGET ${target}) @@ -277,6 +305,50 @@ if(BUILD_CORE AND TARGET EchoionCore) install_with_dependencies(EchoionCore) endif() +if(BUILD_TESTS AND UNIX) + add_test(NAME echoion_release_manifest_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_runtime_dependency_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_release_archive_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_frontend_license_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_installer_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh") +endif() + +# The universal .tar.zst/.run workflow is the supported Linux distribution +# format. Keep legacy CPack available for local Windows/macOS experiments, +# without publishing inaccurate DEB/RPM host-dependency metadata. +option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF) +if(ECHOION_ENABLE_LEGACY_CPACK) + set(CPACK_PACKAGE_NAME "Echoion") + set(CPACK_PACKAGE_VENDOR "Echoion") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak") + set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) + set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") + if(WIN32) + set(CPACK_GENERATOR "ZIP;NSIS") + set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot") + elseif(APPLE) + set(CPACK_GENERATOR "DragNDrop") + set(CPACK_DMG_VOLUME_NAME "Echoion") + else() + set(CPACK_GENERATOR "TGZ") + endif() + include(CPack) +endif() + # Print configuration summary message(STATUS "") message(STATUS "Echoion Configuration:") @@ -285,11 +357,14 @@ message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build API: ${BUILD_API}") message(STATUS " Build Core: ${BUILD_CORE}") message(STATUS " Build Desktop: ${BUILD_DESKTOP}") +message(STATUS " Build Web: ${BUILD_WEB}") +message(STATUS " Build Standalone: ${BUILD_STANDALONE}") message(STATUS " Build Tests: ${BUILD_TESTS}") message(STATUS " Static Link: ${ECHOION_STATIC_LINK}") +message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}") message(STATUS "") message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}") message(STATUS "To build: cmake --build build") message(STATUS "To install: cmake --install build --prefix ") -message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)") +message(STATUS "To release: scripts/release.sh --version ") message(STATUS "") diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..c399551 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,53 @@ +{ + "version": 9, + "cmakeMinimumRequired": { + "major": 4, + "minor": 0, + "patch": 0 + }, + "configurePresets": [ + { + "name": "linux-release", + "displayName": "Linux dynamic runtime release", + "description": "Bot, Core, web dashboard, tests, and a runtime-only install component", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_INSTALL_PREFIX": "${sourceDir}/build-release/stage", + "BUILD_SHARED_LIBS": "ON", + "ECHOION_STATIC_LINK": "OFF", + "ECHOION_INSTALL_RUNTIME_BUNDLE": "ON", + "ECHOION_ENABLE_LEGACY_CPACK": "OFF", + "ECHOION_ENABLE_LTO": "ON", + "BUILD_API": "ON", + "BUILD_CORE": "ON", + "BUILD_WEB": "ON", + "ECHOION_BUILD_WEB": "ON", + "BUILD_STANDALONE": "ON", + "BUILD_DESKTOP": "OFF", + "BUILD_TESTS": "ON" + } + } + ], + "buildPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release", + "configuration": "Release" + } + ], + "testPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release", + "configuration": "Release", + "output": { + "outputOnFailure": true + }, + "execution": { + "noTestsAction": "error" + } + } + ] +} diff --git a/EchoionCore b/EchoionCore index 39aff68..9f06af6 160000 --- a/EchoionCore +++ b/EchoionCore @@ -1 +1 @@ -Subproject commit 39aff68d8d79d3e5d5c92e0c10f20d7fc4c6a4e0 +Subproject commit 9f06af6c8043bf27b506cdd141b9d8260c42691e diff --git a/EchoionHost/src/CoreLoader.cpp b/EchoionHost/src/CoreLoader.cpp index 85c5b35..64327a0 100644 --- a/EchoionHost/src/CoreLoader.cpp +++ b/EchoionHost/src/CoreLoader.cpp @@ -1,43 +1,114 @@ +#include "echoion/host/CoreLoader.hpp" #include #include #include -#include "echoion/host/CoreLoader.hpp" +#include #include #include #include #include #include +#include + +#ifndef _WIN32 +#include +#include +#endif namespace Echoion::Host { + namespace + { + bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath) + { + const auto directory = libraryPath.parent_path(); +#ifdef _WIN32 + std::error_code error; + const auto status = std::filesystem::status(directory, error); + if (error || !std::filesystem::is_directory(status)) { + return false; + } + constexpr auto writable = std::filesystem::perms::owner_write | + std::filesystem::perms::group_write | + std::filesystem::perms::others_write; + return (status.permissions() & writable) != + std::filesystem::perms::none; +#else + struct stat metadata{}; + if (::stat(directory.c_str(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + return false; + } + + const auto effectiveUser = ::geteuid(); + const auto effectiveGroup = ::getegid(); + bool usesDirectoryGroup = effectiveGroup == metadata.st_gid; + if (!usesDirectoryGroup) { + const int count = ::getgroups(0, nullptr); + if (count > 0) { + std::vector groups(static_cast(count)); + if (::getgroups(count, groups.data()) == count) { + usesDirectoryGroup = + std::ranges::contains(groups, metadata.st_gid); + } + } + } + + mode_t required{}; + if (effectiveUser == metadata.st_uid) { + required = S_IWUSR | S_IXUSR; + } else if (usesDirectoryGroup) { + required = S_IWGRP | S_IXGRP; + } else { + required = S_IWOTH | S_IXOTH; + } + return (metadata.st_mode & required) == required && + ::access(directory.c_str(), W_OK | X_OK) == 0; +#endif + } + } // namespace CoreLoader::CoreLoader() : pluginManager_(Void::Plugin::PluginManager::Options{ .dlclose_on_swap = false, - .copy_on_load = true, - .config_provider = [this](std::string_view) { - return configPath_.string(); - }, - .instance_validator = [](Void::Plugin::IPlugin& plugin, - const Void::Plugin::PluginInfo&) { - return dynamic_cast(&plugin) != nullptr; - }}) + // Packaged Core libraries live in an immutable, service-readable + // directory. Initial load must never create a hotswap sibling + // there. + .copy_on_load = false, + .config_provider = + [this](std::string_view) { return configPath_.string(); }, + .instance_validator = + [](Void::Plugin::IPlugin& plugin, + const Void::Plugin::PluginInfo&) { + return dynamic_cast(&plugin) != + nullptr; + }}) { } void CoreLoader::enableAutoReload() { - if (autoReloadEnabled_.exchange(true)) { - return; // Already enabled - } - std::lock_guard lock(mutex_); + if (autoReloadEnabled_.load()) { + return; + } if (!currentLibraryPath_.empty() && std::filesystem::exists(currentLibraryPath_)) { - Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}", - currentLibraryPath_.string())); + if (!canCreateHotReloadCopy(currentLibraryPath_)) { + Void::Log::info( + "CoreLoader", "{}", + std::format( + "Auto-reload disabled for read-only Core directory: {}", + currentLibraryPath_.parent_path().string())); + return; + } + autoReloadEnabled_ = true; + Void::Log::info("CoreLoader", "{}", + std::format("Enabling auto-reload for: {}", + currentLibraryPath_.string())); - fileWatcher_.watch(currentLibraryPath_, + fileWatcher_.watch( + currentLibraryPath_, [this](const Void::FileSystem::FileWatcher::Event& event) { if (event.exists) { onCoreFileChanged(); @@ -66,7 +137,8 @@ namespace Echoion::Host return; } - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", "Core file changed, scheduling hot reload after current track..."); // Small delay to ensure file write is complete @@ -88,7 +160,8 @@ namespace Echoion::Host } } - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", std::format("Playback active (track: {}), deferring reload " "until track finishes", currentTrackId)); @@ -104,10 +177,12 @@ namespace Echoion::Host // No playback, reload immediately auto result = hotReload(currentLibraryPath_); if (!result) { - Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}", - result.error().message)); + Void::Log::error("CoreLoader", "{}", + std::format("Auto hot-reload failed: {}", + result.error().message)); } else { - Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully"); + Void::Log::info("CoreLoader", "{}", + "Auto hot-reload completed successfully"); } } } @@ -144,8 +219,10 @@ namespace Echoion::Host void CoreLoader::waitForTrackAndReload( const std::filesystem::path& targetPath, const std::string& trackId) { - Void::Log::info("CoreLoader", "{}", std::format( - "Waiting for track {} to finish before reload...", trackId)); + Void::Log::info( + "CoreLoader", "{}", + std::format("Waiting for track {} to finish before reload...", + trackId)); // Poll every 500ms to check if the specific track finished // (playback may continue with next track, but we only care about THIS @@ -157,7 +234,8 @@ namespace Echoion::Host if (deferredReloadCv_.wait_for( lock, std::chrono::milliseconds(500), [this] { return stopDeferredReload_.load(); })) { - Void::Log::info("CoreLoader", "{}", + Void::Log::info( + "CoreLoader", "{}", "Deferred hot-reload cancelled (loader shutting down)"); return; } @@ -167,7 +245,8 @@ namespace Echoion::Host return; } - Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload"); + Void::Log::info("CoreLoader", "{}", + "Track finished, starting hot reload"); // Clear pending flag { @@ -179,10 +258,12 @@ namespace Echoion::Host // Now do the reload auto result = hotReload(targetPath); if (!result) { - Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}", - result.error().message)); + Void::Log::error("CoreLoader", "{}", + std::format("Deferred hot-reload failed: {}", + result.error().message)); } else { - Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully"); + Void::Log::info("CoreLoader", "{}", + "Deferred hot-reload completed successfully"); } } @@ -211,7 +292,7 @@ namespace Echoion::Host if (loaded_) { return Api::fail(Api::ErrorCode::AlreadyExists, - "Core already loaded"); + "Core already loaded"); } if (!std::filesystem::exists(libraryPath)) { @@ -236,13 +317,13 @@ namespace Echoion::Host } Api::Result - CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) + CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { std::unique_lock lock(mutex_); if (!loaded_) { return Api::fail(Api::ErrorCode::NotFound, - "No core loaded to reload"); + "No core loaded to reload"); } auto targetPath = @@ -254,13 +335,22 @@ namespace Echoion::Host std::format("New library not found: {}", targetPath.string())); } if (targetPath != currentLibraryPath_) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "in-process Core reload must use the loaded path; release bundles " + return Api::fail( + Api::ErrorCode::InvalidArgument, + "in-process Core reload must use the loaded path; release " + "bundles " "with a new path are applied through daemon re-exec"); } + if (!canCreateHotReloadCopy(targetPath)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "in-process Core reload requires a writable library directory; " + "immutable releases are applied through daemon re-exec"); + } hotReloading_ = true; - Void::Log::info("CoreLoader", "{}", "Starting transactional hot reload..."); + Void::Log::info("CoreLoader", "{}", + "Starting transactional hot reload..."); // No callback may execute code from the old shared object after this // barrier returns. State capture and dlclose are safe only after event @@ -289,13 +379,15 @@ namespace Echoion::Host const auto reloadResult = pluginManager_.reload(pluginName_); if (!reloadResult) { hotReloading_ = false; - auto message = std::format( - "new Core rejected; running Core retained: {}", - Void::Plugin::to_string(reloadResult.error())); + auto message = + std::format("new Core rejected; running Core retained: {}", + Void::Plugin::to_string(reloadResult.error())); if (core_) { - if (auto initialized = core_->initialize(configPath_); !initialized) { - message += std::format("; retained Core reactivation failed: {}", - initialized.error().message); + if (auto initialized = core_->initialize(configPath_); + !initialized) { + message += + std::format("; retained Core reactivation failed: {}", + initialized.error().message); } else if (!state.empty()) { if (auto restored = core_->restoreState(state); !restored) { message += std::format( @@ -320,8 +412,9 @@ namespace Echoion::Host } if (!state.empty()) { if (auto restored = core_->restoreState(state); !restored) { - Void::Log::warn("CoreLoader", "new Core state restore failed: {}", - restored.error().message); + Void::Log::warn("CoreLoader", + "new Core state restore failed: {}", + restored.error().message); } } hotReloading_ = false; @@ -360,12 +453,12 @@ namespace Echoion::Host } Api::Result - CoreLoader::checkpoint(const std::filesystem::path& destination) + CoreLoader::checkpoint(const std::filesystem::path& destination) { std::lock_guard lock(mutex_); if (!core_) { return Api::fail(Api::ErrorCode::NotInitialized, - "cannot checkpoint without a loaded Core"); + "cannot checkpoint without a loaded Core"); } const auto state = core_->saveState(); std::string bytes; @@ -379,37 +472,37 @@ namespace Echoion::Host appendU32(static_cast(state.timestamp.size())); bytes.append(state.timestamp); bytes.append(reinterpret_cast(state.data.data()), - state.data.size()); + state.data.size()); if (auto result = Void::FileSystem::atomic_write(destination, bytes); !result) { return Api::fail(Api::ErrorCode::PluginError, - result.error().message()); + result.error().message()); } return {}; } Api::Result - CoreLoader::restoreCheckpoint(const std::filesystem::path& source) + CoreLoader::restoreCheckpoint(const std::filesystem::path& source) { std::lock_guard lock(mutex_); if (!core_) { return Api::fail(Api::ErrorCode::NotInitialized, - "cannot restore without a loaded Core"); + "cannot restore without a loaded Core"); } auto contents = Void::FileSystem::read_file(source); if (!contents) { return Api::fail(Api::ErrorCode::NotFound, - contents.error().message()); + contents.error().message()); } if (contents->size() < 8) { return Api::fail(Api::ErrorCode::ParseError, - "checkpoint header is truncated"); + "checkpoint header is truncated"); } auto readU32 = [&contents](std::size_t offset) { uint32_t value = 0; for (std::size_t index = 0; index < 4; ++index) { value = (value << 8U) | - static_cast((*contents)[offset + index]); + static_cast((*contents)[offset + index]); } return value; }; @@ -418,12 +511,13 @@ namespace Echoion::Host const auto timestampSize = readU32(4); if (timestampSize > contents->size() - 8) { return Api::fail(Api::ErrorCode::ParseError, - "checkpoint timestamp is truncated"); + "checkpoint timestamp is truncated"); } state.timestamp = contents->substr(8, timestampSize); const auto dataOffset = 8 + timestampSize; state.data.assign(contents->begin() + - static_cast(dataOffset), contents->end()); + static_cast(dataOffset), + contents->end()); return core_->restoreState(state); } @@ -432,9 +526,10 @@ namespace Echoion::Host { auto result = pluginManager_.load(path); if (!result) { - return Api::fail(Api::ErrorCode::PluginError, + return Api::fail( + Api::ErrorCode::PluginError, std::format("failed to load Core plugin: {}", - Void::Plugin::to_string(result.error()))); + Void::Plugin::to_string(result.error()))); } pluginName_ = std::move(*result); if (auto refreshed = refreshCoreHandle(); !refreshed) { @@ -453,11 +548,12 @@ namespace Echoion::Host pluginManager_.acquire(pluginName_)); if (!*pin) { return Api::fail(Api::ErrorCode::PluginError, - "Core plugin disappeared from the registry"); + "Core plugin disappeared from the registry"); } auto* interface = dynamic_cast(pin->get()); if (interface == nullptr) { - return Api::fail(Api::ErrorCode::InvalidArgument, + return Api::fail( + Api::ErrorCode::InvalidArgument, "Void plugin does not implement Echoion Core interface"); } core_ = Api::CoreInterfacePtr{std::move(pin), interface}; @@ -475,9 +571,10 @@ namespace Echoion::Host core_.reset(); if (!pluginName_.empty()) { if (auto result = pluginManager_.unload(pluginName_); !result) { - return Api::fail(Api::ErrorCode::PluginError, + return Api::fail( + Api::ErrorCode::PluginError, std::format("failed to unload Core plugin: {}", - Void::Plugin::to_string(result.error()))); + Void::Plugin::to_string(result.error()))); } pluginName_.clear(); } diff --git a/EchoionStandalone/CMakeLists.txt b/EchoionStandalone/CMakeLists.txt index 70a5284..2a21694 100644 --- a/EchoionStandalone/CMakeLists.txt +++ b/EchoionStandalone/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/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp b/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp index d68c675..553230d 100644 --- a/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp +++ b/EchoionStandalone/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/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp b/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp new file mode 100644 index 0000000..88122a1 --- /dev/null +++ b/EchoionStandalone/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/EchoionStandalone/src/ReleaseManifest.cpp b/EchoionStandalone/src/ReleaseManifest.cpp index 9775af5..f39ff7a 100644 --- a/EchoionStandalone/src/ReleaseManifest.cpp +++ b/EchoionStandalone/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/EchoionStandalone/src/RuntimePaths.cpp b/EchoionStandalone/src/RuntimePaths.cpp new file mode 100644 index 0000000..7996086 --- /dev/null +++ b/EchoionStandalone/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/EchoionStandalone/src/StandaloneClientInterface.cpp b/EchoionStandalone/src/StandaloneClientInterface.cpp index 8a3b809..915d6be 100644 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ b/EchoionStandalone/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/EchoionStandalone/src/main.cpp b/EchoionStandalone/src/main.cpp index 2acb628..983cc14 100644 --- a/EchoionStandalone/src/main.cpp +++ b/EchoionStandalone/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/EchoionStandalone/tests/test_core_loader_reload.cpp b/EchoionStandalone/tests/test_core_loader_reload.cpp index 6461392..f3b75ef 100644 --- a/EchoionStandalone/tests/test_core_loader_reload.cpp +++ b/EchoionStandalone/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/EchoionStandalone/tests/test_release_manifest.cpp b/EchoionStandalone/tests/test_release_manifest.cpp index 64ce918..43de15c 100644 --- a/EchoionStandalone/tests/test_release_manifest.cpp +++ b/EchoionStandalone/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/EchoionStandalone/tests/test_runtime_paths.cpp b/EchoionStandalone/tests/test_runtime_paths.cpp new file mode 100644 index 0000000..053451f --- /dev/null +++ b/EchoionStandalone/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/EchoionStandalone/tests/test_stage_release.sh b/EchoionStandalone/tests/test_stage_release.sh index 02cd823..be3c8e2 100755 --- a/EchoionStandalone/tests/test_stage_release.sh +++ b/EchoionStandalone/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 diff --git a/EchoionWeb/CMakeLists.txt b/EchoionWeb/CMakeLists.txt index e10aa9c..f19a519 100644 --- a/EchoionWeb/CMakeLists.txt +++ b/EchoionWeb/CMakeLists.txt @@ -71,9 +71,12 @@ if(ECHOION_BUILD_WEB) # Rebuild web-dist whenever any source/config under frontend/ (excluding # node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at # build time so new files are picked up without re-running CMake. - file(GLOB_RECURSE _web_srcs CONFIGURE_DEPENDS + file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS + LIST_DIRECTORIES FALSE "${_web_frontend}/src/*" - "${_web_frontend}/public/*" + "${_web_frontend}/public/*") + set(_web_srcs + ${_web_tree_srcs} "${_web_frontend}/index.html" "${_web_frontend}/package.json" "${_web_frontend}/package-lock.json" @@ -82,8 +85,9 @@ if(ECHOION_BUILD_WEB) add_custom_command( OUTPUT "${_web_dist}/index.html" - # `npm ci` when the lockfile is newer than node_modules keeps installs - # reproducible; the stamp check avoids reinstalling on every build. + # Release builds run `npm ci` before CMake. This lockfile-aware fallback + # keeps direct developer builds convenient without reinstalling on every + # incremental build. COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund COMMAND ${NPM_EXECUTABLE} run build WORKING_DIRECTORY "${_web_frontend}" diff --git a/README.md b/README.md index 61493c1..3ed5d09 100644 --- a/README.md +++ b/README.md @@ -27,32 +27,48 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp ## Building -### Requirements +### Developer requirements - C++26 compatible compiler with reflections (GCC 16+) - CMake 4.0+ -- Qt6 (for desktop client) -- FFmpeg (for audio decoding) +- Qt6 (only when building the desktop client) +- FFmpeg 5+ (for audio decoding and the modern channel-layout API) - Boost (system installation preferred; the build vendors one only when absent — mixing a vendored and a system Boost in one process breaks boost.url) - OpenSSL, libsodium, Opus, FFmpeg, and Boost development packages -### Build Instructions +### Local build ```bash -mkdir build && cd build -cmake .. -cmake --build . +cmake -S . -B build -DBUILD_TESTS=ON +cmake --build build -j2 +ctest --test-dir build --output-on-failure ``` -### Tests +The supported Linux release is dynamically linked. Static GCC runtime linking +is disabled by default; the release process collects the non-glibc shared +library closure into the bundle and assigns relocatable `$ORIGIN` RUNPATHs. + +### Clean containerized Linux release + +Docker is the only host requirement for the default release command: ```bash -cmake .. -DBUILD_TESTS=ON -cmake --build . && ctest +scripts/release.sh --version 1.2.3 ``` -The protocol suite covers command escaping/parsing, packet crypto, QuickLZ, -identity generation and persistence, and TeamSpeak identity-export import. +It builds with a version-pinned GCC 16/FFmpeg 8.0.3 toolchain on Ubuntu 22.04, +runs the C++ and frontend test suites, installs into a clean staging tree, +bundles dynamic dependencies, validates the ELF closure with `readelf`, and +produces both `.tar.zst` and self-extracting `.run` artifacts under `dist/`. +The bot is never initialized or started during release creation. Use `--host` +only on a Debian-family build host with `dpkg-query`, `ldconfig`, and a glibc +ABI no newer than the supported 2.35 floor; incompatible host artifacts are +rejected. + +The Linux x86-64 bundle targets glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+, +and current Arch Linux). glibc and the ELF loader come from the target system; +libstdc++, libgcc, FFmpeg, OpenSSL, Opus, and the remaining runtime closure are +carried in `lib/`. ## Configuration @@ -66,7 +82,7 @@ Edit the configuration file with your server details: ```json { - "server": { + "teamspeak": { "address": "your.server.com", "port": 9987, "nickname": "MusicBot", @@ -77,20 +93,78 @@ Edit the configuration file with your server details: ## Installation -### Standalone daemon +The `.run` artifact is the recommended installer. It supports system, user, +and portable layouts and never starts the bot unless `--start` is explicitly +supplied. -1. Build the project and install `echoiond` together with `Echoion.ts`. -2. Copy `systemd/echoion-standalone.service` to your user systemd directory, - adjust its paths, and enable it. -3. On first start, Echoion generates `~/.config/echoion/identity.txt`. +```bash +# User install; registers a disabled/stopped user service. +./echoion-1.2.3-linux-x86_64.run \ + --mode user --non-interactive + +# System install and explicit activation. +sudo ./echoion-1.2.3-linux-x86_64.run \ + --mode system --register-service system --start --non-interactive + +# Fully self-contained portable install, without a service. +./echoion-1.2.3-linux-x86_64.run \ + --mode portable --prefix /srv/echoion-portable \ + --data-layout self-contained --register-service none --non-interactive + +# A portable tree may also register a stable user service. +./echoion-1.2.3-linux-x86_64.run \ + --mode portable --prefix "$HOME/echoion-portable" \ + --data-layout self-contained --register-service user --non-interactive +``` + +Portable service registration rejects temporary, world-writable, or +service-inaccessible prefixes, including group/world-writable ancestors. Run +user-service registration as the intended non-root user; root user services are +rejected. Use `--register-service system` with root when a portable tree must +run as a system service. Its complete runtime path must be root-owned and not +writable by the service account. Registration alone performs a daemon reload +and leaves the unit disabled and stopped; add `--start` to enable and start it. + +Every installation uses immutable `versions//` payloads and an atomic +`current` symlink. Configuration is created once and is not overwritten by an +upgrade. The standard mutable paths are: + +| Mode | Configuration | State, database, logs, cache and temporary files | +|---|---|---| +| user/portable with no or user service | `$XDG_CONFIG_HOME/echoion` | `$XDG_STATE_HOME/echoion` | +| system/portable with system service | `/etc/echoion` | `/var/lib/echoion` | +| self-contained | `/config` | `/data` | + +Override them with `--config-dir` and `--state-dir`. In a self-contained +portable install, runtime code, web assets, config, identity, database, +extensions, logs, downloaded helpers, cache, and temporary audio all remain +below the selected prefix. + +A self-contained portable install also creates `/echoion`; use that +launcher instead of invoking `current/bin/echoiond` directly. It derives the +config and state paths from its own location, so a stopped, service-free tree +can be moved as one folder and run from the new path. If a portable service was +registered, uninstall or re-register its unit before moving the tree because +systemd stores an absolute executable path. + +The installer executes only the daemon's offline `--validate-install` mode to +verify every immutable file, symlink, mode, and SHA-256 before switching +`current`; it does not initialize the TeamSpeak client or load Core. + +To remove an install, run `/uninstall.sh`. Configuration and state are +preserved by default. Add `--purge` to remove directories that this installer +created and marked as dedicated Echoion data. Pre-existing override directories +are preserved and must be removed manually. To preserve the permissions and UID of an existing TeamSpeak client identity, export it from TeamSpeak's Identity Manager and import it before first start: ```bash -echoiond --import-identity identity.ini +/current/bin/echoiond --import-identity identity.ini \ + --state-dir # Choose a non-default destination or replace an existing identity explicitly: -echoiond --import-identity identity.ini --identity-path /path/to/identity.txt --force +/current/bin/echoiond --import-identity identity.ini \ + --identity-path /path/to/identity.txt --force ``` The identity file contains a private key. Keep both the TeamSpeak export and @@ -157,26 +231,35 @@ visible TeamSpeak identity. ## Development -### Hot Reload +### Development hot reload The core library can be hot-reloaded without disconnecting from the server: 1. Build the new core: `cmake --build . --target EchoionCore` 2. Replace `Echoion.ts`; the daemon's host watcher reloads it automatically. -Protocol or host changes require a validated daemon re-exec rather than a Core -hot reload. Stage both artifacts and atomically publish the watched manifest: +This developer-only watcher is enabled for writable build trees. Installed +release payloads are immutable and use installer upgrades plus service restart +instead of writing temporary libraries beside Core. + +Protocol or host changes can use the daemon's opt-in transactional re-exec API. +The process must be started with `ECHOION_RELEASE_MANIFEST` set to the absolute +manifest path before a release is staged: ```bash +export ECHOION_RELEASE_MANIFEST="$HOME/echoion/releases/pending-release.json" +# Start the development daemon with its normal --config/--state-dir arguments. scripts/stage-release.sh "$HOME/echoion/releases" 1.2.3 \ - build/bin/echoiond build/lib/Echoion.ts + build-release/runtime-stage ``` The staging command rejects unsafe version names and existing release -directories, copies complete artifacts first, calculates SHA-256 hashes, then -renames `pending-release.json` into place. The running daemon validates it in a -child process, checkpoints Core state, disconnects cleanly, and -re-execs the staged binary. +directories, verifies the bundle's v2 whole-payload manifest, copies the full +runtime tree, and then renames `pending-release.json` into place. The running +daemon validates every declared file in a child process, checkpoints Core +state, disconnects cleanly, and re-execs the staged binary. The installer does +not enable this development watcher; installed upgrades are performed by +running the new `.run` artifact against the same prefix. ### Adding Commands @@ -204,40 +287,26 @@ instead of compiling commands into Core. See [Native plugins](docs/plugins.md). ## Packaging and Distribution -### Using CPack +The supported Linux distribution path is `scripts/release.sh`. Each release +contains: -The project includes CPack configuration for creating installers: +- `echoion--linux-x86_64.tar.zst` with one top-level directory; +- `echoion--linux-x86_64.run`, which accepts the installer flags above; +- the external v2 manifest and ELF dependency report; +- `SHA256SUMS` for all published artifacts. + +The archive and installer contain the same relocatable dynamic payload. They do +not depend on DEB/RPM metadata or static linking, so one build can be installed +on the supported Ubuntu, Debian, and Arch targets. + +When unpacking the `.tar.zst` form directly, preserve the release modes even +under a restrictive shell umask: ```bash -cd build - -# Create tarball -cpack -G TGZ - -# Create DEB package (Debian/Ubuntu) -cpack -G DEB - -# Create RPM package (Fedora/RHEL) -cpack -G RPM - -# Create ZIP (Windows) -cpack -G ZIP - -# Create NSIS installer (Windows) -cpack -G NSIS +tar --same-permissions --no-same-owner --zstd \ + -xf echoion-1.2.3-linux-x86_64.tar.zst ``` -### Static Linking - -For a standalone distribution without external dependencies: - -```bash -cmake .. -DECHOION_STATIC_LINK=ON -cmake --build . -``` - -Note: Some dependencies (Qt6, FFmpeg) may still require bundling. See `packaging/README.md` for detailed instructions. - ### CMake Package Support The project uses [PackageProject.cmake](https://github.com/TheLartians/PackageProject.cmake) to export CMake targets: diff --git a/cmake/BundleRuntimeDependencies.cmake b/cmake/BundleRuntimeDependencies.cmake new file mode 100644 index 0000000..66ab874 --- /dev/null +++ b/cmake/BundleRuntimeDependencies.cmake @@ -0,0 +1,197 @@ +cmake_minimum_required(VERSION 4.0) + +if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "Echoion runtime dependency bundling currently supports Linux only") +endif() +if(NOT DEFINED BUNDLE_ROOT OR BUNDLE_ROOT STREQUAL "") + message(FATAL_ERROR "BUNDLE_ROOT must name the staged runtime tree") +endif() +if(NOT DEFINED PATCHELF_EXECUTABLE OR PATCHELF_EXECUTABLE STREQUAL "") + find_program(PATCHELF_EXECUTABLE NAMES patchelf REQUIRED) +endif() +if(NOT DEFINED BUNDLE_SEED_FILES OR BUNDLE_SEED_FILES STREQUAL "") + message(FATAL_ERROR + "BUNDLE_SEED_FILES must contain the exact compiler runtime libraries") +endif() + +cmake_path(ABSOLUTE_PATH BUNDLE_ROOT NORMALIZE OUTPUT_VARIABLE _bundle_root) +set(_executable "${_bundle_root}/bin/echoiond") +set(_core "${_bundle_root}/lib/Echoion.ts") +set(_library_dir "${_bundle_root}/lib") +if(NOT DEFINED BUNDLE_RESOLVER_EXECUTABLE OR + BUNDLE_RESOLVER_EXECUTABLE STREQUAL "") + set(BUNDLE_RESOLVER_EXECUTABLE "${_executable}") +endif() +if(NOT DEFINED BUNDLE_RESOLVER_LIBRARIES OR + BUNDLE_RESOLVER_LIBRARIES STREQUAL "") + set(BUNDLE_RESOLVER_LIBRARIES "${_core}") +endif() + +if(NOT EXISTS "${_executable}") + message(FATAL_ERROR "Missing staged daemon: ${_executable}") +endif() +if(NOT EXISTS "${_core}") + message(FATAL_ERROR "Missing staged Core library: ${_core}") +endif() +if(NOT IS_ABSOLUTE "${BUNDLE_RESOLVER_EXECUTABLE}" OR + NOT EXISTS "${BUNDLE_RESOLVER_EXECUTABLE}" OR + IS_DIRECTORY "${BUNDLE_RESOLVER_EXECUTABLE}") + message(FATAL_ERROR + "Missing absolute dependency resolver executable: ${BUNDLE_RESOLVER_EXECUTABLE}") +endif() +foreach(_resolver_library IN LISTS BUNDLE_RESOLVER_LIBRARIES) + if(NOT IS_ABSOLUTE "${_resolver_library}" OR + NOT EXISTS "${_resolver_library}" OR + IS_DIRECTORY "${_resolver_library}") + message(FATAL_ERROR + "Missing absolute dependency resolver library: ${_resolver_library}") + endif() +endforeach() +file(MAKE_DIRECTORY "${_library_dir}") + +# Linux dependency resolution checks RUNPATH and then ldconfig before consulting +# DIRECTORIES. Seed the exact compiler runtimes into $ORIGIN first so an older +# host libstdc++/libgcc with the same SONAME cannot be selected accidentally. +foreach(_seed IN LISTS BUNDLE_SEED_FILES) + if(NOT IS_ABSOLUTE "${_seed}" OR NOT EXISTS "${_seed}" OR IS_DIRECTORY "${_seed}") + message(FATAL_ERROR "Missing absolute runtime seed: ${_seed}") + endif() + file(COPY "${_seed}" + DESTINATION "${_library_dir}" + FOLLOW_SYMLINK_CHAIN) +endforeach() + +# glibc and the ELF loader define the portable ABI floor and must be supplied +# by the target host. Everything else, including libgcc_s and libstdc++, is +# resolved recursively and copied into lib/. +set(_system_dependency_regexes + "^linux-vdso\\.so\\.1$" + "^ld-linux-x86-64\\.so\\.2$" + "^libc\\.so\\.6$" + "^libm\\.so\\.6$" + "^libmvec\\.so\\.1$" + "^libdl\\.so\\.2$" + "^libpthread\\.so\\.0$" + "^librt\\.so\\.1$" + "^libresolv\\.so\\.2$" + "^libutil\\.so\\.1$" + "^libanl\\.so\\.1$" + "^libBrokenLocale\\.so\\.1$" + "^libthread_db\\.so\\.1$") + +# These runtimes are explicit, compiler-derived seed files. Never let the +# resolver select a different host copy with the same SONAME through ldconfig. +set(_seed_dependency_regexes + "^libstdc\\+\\+\\.so.*$" + "^libgcc_s\\.so.*$") + +file(GET_RUNTIME_DEPENDENCIES + RESOLVED_DEPENDENCIES_VAR _resolved_dependencies + UNRESOLVED_DEPENDENCIES_VAR _unresolved_dependencies + CONFLICTING_DEPENDENCIES_PREFIX _conflicts + EXECUTABLES "${BUNDLE_RESOLVER_EXECUTABLE}" + LIBRARIES ${BUNDLE_RESOLVER_LIBRARIES} + DIRECTORIES ${BUNDLE_SEARCH_DIRECTORIES} + PRE_EXCLUDE_REGEXES + ${_system_dependency_regexes} + ${_seed_dependency_regexes}) + +if(_unresolved_dependencies) + list(SORT _unresolved_dependencies) + list(JOIN _unresolved_dependencies ", " _unresolved_text) + message(FATAL_ERROR "Unresolved runtime dependencies: ${_unresolved_text}") +endif() +if(_conflicts_FILENAMES) + list(SORT _conflicts_FILENAMES) + list(JOIN _conflicts_FILENAMES ", " _conflict_text) + message(FATAL_ERROR "Conflicting runtime dependency names: ${_conflict_text}") +endif() + +list(REMOVE_DUPLICATES _resolved_dependencies) +list(SORT _resolved_dependencies) +foreach(_dependency IN LISTS _resolved_dependencies) + if(NOT EXISTS "${_dependency}") + message(FATAL_ERROR "Resolved dependency disappeared: ${_dependency}") + endif() + cmake_path(GET _dependency PARENT_PATH _dependency_directory) + cmake_path(NORMAL_PATH _dependency_directory) + if(_dependency_directory STREQUAL _library_dir) + continue() + endif() + cmake_path(GET _dependency FILENAME _dependency_name) + if(EXISTS "${_library_dir}/${_dependency_name}" OR + IS_SYMLINK "${_library_dir}/${_dependency_name}") + continue() + endif() + file(COPY "${_dependency}" + DESTINATION "${_library_dir}" + FOLLOW_SYMLINK_CHAIN) +endforeach() + +function(_echoion_is_elf path result_var) + if(IS_SYMLINK "${path}" OR NOT EXISTS "${path}") + set(${result_var} FALSE PARENT_SCOPE) + return() + endif() + file(READ "${path}" _magic OFFSET 0 LIMIT 4 HEX) + string(TOLOWER "${_magic}" _magic) + if(_magic STREQUAL "7f454c46") + set(${result_var} TRUE PARENT_SCOPE) + else() + set(${result_var} FALSE PARENT_SCOPE) + endif() +endfunction() + +# Ensure a SONAME link exists even when CMake resolved a dependency directly to +# its real versioned file instead of the symlink used by DT_NEEDED. +file(GLOB _library_entries LIST_DIRECTORIES FALSE "${_library_dir}/*") +list(SORT _library_entries) +foreach(_entry IN LISTS _library_entries) + _echoion_is_elf("${_entry}" _is_elf) + if(NOT _is_elf) + continue() + endif() + + execute_process( + COMMAND "${PATCHELF_EXECUTABLE}" --print-soname "${_entry}" + RESULT_VARIABLE _soname_result + OUTPUT_VARIABLE _soname + ERROR_VARIABLE _soname_error + OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT _soname_result EQUAL 0) + message(FATAL_ERROR + "Cannot read SONAME from ${_entry}: ${_soname_error}") + endif() + if(NOT _soname STREQUAL "") + if(NOT _soname MATCHES "^[A-Za-z0-9][A-Za-z0-9._+~-]*$") + message(FATAL_ERROR "Unsafe SONAME '${_soname}' in ${_entry}") + endif() + get_filename_component(_entry_name "${_entry}" NAME) + set(_soname_path "${_library_dir}/${_soname}") + if(NOT _entry_name STREQUAL _soname + AND NOT EXISTS "${_soname_path}" + AND NOT IS_SYMLINK "${_soname_path}") + file(CREATE_LINK "${_entry_name}" "${_soname_path}" SYMBOLIC) + endif() + endif() + + execute_process( + COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN" "${_entry}" + RESULT_VARIABLE _patch_result + ERROR_VARIABLE _patch_error) + if(NOT _patch_result EQUAL 0) + message(FATAL_ERROR "Cannot set RUNPATH on ${_entry}: ${_patch_error}") + endif() +endforeach() + +execute_process( + COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN/../lib" "${_executable}" + RESULT_VARIABLE _patch_executable_result + ERROR_VARIABLE _patch_executable_error) +if(NOT _patch_executable_result EQUAL 0) + message(FATAL_ERROR + "Cannot set RUNPATH on ${_executable}: ${_patch_executable_error}") +endif() + +list(LENGTH _resolved_dependencies _dependency_count) +message(STATUS "Bundled ${_dependency_count} resolved runtime dependencies") diff --git a/containers/release.Dockerfile b/containers/release.Dockerfile new file mode 100644 index 0000000..1eb784d --- /dev/null +++ b/containers/release.Dockerfile @@ -0,0 +1,193 @@ +FROM ubuntu:22.04 AS gcc-builder + +ARG DEBIAN_FRONTEND=noninteractive +ARG GCC_VERSION=16.1.0 +ARG GCC_SHA512=b3454958891ab47e1e5b6cb9396c0ad3b04f32fe2a7bf1153a143f21013fdb6b295ca94c98964698a688e4c1d7555ffd8ffbc20187507cce6b1c32cbcc09897a +ARG GCC_BUILD_JOBS=2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + binutils \ + bison \ + build-essential \ + ca-certificates \ + curl \ + flex \ + libgmp-dev \ + libisl-dev \ + libmpc-dev \ + libmpfr-dev \ + libzstd-dev \ + texinfo \ + xz-utils \ + zlib1g-dev \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /tmp/gcc +RUN curl -fsSLO \ + "https://ftp.gnu.org/gnu/gcc/gcc-${GCC_VERSION}/gcc-${GCC_VERSION}.tar.xz" \ + && echo "${GCC_SHA512} gcc-${GCC_VERSION}.tar.xz" | sha512sum -c - \ + && tar -xf "gcc-${GCC_VERSION}.tar.xz" \ + && mkdir build \ + && cd build \ + && "../gcc-${GCC_VERSION}/configure" \ + --prefix="/opt/gcc-${GCC_VERSION}" \ + --disable-bootstrap \ + --disable-multilib \ + --enable-default-pie \ + --enable-default-ssp \ + --enable-languages=c,c++ \ + --with-system-zlib \ + && make -j"${GCC_BUILD_JOBS}" \ + && make install-strip \ + && install -d -m 0755 "/opt/gcc-${GCC_VERSION}/share/licenses/gcc" \ + && install -m 0644 \ + "../gcc-${GCC_VERSION}/COPYING3" \ + "../gcc-${GCC_VERSION}/COPYING.RUNTIME" \ + "../gcc-${GCC_VERSION}/libstdc++-v3/COPYING" \ + "/opt/gcc-${GCC_VERSION}/share/licenses/gcc/" + + +FROM ubuntu:22.04 AS release-builder + +ARG DEBIAN_FRONTEND=noninteractive +ARG GCC_VERSION=16.1.0 +ARG CMAKE_VERSION=4.0.3 +ARG CMAKE_SHA256=585ae9e013107bc8e7c7c9ce872cbdcbdff569e675b07ef57aacfb88c886faac +ARG NODE_VERSION=22.17.0 +ARG NODE_SHA256=325c0f1261e0c61bcae369a1274028e9cfb7ab7949c05512c5b1e630f7e80e12 +ARG FFMPEG_VERSION=8.0.3 +ARG FFMPEG_SHA256=6136812ea6d4e68bdba27e33c2a94382711cdf4f8602ffef056ff792bd6f9818 +ARG FFMPEG_BUILD_JOBS=2 +ARG BOOST_VERSION=1.87.0 +ARG BOOST_VERSION_UNDERSCORE=1_87_0 +ARG BOOST_SHA256=af57be25cb4c4f4b413ed692fe378affb4352ea50fbe294a11ef548f4d527d89 +ARG BOOST_BUILD_JOBS=2 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + binutils \ + bzip2 \ + ca-certificates \ + curl \ + file \ + git \ + gzip \ + jq \ + libcurl4-openssl-dev \ + libgmp10 \ + libisl23 \ + libmpc3 \ + libmpfr6 \ + libopus-dev \ + libsodium-dev \ + libsqlite3-dev \ + libssl-dev \ + libtbb-dev \ + libzstd1 \ + make \ + nasm \ + ninja-build \ + patchelf \ + pkg-config \ + python3 \ + tar \ + xz-utils \ + zstd \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=gcc-builder "/opt/gcc-${GCC_VERSION}" "/opt/gcc-${GCC_VERSION}" + +RUN curl -fsSLO \ + "https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ + && echo "${CMAKE_SHA256} cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" | sha256sum -c - \ + && tar -xzf "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ + -C /usr/local --strip-components=1 \ + && rm "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ + && curl -fsSLO \ + "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \ + && echo "${NODE_SHA256} node-v${NODE_VERSION}-linux-x64.tar.xz" | sha256sum -c - \ + && tar -xJf "node-v${NODE_VERSION}-linux-x64.tar.xz" \ + -C /usr/local --strip-components=1 \ + && rm "node-v${NODE_VERSION}-linux-x64.tar.xz" + +ENV GCC_ROOT="/opt/gcc-${GCC_VERSION}" +ENV PATH="${GCC_ROOT}/bin:${PATH}" \ + LD_LIBRARY_PATH="${GCC_ROOT}/lib64:${GCC_ROOT}/lib" \ + CC="${GCC_ROOT}/bin/gcc" \ + CXX="${GCC_ROOT}/bin/g++" + +RUN test "$(uname -m)" = x86_64 \ + && gcc --version | grep -F "gcc (GCC) 16.1.0" + +RUN curl -fsSLO \ + "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \ + && echo "${FFMPEG_SHA256} ffmpeg-${FFMPEG_VERSION}.tar.xz" | sha256sum -c - \ + && tar -xJf "ffmpeg-${FFMPEG_VERSION}.tar.xz" \ + && cd "ffmpeg-${FFMPEG_VERSION}" \ + && ./configure \ + --prefix="/opt/ffmpeg-${FFMPEG_VERSION}" \ + --cc="${CC}" \ + --cxx="${CXX}" \ + --disable-static \ + --enable-shared \ + --disable-autodetect \ + --disable-programs \ + --disable-doc \ + --disable-debug \ + --disable-avdevice \ + --disable-avfilter \ + --disable-swscale \ + --disable-encoders \ + --disable-muxers \ + --disable-hwaccels \ + --enable-openssl \ + && make -j"${FFMPEG_BUILD_JOBS}" \ + && make install \ + && install -D -m 0644 COPYING.LGPLv2.1 \ + "/opt/ffmpeg-${FFMPEG_VERSION}/share/licenses/ffmpeg/COPYING.LGPLv2.1" \ + && cd / \ + && rm -rf \ + "ffmpeg-${FFMPEG_VERSION}" \ + "ffmpeg-${FFMPEG_VERSION}.tar.xz" + +ENV FFMPEG_ROOT="/opt/ffmpeg-${FFMPEG_VERSION}" \ + PKG_CONFIG_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib/pkgconfig" \ + LD_LIBRARY_PATH="/opt/ffmpeg-${FFMPEG_VERSION}/lib:${LD_LIBRARY_PATH}" + +RUN test "$(pkg-config --modversion libavcodec)" = 62.11.103 \ + && test "$(pkg-config --modversion libavformat)" = 62.3.103 \ + && test "$(pkg-config --modversion libavutil)" = 60.8.103 \ + && test "$(pkg-config --modversion libswresample)" = 6.1.103 + +RUN curl -fsSLO \ + "https://archives.boost.io/release/${BOOST_VERSION}/source/boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \ + && echo "${BOOST_SHA256} boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" | sha256sum -c - \ + && tar -xjf "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \ + && cd "boost_${BOOST_VERSION_UNDERSCORE}" \ + && ./bootstrap.sh --prefix="/opt/boost-${BOOST_VERSION}" \ + && ./b2 -j"${BOOST_BUILD_JOBS}" \ + cxxstd=23 \ + link=shared \ + runtime-link=shared \ + threading=multi \ + variant=release \ + --with-container \ + --with-stacktrace \ + --with-system \ + --with-thread \ + --with-url \ + install \ + && install -D -m 0644 \ + LICENSE_1_0.txt \ + "/opt/boost-${BOOST_VERSION}/share/licenses/boost/LICENSE_1_0.txt" \ + && cd / \ + && rm -rf \ + "boost_${BOOST_VERSION_UNDERSCORE}" \ + "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" + +ENV BOOST_ROOT="/opt/boost-${BOOST_VERSION}" \ + CMAKE_PREFIX_PATH="/opt/boost-${BOOST_VERSION}:${FFMPEG_ROOT}" \ + LD_LIBRARY_PATH="/opt/boost-${BOOST_VERSION}/lib:${LD_LIBRARY_PATH}" + +WORKDIR /workspace diff --git a/packaging/README.md b/packaging/README.md new file mode 100644 index 0000000..3d03731 --- /dev/null +++ b/packaging/README.md @@ -0,0 +1,25 @@ +# Linux installer layout + +`install.sh` and `uninstall.sh` are copied into each Linux release payload. +`service/echoion.service.in` is rendered by the installer for user or system +systemd scope. `tests/installer_test.sh` exercises portable installation, +service opt-in, rollback, tamper protection, preservation, and purge behavior. +System-scoped payloads are normalized to root ownership. Registered-service +prefixes require a trusted path not writable by other identities. Purge uses +recorded directory identity plus an installer marker before removing custom +mutable paths. +Install and uninstall also take a nonblocking advisory lock on the prefix +directory so concurrent lifecycle operations fail before changing the runtime. +Self-contained portable installs add a managed `echoion` launcher and relative +install metadata, allowing a service-free tree to be moved and uninstalled as +one directory. + +Create publishable artifacts from the repository root: + +```bash +scripts/release.sh --version 1.2.3 +``` + +The default command uses the version-pinned release toolchain container and +does not start the bot. Installation flags and data layouts are documented in +the root README. diff --git a/packaging/install.sh b/packaging/install.sh new file mode 100755 index 0000000..14482a3 --- /dev/null +++ b/packaging/install.sh @@ -0,0 +1,1351 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROGRAM=${0##*/} +SERVICE_NAME=echoion.service +SERVICE_USER=echoion +RECORD_NAME=.echoion-install +MANAGED_MARKER=.echoion-managed + +die() { + printf '%s: %s\n' "$PROGRAM" "$*" >&2 + exit 1 +} + +warn() { + printf '%s: warning: %s\n' "$PROGRAM" "$*" >&2 +} + +usage() { + cat <<'EOF' +Usage: install.sh [OPTIONS] + +Install an Echoion release without starting it by default. + +Options: + --mode MODE system, user, or portable (default: user) + --prefix PATH installation root + --data-layout LAYOUT standard or self-contained (default: standard) + --config-dir PATH override the configuration directory + --state-dir PATH override the writable state directory + --register-service SCOPE none, user, or system + --start enable and start the registered service + --non-interactive accept defaults instead of prompting + -h, --help show this help + +System and user installs register a matching service by default. Portable +installs do not register a service unless explicitly requested. Registration +alone leaves the service disabled and stopped; only --start activates it. +EOF +} + +require_value() { + [[ $# -ge 2 && -n $2 ]] || die "$1 requires a value" +} + +validate_choice() { + local value=$1 + local label=$2 + shift 2 + local candidate + for candidate in "$@"; do + [[ $value == "$candidate" ]] && return 0 + done + die "invalid $label '$value' (expected: $*)" +} + +reject_control_characters() { + local label=$1 + local value=$2 + [[ ! $value =~ [[:cntrl:]] ]] || + die "$label contains an unsupported control character" +} + +absolute_path() { + local value=$1 + realpath -m -- "$value" +} + +prompt_value() { + local variable=$1 + local label=$2 + local default_value=$3 + local answer + printf '%s [%s]: ' "$label" "$default_value" >&2 + IFS= read -r answer || true + printf -v "$variable" '%s' "${answer:-$default_value}" +} + +prompt_yes_no() { + local variable=$1 + local label=$2 + local answer + printf '%s [y/N]: ' "$label" >&2 + IFS= read -r answer || true + case $answer in + y | Y | yes | YES | Yes) printf -v "$variable" '%s' 1 ;; + *) printf -v "$variable" '%s' 0 ;; + esac +} + +manifest_version() { + local manifest=$1 + local line + while IFS= read -r line; do + if [[ $line =~ \"version\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + printf '%s\n' "${BASH_REMATCH[1]}" + return 0 + fi + done < "$manifest" + return 1 +} + +manifest_is_v2_with_files() { + local manifest=$1 + local line + local schema_ok=0 + local files_ok=0 + while IFS= read -r line; do + if [[ $line =~ \"schemaVersion\"[[:space:]]*:[[:space:]]*2([,[:space:]]|$) ]]; then + schema_ok=1 + fi + if [[ $line =~ \"path\"[[:space:]]*:[[:space:]]*\"[^\"]+\" ]]; then + files_ok=1 + fi + done < "$manifest" + [[ $schema_ok -eq 1 && $files_ok -eq 1 ]] +} + +sha256_file() { + local result + result=$(sha256sum -- "$1") + printf '%s\n' "${result%% *}" +} + +json_escape() { + local value=$1 + value=${value//\\/\\\\} + value=${value//\"/\\\"} + printf '%s' "$value" +} + +systemd_setting_escape() { + local value=$1 + value=${value//\\/\\\\} + value=${value//\"/\\\"} + value=${value//%/%%} + printf '%s' "$value" +} + +systemd_exec_escape() { + local value + value=$(systemd_setting_escape "$1") + value=${value//\$/\$\$} + printf '%s' "$value" +} + +render_config() { + local source=$1 + local destination=$2 + local web_root=$3 + local escaped + local temporary + local line + local found=0 + escaped=$(json_escape "$web_root") + temporary=$(mktemp --tmpdir="$(dirname -- "$destination")" '.config.json.XXXXXX') + while IFS= read -r line || [[ -n $line ]]; do + if [[ $line =~ ^([[:space:]]*)\"webRoot\"[[:space:]]*: ]]; then + printf '%s"webRoot": "%s",\n' "${BASH_REMATCH[1]}" "$escaped" >> "$temporary" + found=$((found + 1)) + else + printf '%s\n' "$line" >> "$temporary" + fi + done < "$source" + if [[ $found -ne 1 ]]; then + rm -f -- "$temporary" + die "configuration template has no unique webRoot field" + fi + chmod 0600 "$temporary" + mv -f -- "$temporary" "$destination" +} + +effective_uid() { + printf '%s\n' "${EUID:-$(id -u)}" +} + +validate_registration_identity() { + local scope=$1 + local uid=$2 + if [[ $scope == user && $uid -eq 0 ]]; then + die "refusing to register a root user service; use system scope instead" + fi +} + +validate_trusted_path_ancestors() { + local scope=$1 + local path=$2 + local service_uid=$3 + local require_leaf_owner=${4:-0} + local current owner mode root_owner + + root_owner=$(stat -c '%u' -- /) + current=$path + while [[ ! -e $current ]]; do + [[ $current != / ]] || break + current=$(dirname -- "$current") + done + + while :; do + [[ -d $current && ! -L $current ]] || + die "service path component is not a real directory: '$current'" + owner=$(stat -c '%u' -- "$current") + mode=$(stat -c '%a' -- "$current") + if (( (8#$mode & 0022) != 0 )); then + die "service path component is group/world-writable: '$current'" + fi + if [[ $scope == system ]]; then + [[ $owner -eq $root_owner ]] || + die "system service path is not owned by root: '$current'" + elif [[ $owner -ne $root_owner && $owner -ne $service_uid ]]; then + die "user service path has an untrusted owner: '$current'" + fi + [[ $current != / ]] || break + current=$(dirname -- "$current") + done + + if [[ $require_leaf_owner -eq 1 ]]; then + owner=$(stat -c '%u' -- "$path") + if [[ $scope == system ]]; then + [[ $owner -eq $root_owner ]] || die "system service prefix is not owned by root: '$path'" + else + [[ $owner -eq $service_uid ]] || + die "user service prefix is not owned by uid $service_uid: '$path'" + fi + fi +} + +acquire_prefix_lock() { + local lock_prefix=$1 + command -v flock >/dev/null 2>&1 || die "flock is required for safe installation" + exec {INSTALL_LOCK_FD}< "$lock_prefix" + flock -n "$INSTALL_LOCK_FD" || die "another Echoion install or uninstall is active for '$lock_prefix'" +} + +reject_temporary_prefix() { + local prefix=$1 + local candidate + for candidate in /tmp /var/tmp /dev/shm /run "${TMPDIR:-}" "${XDG_RUNTIME_DIR:-}"; do + [[ -n $candidate ]] || continue + candidate=$(absolute_path "$candidate") + case $prefix in + "$candidate" | "$candidate"/*) + die "refusing to register a service from temporary path '$prefix'" + ;; + esac + done +} + +validate_mutable_path_ancestors() { + local scope=$1 + local path=$2 + local service_uid=$3 + local existing=$path + if [[ -e $existing || -L $existing ]]; then + existing=$(dirname -- "$existing") + else + while [[ ! -e $existing ]]; do + [[ $existing != / ]] || break + existing=$(dirname -- "$existing") + done + fi + validate_trusted_path_ancestors "$scope" "$existing" "$service_uid" 0 +} + +validate_mutable_directory() { + local scope=$1 + local path=$2 + local expected_uid=$3 + local service_uid=$4 + local owner mode + [[ -d $path && ! -L $path ]] || die "mutable service path is not a real directory: '$path'" + owner=$(stat -c '%u' -- "$path") + mode=$(stat -c '%a' -- "$path") + [[ $owner -eq $expected_uid ]] || die "mutable service path has the wrong owner: '$path'" + (( (8#$mode & 0022) == 0 )) || + die "mutable service path is group/world-writable: '$path'" + validate_trusted_path_ancestors "$scope" "$(dirname -- "$path")" "$service_uid" 0 +} + +systemctl_for() { + local scope=$1 + shift + if [[ $scope == user ]]; then + systemctl --user "$@" + else + systemctl "$@" + fi +} + +safe_recorded_unit_path() { + local scope=$1 + local unit=$2 + [[ $unit == /* && $unit != *'/../'* && $unit != *'/./'* ]] || return 1 + case $scope:$unit in + system:/etc/systemd/system/echoion.service) return 0 ;; + user:/*/systemd/user/echoion.service) return 0 ;; + *) return 1 ;; + esac +} + +render_unit() { + local template=$1 + local destination=$2 + local scope=$3 + local home=$4 + local core=$5 + local state=$6 + local executable=$7 + local config=$8 + local escaped_home escaped_core escaped_state escaped_executable escaped_config + local escaped_exec_state + local line + escaped_home=$(systemd_setting_escape "$home") + escaped_core=$(systemd_setting_escape "$core") + escaped_state=$(systemd_setting_escape "$state") + escaped_executable=$(systemd_exec_escape "$executable") + escaped_config=$(systemd_exec_escape "$config") + escaped_exec_state=$(systemd_exec_escape "$state") + : > "$destination" + while IFS= read -r line || [[ -n $line ]]; do + case $line in + @SERVICE_IDENTITY@) + if [[ $scope == system ]]; then + printf 'User=%s\nGroup=%s\n' "$SERVICE_USER" "$SERVICE_USER" >> "$destination" + fi + ;; + @WORKING_DIRECTORY@) + printf 'WorkingDirectory="%s"\n' "$escaped_home" >> "$destination" + ;; + @ENVIRONMENT_HOME@) + printf 'Environment="ECHOION_HOME=%s"\n' "$escaped_home" >> "$destination" + ;; + @ENVIRONMENT_CORE@) + printf 'Environment="ECHOION_CORE_PATH=%s"\n' "$escaped_core" >> "$destination" + ;; + @ENVIRONMENT_STATE@) + printf 'Environment="ECHOION_STATE_DIR=%s"\n' "$escaped_state" >> "$destination" + ;; + @EXEC_START@) + printf 'ExecStart="%s" --config "%s" --state-dir "%s"\n' \ + "$escaped_executable" "$escaped_config" "$escaped_exec_state" >> "$destination" + ;; + @INSTALL_TARGET@) + if [[ $scope == system ]]; then + printf 'WantedBy=multi-user.target\n' >> "$destination" + else + printf 'WantedBy=default.target\n' >> "$destination" + fi + ;; + *) printf '%s\n' "$line" >> "$destination" ;; + esac + done < "$template" +} + +render_portable_launcher() { + local destination=$1 + cat > "$destination" <<'EOF' +#!/usr/bin/env bash +# Echoion portable launcher +set -euo pipefail + +die() { + printf 'echoion: %s\n' "$*" >&2 + exit 1 +} + +launcher=$(realpath -e -- "${BASH_SOURCE[0]}") || die 'cannot resolve launcher path' +prefix=$(cd -P -- "$(dirname -- "$launcher")" && pwd -P) || + die 'cannot resolve portable prefix' +[[ $prefix != / ]] || die 'refusing to run from the filesystem root' +current=$prefix/current +versions=$prefix/versions +[[ -d $versions && ! -L $versions ]] || + die "versions directory is missing or unsafe: $versions" +[[ -L $current ]] || die "current release link is missing: $current" +target=$(readlink -- "$current") +[[ $target =~ ^versions/[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || + die "unsafe current release target: $target" +daemon=$current/bin/echoiond +config=$prefix/config/config.json +state=$prefix/data +core=$current/lib/Echoion.ts +[[ -x $daemon ]] || die "daemon is missing or not executable: $daemon" +[[ -f $config && ! -L $config ]] || die "configuration is missing or unsafe: $config" +[[ -d $state && ! -L $state ]] || die "state directory is missing or unsafe: $state" +[[ -f $core ]] || die "Core library is missing: $core" +for argument in "$@"; do + case $argument in + --config | --config=* | --state-dir | --state-dir=*) + die "$argument is managed by the portable launcher" + ;; + esac +done +export ECHOION_HOME=$current +export ECHOION_CORE_PATH=$core +export ECHOION_STATE_DIR=$state +exec "$daemon" --config "$config" --state-dir "$state" "$@" +EOF +} + +load_old_record() { + local record=$1 + local key value + OLD_PREFIX= + OLD_SERVICE_SCOPE=none + OLD_SERVICE_UNIT= + OLD_SERVICE_SHA256= + OLD_CREATED_SYSTEM_USER=0 + OLD_SERVICE_UID= + OLD_SERVICE_GID= + OLD_INSTALL_ID= + OLD_CONFIG_PURGE_ALLOWED=0 + OLD_CONFIG_DIR_DEVICE= + OLD_CONFIG_DIR_INODE= + OLD_CONFIG_DIR_UID= + OLD_CONFIG_DIR_GID= + OLD_CONFIG_MARKER_SHA256= + OLD_STATE_PURGE_ALLOWED=0 + OLD_STATE_DIR_DEVICE= + OLD_STATE_DIR_INODE= + OLD_STATE_DIR_UID= + OLD_STATE_DIR_GID= + OLD_STATE_MARKER_SHA256= + OLD_RELOCATABLE=0 + OLD_LAUNCHER= + OLD_LAUNCHER_SHA256= + [[ -f $record ]] || return 0 + while IFS='=' read -r key value; do + case $key in + prefix) OLD_PREFIX=$value ;; + service_scope) OLD_SERVICE_SCOPE=$value ;; + service_unit) OLD_SERVICE_UNIT=$value ;; + service_unit_sha256) OLD_SERVICE_SHA256=$value ;; + created_system_user) OLD_CREATED_SYSTEM_USER=$value ;; + service_uid) OLD_SERVICE_UID=$value ;; + service_gid) OLD_SERVICE_GID=$value ;; + install_id) OLD_INSTALL_ID=$value ;; + config_purge_allowed) OLD_CONFIG_PURGE_ALLOWED=$value ;; + config_dir_device) OLD_CONFIG_DIR_DEVICE=$value ;; + config_dir_inode) OLD_CONFIG_DIR_INODE=$value ;; + config_dir_uid) OLD_CONFIG_DIR_UID=$value ;; + config_dir_gid) OLD_CONFIG_DIR_GID=$value ;; + config_marker_sha256) OLD_CONFIG_MARKER_SHA256=$value ;; + state_purge_allowed) OLD_STATE_PURGE_ALLOWED=$value ;; + state_dir_device) OLD_STATE_DIR_DEVICE=$value ;; + state_dir_inode) OLD_STATE_DIR_INODE=$value ;; + state_dir_uid) OLD_STATE_DIR_UID=$value ;; + state_dir_gid) OLD_STATE_DIR_GID=$value ;; + state_marker_sha256) OLD_STATE_MARKER_SHA256=$value ;; + relocatable) OLD_RELOCATABLE=$value ;; + launcher) OLD_LAUNCHER=$value ;; + launcher_sha256) OLD_LAUNCHER_SHA256=$value ;; + esac + done < "$record" + case $OLD_RELOCATABLE in + 0) + [[ $OLD_PREFIX == "$prefix" ]] || + die "install record belongs to '$OLD_PREFIX', not '$prefix'" + ;; + 1) + [[ $OLD_PREFIX == . ]] || die "relocatable install record has an unsafe prefix" + ;; + *) die "install record has an invalid relocatable value" ;; + esac +} + +verify_recorded_unit() { + local scope=$1 + local unit=$2 + local expected_hash=$3 + [[ -n $unit && -n $expected_hash ]] || die "existing service record is incomplete" + safe_recorded_unit_path "$scope" "$unit" || die "existing service record has an unsafe unit path" + [[ -f $unit ]] || die "recorded service unit is missing: $unit" + [[ $(sha256_file "$unit") == "$expected_hash" ]] || + die "recorded service unit was modified; refusing to overwrite it: $unit" +} + +verify_recorded_launcher() { + local launcher=$1 + local expected_hash=$2 + local path + [[ $launcher == echoion && $expected_hash =~ ^[0-9a-f]{64}$ ]] || + die "existing portable launcher record is incomplete or unsafe" + path=$prefix/$launcher + [[ -f $path && ! -L $path && -x $path ]] || + die "recorded portable launcher is missing or unsafe: $path" + [[ $(sha256_file "$path") == "$expected_hash" ]] || + die "recorded portable launcher was modified; refusing to overwrite it: $path" +} + +remove_recorded_service() { + local scope=$1 + local unit=$2 + local expected_hash=$3 + verify_recorded_unit "$scope" "$unit" "$expected_hash" + systemctl_for "$scope" disable --now "$SERVICE_NAME" || return 1 + rm -f -- "$unit" || return 1 + systemctl_for "$scope" daemon-reload || return 1 +} + +ensure_system_user() { + local state=$1 + local passwd_entry shell group_gid + if id -u "$SERVICE_USER" >/dev/null 2>&1; then + SERVICE_UID=$(id -u "$SERVICE_USER") + SERVICE_GID=$(id -g "$SERVICE_USER") + passwd_entry=$(getent passwd "$SERVICE_USER") || + die "could not inspect existing $SERVICE_USER account" + IFS=: read -r _ _ _ _ _ _ shell <<< "$passwd_entry" + case ${shell##*/} in + nologin | false) ;; + *) die "existing $SERVICE_USER account does not use a non-login shell" ;; + esac + group_gid=$(getent group "$SERVICE_USER" | cut -d: -f3) || true + [[ -n $group_gid && $group_gid -eq $SERVICE_GID ]] || + die "existing $SERVICE_USER account has no matching primary group" + if [[ ${OLD_CREATED_SYSTEM_USER:-0} == 1 ]]; then + [[ ${OLD_SERVICE_UID:-} =~ ^[0-9]+$ && ${OLD_SERVICE_GID:-} =~ ^[0-9]+$ ]] || + die "installer-created service account record has no uid/gid identity" + [[ $SERVICE_UID -eq $OLD_SERVICE_UID && $SERVICE_GID -eq $OLD_SERVICE_GID ]] || + die "the recorded $SERVICE_USER account was deleted or replaced" + fi + return 0 + fi + local nologin=/usr/sbin/nologin + [[ -x $nologin ]] || nologin=/sbin/nologin + useradd --system --user-group --home-dir "$state" --shell "$nologin" \ + --no-create-home "$SERVICE_USER" + CREATED_SYSTEM_USER=1 + ACCOUNT_CREATED_THIS_RUN=1 + SERVICE_UID=$(id -u "$SERVICE_USER") + SERVICE_GID=$(id -g "$SERVICE_USER") + ACCOUNT_IDENTITY_CAPTURED=1 +} + +remove_new_system_user() { + [[ ${ACCOUNT_CREATED_THIS_RUN:-0} -eq 1 ]] || return 0 + if [[ ${ACCOUNT_IDENTITY_CAPTURED:-0} -eq 0 ]]; then + userdel "$SERVICE_USER" || warn "could not remove newly created $SERVICE_USER account" + elif id -u "$SERVICE_USER" >/dev/null 2>&1 && + [[ $(id -u "$SERVICE_USER") -eq ${SERVICE_UID:-999999} ]] && + [[ $(id -g "$SERVICE_USER") -eq ${SERVICE_GID:-999999} ]]; then + userdel "$SERVICE_USER" || warn "could not remove newly created $SERVICE_USER account" + else + warn "new $SERVICE_USER account identity changed; refusing automatic deletion" + fi +} + +validate_service_access() { + local scope=$1 + local executable=$2 + local config=$3 + local state=$4 + if [[ $scope == user ]]; then + [[ -x $executable ]] || die "service user cannot execute '$executable'" + [[ -r $config ]] || die "service user cannot read '$config'" + [[ -w $state ]] || die "service user cannot write '$state'" + return 0 + fi + command -v runuser >/dev/null 2>&1 || + die "runuser is required to validate the system service account" + runuser -u "$SERVICE_USER" -- test -x "$executable" || + die "$SERVICE_USER cannot traverse the prefix or execute echoiond" + runuser -u "$SERVICE_USER" -- test -r "$config" || + die "$SERVICE_USER cannot read '$config'" + runuser -u "$SERVICE_USER" -- test -w "$state" || + die "$SERVICE_USER cannot write '$state'" +} + +normalize_and_validate_system_runtime() { + local root=$1 + local foreign writable path + chown -R root:root -- "$root" + foreign=$(find "$root" \( ! -uid 0 -o ! -gid 0 \) -print -quit) + [[ -z $foreign ]] || die "immutable runtime entry is not root-owned: '$foreign'" + foreign=$(find "$root" ! -type l -perm /022 -print -quit) + [[ -z $foreign ]] || die "immutable runtime entry is group/world-writable: '$foreign'" + writable=$(runuser -u "$SERVICE_USER" -- find "$root" -writable -print -quit) || + die "could not verify immutable runtime permissions as $SERVICE_USER" + [[ -z $writable ]] || die "$SERVICE_USER can modify immutable runtime entry: '$writable'" + for path in "$root" "$(dirname -- "$root")" "$(dirname -- "$(dirname -- "$root")")"; do + if runuser -u "$SERVICE_USER" -- test -w "$path"; then + die "$SERVICE_USER can replace immutable runtime path: '$path'" + fi + done +} + +new_install_id() { + local value + if [[ -r /proc/sys/kernel/random/uuid ]]; then + IFS= read -r value < /proc/sys/kernel/random/uuid + else + value=$(printf '%s:%s:%s:%s' "$prefix" "$$" "$RANDOM" "$(date +%s%N)" | + sha256sum) + value=${value%% *} + fi + printf '%s\n' "$value" +} + +write_managed_marker() { + local directory=$1 + local marker=$directory/$MANAGED_MARKER + local temporary + temporary=$(mktemp --tmpdir="$directory" '.echoion-managed.XXXXXX') + { + printf 'format=1\n' + printf 'install_id=%s\n' "$INSTALL_ID" + printf 'relocatable=%s\n' "$RELOCATABLE" + printf 'prefix=%s\n' "$INSTALL_RECORD_PREFIX" + } > "$temporary" + chmod 0600 "$temporary" + mv -f -- "$temporary" "$marker" +} + +marker_matches() { + local directory=$1 + local expected_hash=$2 + local marker=$directory/$MANAGED_MARKER + [[ -f $marker && ! -L $marker && -n $expected_hash ]] || return 1 + [[ $(sha256_file "$marker") == "$expected_hash" ]] || return 1 + grep -Fx -- "install_id=$INSTALL_ID" "$marker" >/dev/null || return 1 + grep -Fx -- "prefix=$INSTALL_RECORD_PREFIX" "$marker" >/dev/null +} + +capture_managed_directory() { + local kind=$1 + local directory=$2 + local old_allowed=$3 + local old_device=$4 + local old_inode=$5 + local old_uid=$6 + local old_gid=$7 + local old_marker_hash=$8 + local created=$9 + local allowed=0 marker_hash='' device inode uid gid + + device=$(stat -c '%d' -- "$directory") + inode=$(stat -c '%i' -- "$directory") + uid=$(stat -c '%u' -- "$directory") + gid=$(stat -c '%g' -- "$directory") + if [[ $old_allowed == 1 && $device == "$old_device" && $inode == "$old_inode" && + $uid == "$old_uid" && $gid == "$old_gid" ]] && marker_matches "$directory" "$old_marker_hash"; then + allowed=1 + marker_hash=$old_marker_hash + elif [[ $created -eq 1 ]]; then + write_managed_marker "$directory" + allowed=1 + marker_hash=$(sha256_file "$directory/$MANAGED_MARKER") + elif [[ $old_allowed == 1 ]]; then + warn "$kind directory identity changed; disabling automatic purge for '$directory'" + fi + + printf -v "${kind^^}_PURGE_ALLOWED" '%s' "$allowed" + printf -v "${kind^^}_DIR_DEVICE" '%s' "$device" + printf -v "${kind^^}_DIR_INODE" '%s' "$inode" + printf -v "${kind^^}_DIR_UID" '%s' "$uid" + printf -v "${kind^^}_DIR_GID" '%s' "$gid" + printf -v "${kind^^}_MARKER_SHA256" '%s' "$marker_hash" +} + +snapshot_path_metadata() { + local path=$1 + [[ -e $path && ! -L $path ]] || return 0 + stat -c '%d:%i:%u:%g:%a' -- "$path" +} + +restore_path_metadata() { + local path=$1 + local snapshot=$2 + local expected_device expected_inode uid gid mode current_device current_inode + [[ -n $snapshot ]] || return 0 + IFS=: read -r expected_device expected_inode uid gid mode <<< "$snapshot" + [[ -e $path && ! -L $path ]] || return 1 + current_device=$(stat -c '%d' -- "$path") || return 1 + current_inode=$(stat -c '%i' -- "$path") || return 1 + [[ $current_device == "$expected_device" && $current_inode == "$expected_inode" ]] || return 1 + chown "$uid:$gid" -- "$path" || return 1 + chmod "$mode" -- "$path" +} + +write_record() { + local destination=$1 + local temporary + local unit=$2 + local unit_hash=$3 + temporary=$(mktemp --tmpdir="$(dirname -- "$destination")" '.echoion-install.XXXXXX') + RECORD_TEMPORARY=$temporary + umask 077 + { + printf 'format=1\n' + printf 'mode=%s\n' "$mode" + printf 'relocatable=%s\n' "$RELOCATABLE" + printf 'prefix=%s\n' "$INSTALL_RECORD_PREFIX" + printf 'version=%s\n' "$version" + printf 'data_layout=%s\n' "$data_layout" + printf 'config_dir=%s\n' "$INSTALL_RECORD_CONFIG_DIR" + printf 'state_dir=%s\n' "$INSTALL_RECORD_STATE_DIR" + printf 'config_created=%s\n' "$CONFIG_CREATED" + printf 'service_scope=%s\n' "$register_service" + printf 'service_name=%s\n' "$SERVICE_NAME" + printf 'service_unit=%s\n' "$unit" + printf 'service_unit_sha256=%s\n' "$unit_hash" + printf 'created_system_user=%s\n' "$CREATED_SYSTEM_USER" + printf 'service_uid=%s\n' "$SERVICE_UID" + printf 'service_gid=%s\n' "$SERVICE_GID" + printf 'install_id=%s\n' "$INSTALL_ID" + printf 'config_purge_allowed=%s\n' "$CONFIG_PURGE_ALLOWED" + printf 'config_dir_device=%s\n' "$CONFIG_DIR_DEVICE" + printf 'config_dir_inode=%s\n' "$CONFIG_DIR_INODE" + printf 'config_dir_uid=%s\n' "$CONFIG_DIR_UID" + printf 'config_dir_gid=%s\n' "$CONFIG_DIR_GID" + printf 'config_marker_sha256=%s\n' "$CONFIG_MARKER_SHA256" + printf 'state_purge_allowed=%s\n' "$STATE_PURGE_ALLOWED" + printf 'state_dir_device=%s\n' "$STATE_DIR_DEVICE" + printf 'state_dir_inode=%s\n' "$STATE_DIR_INODE" + printf 'state_dir_uid=%s\n' "$STATE_DIR_UID" + printf 'state_dir_gid=%s\n' "$STATE_DIR_GID" + printf 'state_marker_sha256=%s\n' "$STATE_MARKER_SHA256" + printf 'launcher=%s\n' "$LAUNCHER_RECORD_PATH" + printf 'launcher_sha256=%s\n' "$LAUNCHER_SHA256" + } > "$temporary" + chmod 0600 "$temporary" + mv -f -- "$temporary" "$destination" + RECORD_TEMPORARY= +} + +if [[ ${BASH_SOURCE[0]} != "$0" ]]; then + return 0 +fi + +mode=user +mode_set=0 +prefix= +prefix_set=0 +data_layout=standard +data_layout_set=0 +config_dir= +state_dir= +register_service= +register_service_set=0 +start=0 +start_set=0 +non_interactive=0 + +while [[ $# -gt 0 ]]; do + case $1 in + --mode) + require_value "$@" + mode=$2 + mode_set=1 + shift 2 + ;; + --prefix) + require_value "$@" + prefix=$2 + prefix_set=1 + shift 2 + ;; + --data-layout) + require_value "$@" + data_layout=$2 + data_layout_set=1 + shift 2 + ;; + --config-dir) + require_value "$@" + config_dir=$2 + shift 2 + ;; + --state-dir) + require_value "$@" + state_dir=$2 + shift 2 + ;; + --register-service) + require_value "$@" + register_service=$2 + register_service_set=1 + shift 2 + ;; + --start) + start=1 + start_set=1 + shift + ;; + --non-interactive) + non_interactive=1 + shift + ;; + -h | --help) + usage + exit 0 + ;; + --) + shift + [[ $# -eq 0 ]] || die "unexpected positional arguments: $*" + ;; + *) die "unknown option: $1" ;; + esac +done + +if [[ $non_interactive -eq 0 && -t 0 && -t 1 ]]; then + [[ $mode_set -eq 1 ]] || prompt_value mode 'Install mode (system/user/portable)' user + validate_choice "$mode" mode system user portable + case $mode in + system) default_prefix=/opt/echoion ;; + user) default_prefix=${HOME:?HOME is required}/.local/opt/echoion ;; + portable) default_prefix=$PWD/echoion ;; + esac + [[ $prefix_set -eq 1 ]] || prompt_value prefix 'Install prefix' "$default_prefix" + [[ $data_layout_set -eq 1 ]] || + prompt_value data_layout 'Data layout (standard/self-contained)' standard + if [[ $register_service_set -eq 0 ]]; then + case $mode in + system) default_service=system ;; + user) default_service=user ;; + portable) default_service=none ;; + esac + prompt_value register_service 'Register service (none/user/system)' "$default_service" + fi + [[ $start_set -eq 1 ]] || prompt_yes_no start 'Enable and start the service now' +fi + +validate_choice "$mode" mode system user portable +validate_choice "$data_layout" data-layout standard self-contained +if [[ -z $register_service ]]; then + case $mode in + system) register_service=system ;; + user) register_service=user ;; + portable) register_service=none ;; + esac +fi +validate_choice "$register_service" service-scope none user system +[[ $start -eq 0 || $register_service != none ]] || die "--start requires a registered service" +INSTALL_UID=$(effective_uid) +validate_registration_identity "$register_service" "$INSTALL_UID" + +case $mode in + system) default_prefix=/opt/echoion ;; + user) default_prefix=${HOME:?HOME is required}/.local/opt/echoion ;; + portable) default_prefix=$PWD/echoion ;; +esac +prefix=${prefix:-$default_prefix} +reject_control_characters prefix "$prefix" +prefix=$(absolute_path "$prefix") +[[ $prefix != / ]] || die "the filesystem root cannot be an install prefix" + +if [[ $mode == system || $register_service == system ]]; then + [[ $INSTALL_UID -eq 0 ]] || die "system installation/service registration requires root" +fi + +RUNTIME_TRUST_SCOPE=$register_service +if [[ $RUNTIME_TRUST_SCOPE == none && $mode == system ]]; then + RUNTIME_TRUST_SCOPE=system +fi +if [[ $RUNTIME_TRUST_SCOPE != none ]]; then + reject_temporary_prefix "$prefix" + validate_trusted_path_ancestors "$RUNTIME_TRUST_SCOPE" "$prefix" "$INSTALL_UID" 0 +fi + +if [[ $data_layout == self-contained ]]; then + default_config_dir=$prefix/config + default_state_dir=$prefix/data +elif [[ $mode == system || $register_service == system ]]; then + default_config_dir=/etc/echoion + default_state_dir=/var/lib/echoion +else + default_config_dir=${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config}/echoion + default_state_dir=${XDG_STATE_HOME:-${HOME:?HOME is required}/.local/state}/echoion +fi +config_dir=${config_dir:-$default_config_dir} +state_dir=${state_dir:-$default_state_dir} +reject_control_characters config-dir "$config_dir" +reject_control_characters state-dir "$state_dir" +config_dir=$(absolute_path "$config_dir") +state_dir=$(absolute_path "$state_dir") +[[ $config_dir != / && $state_dir != / ]] || die "config/state directory cannot be '/'" +for mutable_path in "$config_dir" "$state_dir"; do + case $mutable_path in + /etc | /var | /usr | /usr/local | /opt | /home | /root | /tmp | /var/tmp | /run) + die "config/state directory must be a dedicated Echoion directory: '$mutable_path'" + ;; + esac + case $prefix in + "$mutable_path" | "$mutable_path"/*) + die "config/state directories cannot contain the installation prefix" + ;; + esac + case $mutable_path in + "$prefix" | "$prefix/current" | "$prefix/current"/* | "$prefix/versions" | "$prefix/versions"/*) + die "config/state directories cannot be placed in the immutable runtime tree" + ;; + esac +done +if [[ $RUNTIME_TRUST_SCOPE != none ]]; then + validate_mutable_path_ancestors "$RUNTIME_TRUST_SCOPE" "$config_dir" "$INSTALL_UID" + validate_mutable_path_ancestors "$RUNTIME_TRUST_SCOPE" "$state_dir" "$INSTALL_UID" +fi +config_file=$config_dir/config.json +RELOCATABLE=0 +INSTALL_RECORD_PREFIX=$prefix +INSTALL_RECORD_CONFIG_DIR=$config_dir +INSTALL_RECORD_STATE_DIR=$state_dir +if [[ $mode == portable && $data_layout == self-contained && + $config_dir == "$prefix/config" && $state_dir == "$prefix/data" ]]; then + RELOCATABLE=1 + INSTALL_RECORD_PREFIX=. + INSTALL_RECORD_CONFIG_DIR=config + INSTALL_RECORD_STATE_DIR=data +fi + +SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +PAYLOAD_ROOT=$SCRIPT_DIR +manifest=$PAYLOAD_ROOT/manifest.json +[[ -f $manifest ]] || die "payload manifest is missing: $manifest" +version=$(manifest_version "$manifest") || die "payload manifest has no version" +[[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || die "unsafe release version '$version'" +manifest_is_v2_with_files "$manifest" || + die "payload manifest must use schemaVersion 2 and contain files" +[[ -x $PAYLOAD_ROOT/bin/echoiond ]] || die "payload executable is missing or not executable" +[[ -f $PAYLOAD_ROOT/lib/Echoion.ts ]] || die "payload Core library is missing" +[[ -f $PAYLOAD_ROOT/share/echoion/config.example.json ]] || die "configuration template is missing" +[[ -d $PAYLOAD_ROOT/share/echoion/web ]] || die "web assets are missing" +[[ -f $PAYLOAD_ROOT/service/echoion.service.in ]] || die "service template is missing" +[[ -x $PAYLOAD_ROOT/uninstall.sh ]] || die "payload uninstaller is missing or not executable" +if ! "$PAYLOAD_ROOT/bin/echoiond" --validate-install "$PAYLOAD_ROOT"; then + die "offline source payload validation failed for Echoion $version" +fi + +CREATED_SYSTEM_USER=0 +ACCOUNT_CREATED_THIS_RUN=0 +ACCOUNT_IDENTITY_CAPTURED=0 +SERVICE_UID= +SERVICE_GID= +CONFIG_CREATED=0 +CONFIG_DIR_CREATED=0 +STATE_DIR_CREATED=0 +CONFIG_DIR_METADATA_SNAPSHOT= +STATE_DIR_METADATA_SNAPSHOT= +CONFIG_FILE_METADATA_SNAPSHOT= +DESTINATION_CREATED=0 +TRANSACTION_ACTIVE=0 +INSTALL_COMMITTED=0 +NEW_UNIT_MUTATION_ARMED=0 +OLD_SERVICE_MUTATION_ARMED=0 +HELPER_MUTATION_ARMED=0 +LAUNCHER_MUTATION_ARMED=0 +RECORD_TEMPORARY= +UNIT_TEMPORARY= +INSTALL_HELPER_TEMPORARY= +UNINSTALL_HELPER_TEMPORARY= +LAUNCHER_TEMPORARY= +LAUNCHER_PATH=$prefix/echoion +LAUNCHER_RECORD_PATH= +LAUNCHER_SHA256= +WANT_LAUNCHER=$RELOCATABLE +STAGING= +TRANSACTION_BACKUP_DIR= + +restore_current_link() { + local target=$1 + local temporary_directory + if [[ -z $target ]]; then + rm -f -- "$prefix/current" + return + fi + temporary_directory=$(mktemp -d --tmpdir="$prefix" '.current-rollback.XXXXXX') || return + ln -s -- "$target" "$temporary_directory/current" || return + mv -Tf -- "$temporary_directory/current" "$prefix/current" || return + rmdir -- "$temporary_directory" || true +} + +rollback_install() { + set +e + if [[ $NEW_UNIT_MUTATION_ARMED -eq 1 ]]; then + systemctl_for "$register_service" disable --now "$SERVICE_NAME" || true + if [[ -f $TRANSACTION_BACKUP_DIR/new-scope-unit ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/new-scope-unit" "$unit_path" + else + rm -f -- "$unit_path" + fi + systemctl_for "$register_service" daemon-reload || true + fi + if [[ $OLD_SERVICE_MUTATION_ARMED -eq 1 && -f $TRANSACTION_BACKUP_DIR/old-scope-unit ]]; then + install -d -m 0755 -- "$(dirname -- "$OLD_SERVICE_UNIT")" + cp -a -- "$TRANSACTION_BACKUP_DIR/old-scope-unit" "$OLD_SERVICE_UNIT" + systemctl_for "$OLD_SERVICE_SCOPE" daemon-reload || true + fi + if [[ $HELPER_MUTATION_ARMED -eq 1 ]]; then + if [[ -f $TRANSACTION_BACKUP_DIR/install-helper ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/install-helper" "$prefix/install.sh" + else + rm -f -- "$prefix/install.sh" + fi + if [[ -f $TRANSACTION_BACKUP_DIR/uninstall-helper ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/uninstall-helper" "$prefix/uninstall.sh" + else + rm -f -- "$prefix/uninstall.sh" + fi + fi + if [[ $LAUNCHER_MUTATION_ARMED -eq 1 ]]; then + if [[ -f $TRANSACTION_BACKUP_DIR/launcher ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/launcher" "$LAUNCHER_PATH" + else + rm -f -- "$LAUNCHER_PATH" + fi + fi + restore_current_link "$old_current" + if [[ -f $TRANSACTION_BACKUP_DIR/install-record ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/install-record" "$record" + else + rm -f -- "$record" + fi + if [[ -n ${OLD_SERVICE_UNIT:-} && -f ${OLD_SERVICE_UNIT:-} ]]; then + if [[ $OLD_SERVICE_WAS_ENABLED -eq 1 ]]; then + systemctl_for "$OLD_SERVICE_SCOPE" enable "$SERVICE_NAME" || true + else + systemctl_for "$OLD_SERVICE_SCOPE" disable "$SERVICE_NAME" || true + fi + if [[ $OLD_SERVICE_WAS_ACTIVE -eq 1 ]]; then + systemctl_for "$OLD_SERVICE_SCOPE" restart "$SERVICE_NAME" || true + else + systemctl_for "$OLD_SERVICE_SCOPE" stop "$SERVICE_NAME" || true + fi + fi +} + +cleanup_install() { + local status=$? + trap - EXIT + if [[ $status -ne 0 && $TRANSACTION_ACTIVE -eq 1 && $INSTALL_COMMITTED -eq 0 ]]; then + rollback_install + fi + [[ -z $RECORD_TEMPORARY ]] || rm -f -- "$RECORD_TEMPORARY" + [[ -z $UNIT_TEMPORARY ]] || rm -f -- "$UNIT_TEMPORARY" + [[ -z $INSTALL_HELPER_TEMPORARY ]] || rm -f -- "$INSTALL_HELPER_TEMPORARY" + [[ -z $UNINSTALL_HELPER_TEMPORARY ]] || rm -f -- "$UNINSTALL_HELPER_TEMPORARY" + [[ -z $LAUNCHER_TEMPORARY ]] || rm -f -- "$LAUNCHER_TEMPORARY" + [[ -z $STAGING ]] || rm -rf -- "$STAGING" + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $DESTINATION_CREATED -eq 1 ]]; then + rm -rf -- "$destination" + fi + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $CONFIG_CREATED -eq 1 ]]; then + rm -f -- "$config_file" + fi + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $CONFIG_DIR_CREATED -eq 1 ]]; then + rm -rf -- "$config_dir" + fi + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $STATE_DIR_CREATED -eq 1 && + $state_dir != "$config_dir" ]]; then + rm -rf -- "$state_dir" + fi + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 ]]; then + restore_path_metadata "$config_file" "$CONFIG_FILE_METADATA_SNAPSHOT" || + warn "could not restore configuration file metadata for '$config_file'" + restore_path_metadata "$state_dir" "$STATE_DIR_METADATA_SNAPSHOT" || + warn "could not restore state directory metadata for '$state_dir'" + restore_path_metadata "$config_dir" "$CONFIG_DIR_METADATA_SNAPSHOT" || + warn "could not restore configuration directory metadata for '$config_dir'" + fi + [[ -z $TRANSACTION_BACKUP_DIR ]] || rm -rf -- "$TRANSACTION_BACKUP_DIR" + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 ]]; then + remove_new_system_user + fi + exit "$status" +} +trap cleanup_install EXIT + +if [[ -e $prefix/versions || -L $prefix/versions ]]; then + [[ -d $prefix/versions && ! -L $prefix/versions ]] || + die "versions path is not a real directory: $prefix/versions" +fi +install -d -m 0755 -- "$prefix" "$prefix/versions" +if [[ $RUNTIME_TRUST_SCOPE != none ]]; then + validate_trusted_path_ancestors "$RUNTIME_TRUST_SCOPE" "$prefix" "$INSTALL_UID" 1 + validate_trusted_path_ancestors "$RUNTIME_TRUST_SCOPE" "$prefix/versions" "$INSTALL_UID" 1 +fi +acquire_prefix_lock "$prefix" + +record=$prefix/$RECORD_NAME +load_old_record "$record" +if [[ -n ${OLD_LAUNCHER:-} ]]; then + verify_recorded_launcher "$OLD_LAUNCHER" "${OLD_LAUNCHER_SHA256:-}" +elif [[ -n ${OLD_LAUNCHER_SHA256:-} ]]; then + die "existing portable launcher record is incomplete" +fi +if [[ $WANT_LAUNCHER -eq 1 && ( -e $LAUNCHER_PATH || -L $LAUNCHER_PATH ) && + -z ${OLD_LAUNCHER:-} ]]; then + die "refusing to overwrite an unrecognized portable launcher: $LAUNCHER_PATH" +fi +if [[ ${OLD_CREATED_SYSTEM_USER:-0} == 1 ]]; then + [[ ${OLD_SERVICE_UID:-} =~ ^[0-9]+$ && ${OLD_SERVICE_GID:-} =~ ^[0-9]+$ ]] || + die "installer-created service account record has no uid/gid identity" + [[ $(id -u "$SERVICE_USER") -eq $OLD_SERVICE_UID && + $(id -g "$SERVICE_USER") -eq $OLD_SERVICE_GID ]] || + die "the recorded $SERVICE_USER account was deleted or replaced" + CREATED_SYSTEM_USER=1 + SERVICE_UID=$OLD_SERVICE_UID + SERVICE_GID=$OLD_SERVICE_GID +fi +if [[ $mode == system || $register_service == system ]]; then + ensure_system_user "$state_dir" +fi + +destination=$prefix/versions/$version +if [[ -e $destination || -L $destination ]]; then + [[ -d $destination && ! -L $destination && -f $destination/manifest.json ]] || + die "release destination already exists but is incomplete: $destination" + cmp -s -- "$manifest" "$destination/manifest.json" || + die "release '$version' is already installed with a different manifest" +else + STAGING=$(mktemp -d --tmpdir="$prefix/versions" ".staging-$version.XXXXXX") + cp -a -- "$PAYLOAD_ROOT/bin" "$PAYLOAD_ROOT/lib" "$PAYLOAD_ROOT/share" \ + "$PAYLOAD_ROOT/service" "$PAYLOAD_ROOT/manifest.json" "$STAGING/" + [[ -x $STAGING/bin/echoiond && -f $STAGING/lib/Echoion.ts ]] || + die "staged release failed layout validation" + mv -- "$STAGING" "$destination" + STAGING= + DESTINATION_CREATED=1 +fi +if [[ $mode == system || $register_service == system ]]; then + normalize_and_validate_system_runtime "$destination" +fi + +[[ -e $config_dir || -L $config_dir ]] || CONFIG_DIR_CREATED=1 +[[ -e $state_dir || -L $state_dir ]] || STATE_DIR_CREATED=1 +CONFIG_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$config_dir") +STATE_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$state_dir") +CONFIG_FILE_METADATA_SNAPSHOT=$(snapshot_path_metadata "$config_file") +if [[ $CONFIG_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == system ]]; then + validate_mutable_directory system "$config_dir" "$(stat -c '%u' -- /)" "$INSTALL_UID" +elif [[ $CONFIG_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == user ]]; then + validate_mutable_directory user "$config_dir" "$INSTALL_UID" "$INSTALL_UID" +fi +if [[ $STATE_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == system ]]; then + validate_mutable_directory system "$state_dir" "$SERVICE_UID" "$INSTALL_UID" +elif [[ $STATE_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == user ]]; then + validate_mutable_directory user "$state_dir" "$INSTALL_UID" "$INSTALL_UID" +fi +install -d -m 0700 -- "$config_dir" "$state_dir" +if [[ ! -e $config_file && ! -L $config_file ]]; then + render_config "$destination/share/echoion/config.example.json" "$config_file" \ + "./web" + CONFIG_CREATED=1 +elif [[ -L $config_file || ! -f $config_file ]]; then + die "configuration path exists but is not a regular file: $config_file" +fi + +if [[ $mode == system || $register_service == system ]]; then + [[ $config_dir != "$state_dir" ]] || + die "system installations require separate configuration and state directories" + chown "$SERVICE_USER:$SERVICE_USER" "$state_dir" + chown "root:$SERVICE_USER" "$config_dir" "$config_file" + chmod 0750 "$config_dir" "$state_dir" + chmod 0640 "$config_file" +else + chmod 0700 "$config_dir" "$state_dir" + chmod 0600 "$config_file" +fi +if [[ $RUNTIME_TRUST_SCOPE == system ]]; then + validate_mutable_directory system "$config_dir" "$(stat -c '%u' -- /)" "$INSTALL_UID" + validate_mutable_directory system "$state_dir" "$SERVICE_UID" "$INSTALL_UID" +elif [[ $RUNTIME_TRUST_SCOPE == user ]]; then + validate_mutable_directory user "$config_dir" "$INSTALL_UID" "$INSTALL_UID" + validate_mutable_directory user "$state_dir" "$INSTALL_UID" "$INSTALL_UID" +fi + +if [[ ${OLD_INSTALL_ID:-} =~ ^[A-Za-z0-9-]{16,64}$ ]]; then + INSTALL_ID=$OLD_INSTALL_ID +else + INSTALL_ID=$(new_install_id) +fi +capture_managed_directory config "$config_dir" "${OLD_CONFIG_PURGE_ALLOWED:-0}" \ + "${OLD_CONFIG_DIR_DEVICE:-}" "${OLD_CONFIG_DIR_INODE:-}" "${OLD_CONFIG_DIR_UID:-}" \ + "${OLD_CONFIG_DIR_GID:-}" "${OLD_CONFIG_MARKER_SHA256:-}" "$CONFIG_DIR_CREATED" +capture_managed_directory state "$state_dir" "${OLD_STATE_PURGE_ALLOWED:-0}" \ + "${OLD_STATE_DIR_DEVICE:-}" "${OLD_STATE_DIR_INODE:-}" "${OLD_STATE_DIR_UID:-}" \ + "${OLD_STATE_DIR_GID:-}" "${OLD_STATE_MARKER_SHA256:-}" "$STATE_DIR_CREATED" + +candidate_executable=$destination/bin/echoiond +if ! "$candidate_executable" --validate-install "$destination"; then + die "offline payload validation failed for Echoion $version" +fi +if [[ $register_service != none ]]; then + validate_service_access "$register_service" "$candidate_executable" "$config_file" "$state_dir" +fi + +old_current= +if [[ -L $prefix/current ]]; then + old_current=$(readlink -- "$prefix/current") + [[ $old_current =~ ^versions/[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || + die "current symlink has an unsafe target: $old_current" +elif [[ -e $prefix/current ]]; then + die "current exists but is not a symlink: $prefix/current" +fi + +unit_path= +unit_hash= +unit_root= +if [[ $register_service == user ]]; then + unit_root=${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config} + reject_control_characters service-unit-root "$unit_root" + unit_root=$(absolute_path "$unit_root") + validate_trusted_path_ancestors user "$unit_root" "$INSTALL_UID" 0 + install -d -m 0755 -- "$unit_root/systemd/user" + validate_trusted_path_ancestors user "$unit_root" "$INSTALL_UID" 1 + unit_path=$unit_root/systemd/user/$SERVICE_NAME +elif [[ $register_service == system ]]; then + unit_path=/etc/systemd/system/$SERVICE_NAME +fi + +service_scope_changes=0 +OLD_SERVICE_WAS_ENABLED=0 +OLD_SERVICE_WAS_ACTIVE=0 +if [[ ${OLD_SERVICE_SCOPE:-none} != none ]]; then + if systemctl_for "$OLD_SERVICE_SCOPE" is-enabled --quiet "$SERVICE_NAME"; then + OLD_SERVICE_WAS_ENABLED=1 + fi + if systemctl_for "$OLD_SERVICE_SCOPE" is-active --quiet "$SERVICE_NAME"; then + OLD_SERVICE_WAS_ACTIVE=1 + fi +fi +if [[ ${OLD_SERVICE_SCOPE:-none} != none && + ( ${OLD_SERVICE_SCOPE:-none} != "$register_service" || ${OLD_SERVICE_UNIT:-} != "$unit_path" ) ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" + service_scope_changes=1 +fi +if [[ $register_service != none && -e $unit_path ]]; then + if [[ ${OLD_SERVICE_UNIT:-} == "$unit_path" && ${OLD_SERVICE_SCOPE:-} == "$register_service" ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" + else + die "refusing to overwrite unrecognized service unit: $unit_path" + fi +fi + +if [[ $register_service != none ]]; then + install -d -m 0755 -- "$(dirname -- "$unit_path")" + UNIT_TEMPORARY=$(mktemp --tmpdir="$(dirname -- "$unit_path")" '.echoion.service.XXXXXX') + render_unit "$destination/service/echoion.service.in" "$UNIT_TEMPORARY" "$register_service" \ + "$prefix/current" "$prefix/current/lib/Echoion.ts" "$state_dir" \ + "$prefix/current/bin/echoiond" "$config_file" + chmod 0644 "$UNIT_TEMPORARY" +fi + +INSTALL_HELPER_TEMPORARY=$(mktemp --tmpdir="$prefix" '.install-helper.XXXXXX') +UNINSTALL_HELPER_TEMPORARY=$(mktemp --tmpdir="$prefix" '.uninstall-helper.XXXXXX') +install -m 0755 -- "$PAYLOAD_ROOT/install.sh" "$INSTALL_HELPER_TEMPORARY" +install -m 0755 -- "$PAYLOAD_ROOT/uninstall.sh" "$UNINSTALL_HELPER_TEMPORARY" +if [[ $WANT_LAUNCHER -eq 1 ]]; then + LAUNCHER_TEMPORARY=$(mktemp --tmpdir="$prefix" '.echoion-launcher.XXXXXX') + render_portable_launcher "$LAUNCHER_TEMPORARY" + chmod 0755 "$LAUNCHER_TEMPORARY" + LAUNCHER_RECORD_PATH=echoion + LAUNCHER_SHA256=$(sha256_file "$LAUNCHER_TEMPORARY") +fi + +TRANSACTION_BACKUP_DIR=$(mktemp -d --tmpdir="$prefix" '.install-rollback.XXXXXX') +if [[ -f $record ]]; then + cp -a -- "$record" "$TRANSACTION_BACKUP_DIR/install-record" +fi +if [[ $service_scope_changes -eq 1 ]]; then + cp -a -- "$OLD_SERVICE_UNIT" "$TRANSACTION_BACKUP_DIR/old-scope-unit" +fi +if [[ $register_service != none && -f $unit_path ]]; then + cp -a -- "$unit_path" "$TRANSACTION_BACKUP_DIR/new-scope-unit" +fi +if [[ -f $prefix/install.sh && $prefix/install.sh != "$INSTALL_HELPER_TEMPORARY" ]]; then + cp -a -- "$prefix/install.sh" "$TRANSACTION_BACKUP_DIR/install-helper" +fi +if [[ -f $prefix/uninstall.sh && $prefix/uninstall.sh != "$UNINSTALL_HELPER_TEMPORARY" ]]; then + cp -a -- "$prefix/uninstall.sh" "$TRANSACTION_BACKUP_DIR/uninstall-helper" +fi +if [[ -n ${OLD_LAUNCHER:-} ]]; then + cp -a -- "$LAUNCHER_PATH" "$TRANSACTION_BACKUP_DIR/launcher" +fi +TRANSACTION_ACTIVE=1 + +HELPER_MUTATION_ARMED=1 +mv -f -- "$INSTALL_HELPER_TEMPORARY" "$prefix/install.sh" +INSTALL_HELPER_TEMPORARY= +mv -f -- "$UNINSTALL_HELPER_TEMPORARY" "$prefix/uninstall.sh" +UNINSTALL_HELPER_TEMPORARY= + +if [[ $WANT_LAUNCHER -eq 1 || -n ${OLD_LAUNCHER:-} ]]; then + LAUNCHER_MUTATION_ARMED=1 + if [[ $WANT_LAUNCHER -eq 1 ]]; then + mv -f -- "$LAUNCHER_TEMPORARY" "$LAUNCHER_PATH" + LAUNCHER_TEMPORARY= + else + rm -f -- "$LAUNCHER_PATH" + fi +fi + +if [[ $service_scope_changes -eq 1 ]]; then + OLD_SERVICE_MUTATION_ARMED=1 + remove_recorded_service "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" || + die "could not remove the previously registered service" +fi +if [[ $register_service != none ]]; then + NEW_UNIT_MUTATION_ARMED=1 + mv -f -- "$UNIT_TEMPORARY" "$unit_path" + UNIT_TEMPORARY= + unit_hash=$(sha256_file "$unit_path") +fi + +new_link_directory=$(mktemp -d --tmpdir="$prefix" '.current-link.XXXXXX') +ln -s -- "versions/$version" "$new_link_directory/current" +mv -Tf -- "$new_link_directory/current" "$prefix/current" +rmdir -- "$new_link_directory" + +if [[ $register_service != none ]]; then + systemctl_for "$register_service" daemon-reload || die "systemd rejected the installed service unit" + if [[ $start -eq 1 ]]; then + if ! systemctl_for "$register_service" enable "$SERVICE_NAME" || + ! systemctl_for "$register_service" restart "$SERVICE_NAME" || + ! systemctl_for "$register_service" is-active --quiet "$SERVICE_NAME"; then + warn "new service failed health validation; restoring previous release and unit" + die "service failed to start" + fi + else + systemctl_for "$register_service" disable --now "$SERVICE_NAME" || + die "could not leave the registered service disabled and stopped" + fi +fi + +write_record "$record" "$unit_path" "$unit_hash" +INSTALL_COMMITTED=1 +TRANSACTION_ACTIVE=0 + +if [[ $PAYLOAD_ROOT == "$prefix" ]]; then + [[ -n $prefix && $prefix != / ]] || die "unsafe in-place install prefix" + rm -rf -- "${prefix:?}/bin" "${prefix:?}/lib" "${prefix:?}/share" \ + "${prefix:?}/service" + rm -f -- "$prefix/manifest.json" +fi + +printf 'Echoion %s installed in %s\n' "$version" "$prefix" +printf 'Configuration: %s\n' "$config_file" +printf 'State: %s\n' "$state_dir" +if [[ $register_service == none ]]; then + if [[ $WANT_LAUNCHER -eq 1 ]]; then + printf 'Run: %q\n' "$LAUNCHER_PATH" + else + printf 'Run: %q --config %q --state-dir %q\n' \ + "$prefix/current/bin/echoiond" "$config_file" "$state_dir" + fi +elif [[ $start -eq 1 ]]; then + printf '%s is enabled and running.\n' "$SERVICE_NAME" +else + printf '%s was registered but is disabled and stopped.\n' "$SERVICE_NAME" +fi diff --git a/packaging/service/echoion.service.in b/packaging/service/echoion.service.in new file mode 100644 index 0000000..bb6cebc --- /dev/null +++ b/packaging/service/echoion.service.in @@ -0,0 +1,20 @@ +[Unit] +Description=Echoion Music Bot +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +@SERVICE_IDENTITY@ +@WORKING_DIRECTORY@ +@ENVIRONMENT_HOME@ +@ENVIRONMENT_CORE@ +@ENVIRONMENT_STATE@ +@EXEC_START@ +Restart=on-failure +RestartSec=5s +LimitNOFILE=65536 +UMask=0077 + +[Install] +@INSTALL_TARGET@ diff --git a/packaging/tests/installer_test.sh b/packaging/tests/installer_test.sh new file mode 100755 index 0000000..3a93ef9 --- /dev/null +++ b/packaging/tests/installer_test.sh @@ -0,0 +1,551 @@ +#!/usr/bin/env bash +# shellcheck disable=SC1091,SC2034,SC2329 +set -euo pipefail + +SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +PACKAGING_DIR=$(cd -P -- "$SCRIPT_DIR/.." && pwd -P) +TEST_ROOT=$(mktemp -d -- "$SCRIPT_DIR/.installer-test.XXXXXX") +trap 'rm -rf -- "$TEST_ROOT"' EXIT + +fail() { + printf 'FAIL: %s\n' "$*" >&2 + exit 1 +} + +assert_file() { + [[ -f $1 ]] || fail "missing file: $1" +} + +assert_not_exists() { + [[ ! -e $1 ]] || fail "unexpected path: $1" +} + +assert_contains() { + local path=$1 + local text=$2 + grep -F -- "$text" "$path" >/dev/null || fail "$path does not contain: $text" +} + +assert_not_contains() { + local path=$1 + local text=$2 + if grep -F -- "$text" "$path" >/dev/null; then + fail "$path unexpectedly contains: $text" + fi +} + +make_payload() { + local root=$1 + install -d -- "$root/bin" "$root/lib" "$root/share/echoion/web" "$root/service" + install -m 0755 -- "$PACKAGING_DIR/install.sh" "$root/install.sh" + install -m 0755 -- "$PACKAGING_DIR/uninstall.sh" "$root/uninstall.sh" + install -m 0644 -- "$PACKAGING_DIR/service/echoion.service.in" "$root/service/echoion.service.in" + cat > "$root/manifest.json" <<'EOF' +{ + "schemaVersion": 2, + "version": "1.2.3", + "files": [ + {"path": "bin/echoiond"} + ] +} +EOF + cat > "$root/bin/echoiond" <<'EOF' +#!/usr/bin/env bash +if [[ ${1:-} == --validate-install && -n ${2:-} ]]; then + printf '%s\n' "$2" >> "${VALIDATOR_LOG:?}" + if [[ -n ${VALIDATOR_FAIL_PATH:-} && $2 == "$VALIDATOR_FAIL_PATH" ]]; then + exit 1 + fi + exit 0 +fi +if [[ ${ALLOW_DAEMON_RUN:-0} == 1 ]]; then + printf 'ECHOION_HOME=%s\n' "${ECHOION_HOME:-}" >> "${DAEMON_LOG:?}" + printf 'ECHOION_CORE_PATH=%s\n' "${ECHOION_CORE_PATH:-}" >> "$DAEMON_LOG" + printf 'ECHOION_STATE_DIR=%s\n' "${ECHOION_STATE_DIR:-}" >> "$DAEMON_LOG" + argument_index=0 + for argument in "$@"; do + printf 'ARG_%d=%s\n' "$argument_index" "$argument" >> "$DAEMON_LOG" + argument_index=$((argument_index + 1)) + done + exit 0 +fi +printf 'daemon unexpectedly ran\n' >> "${DAEMON_LOG:?}" +exit 1 +EOF + chmod 0755 "$root/bin/echoiond" + printf 'fake dynamic core\n' > "$root/lib/Echoion.ts" + cat > "$root/share/echoion/config.example.json" <<'EOF' +{ + "web": { + "webRoot": "./web", + "enabled": false + } +} +EOF + printf '\n' > "$root/share/echoion/web/index.html" +} + +fake_bin=$TEST_ROOT/fake-bin +home=$TEST_ROOT/home +install -d -- "$fake_bin" "$home" +REAL_MV=$(command -v mv) +export REAL_MV +cat > "$fake_bin/systemctl" <<'EOF' +#!/usr/bin/env bash +printf '%s\n' "$*" >> "${SYSTEMCTL_LOG:?}" +if [[ ${SYSTEMCTL_FAIL_RESTART:-0} == 1 && " $* " == *' restart '* ]]; then + exit 1 +fi +exit 0 +EOF +chmod 0755 "$fake_bin/systemctl" +cat > "$fake_bin/mv" <<'EOF' +#!/usr/bin/env bash +last= +for last in "$@"; do :; done +if [[ ${RECORD_COMMIT_FAIL:-0} == 1 && ${last##*/} == .echoion-install ]]; then + exit 73 +fi +exec "${REAL_MV:?}" "$@" +EOF +chmod 0755 "$fake_bin/mv" + +export PATH=$fake_bin:$PATH +export HOME=$home +export XDG_CONFIG_HOME=$home/.config +export XDG_STATE_HOME=$home/.state +export SYSTEMCTL_LOG=$TEST_ROOT/systemctl.log +export DAEMON_LOG=$TEST_ROOT/daemon.log +export VALIDATOR_LOG=$TEST_ROOT/validator.log +: > "$SYSTEMCTL_LOG" +: > "$DAEMON_LOG" +: > "$VALIDATOR_LOG" + +bash -n "$PACKAGING_DIR/install.sh" +bash -n "$PACKAGING_DIR/uninstall.sh" + +trusted_parent=$TEST_ROOT/trusted-parent +trusted_prefix=$trusted_parent/echoion +install -d -m 0700 -- "$trusted_prefix" +( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + validate_trusted_path_ancestors user "$trusted_prefix" "$(id -u)" 1 +) || fail 'trusted user service prefix was rejected' +chmod 0770 "$trusted_parent" +if ( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + validate_trusted_path_ancestors user "$trusted_prefix" "$(id -u)" 1 +) >/dev/null 2>&1; then + fail 'group-writable service prefix ancestor was accepted' +fi +chmod 0700 "$trusted_parent" +if ( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + validate_trusted_path_ancestors system "$trusted_prefix" 0 1 +) >/dev/null 2>&1; then + fail 'non-root-owned system service prefix was accepted' +fi +if ( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + validate_registration_identity user 0 +) >/dev/null 2>&1; then + fail 'root user-scope service registration was accepted' +fi + +CHOWN_LOG=$TEST_ROOT/chown.log +export CHOWN_LOG +( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + chown() { printf '%s\n' "$*" >> "$CHOWN_LOG"; } + find() { return 0; } + runuser() { + [[ " $* " == *' test -w '* ]] && return 1 + return 0 + } + normalize_and_validate_system_runtime "$trusted_prefix" +) +assert_contains "$CHOWN_LOG" '-R root:root' + +USERDEL_LOG=$TEST_ROOT/userdel.log +export USERDEL_LOG +( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + ACCOUNT_CREATED_THIS_RUN=1 + ACCOUNT_IDENTITY_CAPTURED=1 + SERVICE_UID=4242 + SERVICE_GID=4343 + MOCK_UID=4242 + MOCK_GID=4343 + id() { + case $1 in + -u) printf '%s\n' "$MOCK_UID" ;; + -g) printf '%s\n' "$MOCK_GID" ;; + esac + } + userdel() { printf '%s\n' "$*" >> "$USERDEL_LOG"; } + remove_new_system_user +) +assert_contains "$USERDEL_LOG" 'echoion' +: > "$USERDEL_LOG" +( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + ACCOUNT_CREATED_THIS_RUN=1 + ACCOUNT_IDENTITY_CAPTURED=1 + SERVICE_UID=4242 + SERVICE_GID=4343 + MOCK_UID=9999 + MOCK_GID=4343 + id() { + case $1 in + -u) printf '%s\n' "$MOCK_UID" ;; + -g) printf '%s\n' "$MOCK_GID" ;; + esac + } + userdel() { printf '%s\n' "$*" >> "$USERDEL_LOG"; } + remove_new_system_user +) 2>/dev/null +[[ ! -s $USERDEL_LOG ]] || fail 'recreated service account was deleted' + +symlink_prefix=$TEST_ROOT/symlink-versions +install -d -- "$symlink_prefix" "$TEST_ROOT/external-versions" +ln -s -- "$TEST_ROOT/external-versions" "$symlink_prefix/versions" + +payload=$TEST_ROOT/payload +make_payload "$payload" + +locked_prefix=$TEST_ROOT/locked-prefix +install -d -- "$locked_prefix" +exec {TEST_LOCK_FD}< "$locked_prefix" +flock -n "$TEST_LOCK_FD" +if "$payload/install.sh" --mode portable --prefix "$locked_prefix" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'concurrent installer acquired an already-held prefix lock' +fi +flock -u "$TEST_LOCK_FD" +exec {TEST_LOCK_FD}<&- +assert_not_exists "$locked_prefix/versions/1.2.3" + +metadata_prefix=$TEST_ROOT/metadata-rollback +metadata_config=$TEST_ROOT/metadata-config +metadata_state=$TEST_ROOT/metadata-state +install -d -m 0750 -- "$metadata_config" +install -d -m 0710 -- "$metadata_state" +printf '{}\n' > "$metadata_config/config.json" +chmod 0640 "$metadata_config/config.json" +config_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config") +state_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_state") +file_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json") +export VALIDATOR_FAIL_PATH=$metadata_prefix/versions/1.2.3 +if "$payload/install.sh" --mode portable --prefix "$metadata_prefix" \ + --config-dir "$metadata_config" --state-dir "$metadata_state" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'installer accepted injected post-metadata validation failure' +fi +unset VALIDATOR_FAIL_PATH +config_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config") +state_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_state") +file_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json") +[[ $config_metadata_after == "$config_metadata_before" ]] || + fail 'failed install did not restore configuration directory uid/gid/mode' +[[ $state_metadata_after == "$state_metadata_before" ]] || + fail 'failed install did not restore state directory uid/gid/mode' +[[ $file_metadata_after == "$file_metadata_before" ]] || + fail 'failed install did not restore configuration file uid/gid/mode' +assert_not_exists "$metadata_prefix/versions/1.2.3" + +runtime_root=$TEST_ROOT/runtime-directory +install -d -m 0700 -- "$runtime_root" +if XDG_RUNTIME_DIR=$runtime_root "$payload/install.sh" --mode portable \ + --prefix "$runtime_root/echoion" --register-service user \ + --non-interactive >/dev/null 2>&1; then + fail 'XDG runtime portable service prefix was accepted' +fi + +unsafe_mutable_parent=$TEST_ROOT/group-writable-mutable +install -d -m 0770 -- "$unsafe_mutable_parent" +if "$payload/install.sh" --mode portable --prefix "$TEST_ROOT/mutable-trust-install" \ + --config-dir "$unsafe_mutable_parent/config" \ + --state-dir "$TEST_ROOT/mutable-trust-state" --register-service user \ + --non-interactive >/dev/null 2>&1; then + fail 'group-writable mutable-path ancestor was accepted for a service' +fi + +if "$payload/install.sh" --mode portable --prefix "$symlink_prefix" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'symlinked versions directory was accepted' +fi + +bad_payload=$TEST_ROOT/bad-payload +make_payload "$bad_payload" +sed -i 's/"schemaVersion": 2/"schemaVersion": 1/' "$bad_payload/manifest.json" +if "$bad_payload/install.sh" --mode portable --prefix "$TEST_ROOT/bad-install" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'legacy payload manifest was accepted' +fi + +self_prefix=$TEST_ROOT/self-contained +"$payload/install.sh" --mode portable --prefix "$self_prefix" \ + --data-layout self-contained --register-service none --non-interactive +[[ $(readlink -- "$self_prefix/current") == versions/1.2.3 ]] || fail 'wrong current target' +assert_file "$self_prefix/versions/1.2.3/bin/echoiond" +assert_file "$self_prefix/config/config.json" +[[ -x $self_prefix/echoion ]] || fail 'portable launcher is not executable' +assert_contains "$self_prefix/.echoion-install" 'relocatable=1' +assert_contains "$self_prefix/.echoion-install" 'prefix=.' +assert_contains "$self_prefix/.echoion-install" 'config_dir=config' +assert_contains "$self_prefix/.echoion-install" 'state_dir=data' +assert_contains "$self_prefix/.echoion-install" 'launcher=echoion' +assert_contains "$self_prefix/config/config.json" '"webRoot": "./web"' +assert_not_contains "$self_prefix/config/config.json" "$self_prefix/current" +[[ ! -s $SYSTEMCTL_LOG ]] || fail 'service command ran for register-service none' +[[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during installation' +assert_contains "$VALIDATOR_LOG" "$self_prefix/versions/1.2.3" +self_moved_prefix=$TEST_ROOT/self-contained-moved +mv -- "$self_prefix" "$self_moved_prefix" +assert_not_exists "$self_prefix" +: > "$DAEMON_LOG" +ALLOW_DAEMON_RUN=1 "$self_moved_prefix/echoion" --probe 'two words' +assert_contains "$DAEMON_LOG" "ECHOION_HOME=$self_moved_prefix/current" +assert_contains "$DAEMON_LOG" "ECHOION_CORE_PATH=$self_moved_prefix/current/lib/Echoion.ts" +assert_contains "$DAEMON_LOG" "ECHOION_STATE_DIR=$self_moved_prefix/data" +assert_contains "$DAEMON_LOG" 'ARG_0=--config' +assert_contains "$DAEMON_LOG" "ARG_1=$self_moved_prefix/config/config.json" +assert_contains "$DAEMON_LOG" 'ARG_2=--state-dir' +assert_contains "$DAEMON_LOG" "ARG_3=$self_moved_prefix/data" +assert_contains "$DAEMON_LOG" 'ARG_4=--probe' +assert_contains "$DAEMON_LOG" 'ARG_5=two words' +: > "$DAEMON_LOG" +if ALLOW_DAEMON_RUN=1 "$self_moved_prefix/echoion" --config /tmp/override \ + >/dev/null 2>&1; then + fail 'portable launcher accepted a managed config override' +fi +[[ ! -s $DAEMON_LOG ]] || fail 'portable launcher executed daemon after rejected override' +"$self_moved_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$self_moved_prefix" + +dots_prefix=$TEST_ROOT/consecutive-dot-version +dots_payload=$TEST_ROOT/consecutive-dot-payload +dots_upgrade_payload=$TEST_ROOT/consecutive-dot-upgrade-payload +cp -a -- "$payload" "$dots_payload" +sed -i 's/"version": "1.2.3"/"version": "1.0..rc1"/' "$dots_payload/manifest.json" +cp -a -- "$dots_payload" "$dots_upgrade_payload" +sed -i 's/"version": "1.0..rc1"/"version": "1.0..rc2"/' \ + "$dots_upgrade_payload/manifest.json" +"$dots_payload/install.sh" --mode portable --prefix "$dots_prefix" \ + --data-layout self-contained --register-service none --non-interactive >/dev/null +"$dots_upgrade_payload/install.sh" --mode portable --prefix "$dots_prefix" \ + --data-layout self-contained --register-service none --non-interactive >/dev/null +[[ $(readlink -- "$dots_prefix/current") == versions/1.0..rc2 ]] || + fail 'legal consecutive-dot version did not upgrade' +"$dots_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$dots_prefix" + +custom_prefix=$TEST_ROOT/custom-purge-install +custom_config=$TEST_ROOT/custom-configuration +custom_state=$TEST_ROOT/custom-runtime-state +"$payload/install.sh" --mode portable --prefix "$custom_prefix" \ + --config-dir "$custom_config" --state-dir "$custom_state" \ + --register-service none --non-interactive >/dev/null +assert_file "$custom_config/.echoion-managed" +assert_file "$custom_state/.echoion-managed" +assert_contains "$custom_prefix/.echoion-install" 'config_purge_allowed=1' +assert_contains "$custom_prefix/.echoion-install" 'state_purge_allowed=1' +exec {TEST_LOCK_FD}< "$custom_prefix" +flock -n "$TEST_LOCK_FD" +if "$custom_prefix/uninstall.sh" --purge --non-interactive >/dev/null 2>&1; then + fail 'concurrent uninstaller acquired an already-held prefix lock' +fi +assert_file "$custom_prefix/current/bin/echoiond" +flock -u "$TEST_LOCK_FD" +exec {TEST_LOCK_FD}<&- +"$custom_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$custom_prefix" +assert_not_exists "$custom_config" +assert_not_exists "$custom_state" + +service_prefix="$TEST_ROOT/portable path % dollar\$" +: > "$SYSTEMCTL_LOG" +"$payload/install.sh" --mode portable --prefix "$service_prefix" \ + --data-layout standard --register-service user --non-interactive +unit=$XDG_CONFIG_HOME/systemd/user/echoion.service +assert_file "$unit" +assert_contains "$unit" 'WorkingDirectory="' +assert_contains "$unit" 'portable path %% dollar$/current"' +assert_contains "$unit" 'ExecStart="' +assert_contains "$unit" 'portable path %% dollar$$/current/bin/echoiond"' +assert_contains "$unit" 'Environment="ECHOION_HOME=' +assert_contains "$unit" 'Environment="ECHOION_CORE_PATH=' +assert_contains "$unit" 'Environment="ECHOION_STATE_DIR=' +assert_contains "$unit" '--config "' +assert_contains "$unit" '--state-dir "' +if grep -E '@[A-Z_]+@' "$unit" >/dev/null; then + fail 'generated systemd unit contains an unresolved template marker' +fi +if command -v systemd-analyze >/dev/null 2>&1; then + verify_log=$TEST_ROOT/systemd-verify.log + if ! systemd-analyze verify "$unit" 2> "$verify_log" && + grep -E 'echoion\.service:|Failed to load unit' "$verify_log" >/dev/null; then + cat "$verify_log" >&2 + fail 'generated systemd unit did not verify' + fi +fi +assert_contains "$SYSTEMCTL_LOG" '--user daemon-reload' +assert_contains "$SYSTEMCTL_LOG" '--user disable --now echoion.service' +if grep -E -- '(^| )enable( |$)|(^| )restart( |$)' "$SYSTEMCTL_LOG" >/dev/null; then + fail 'service was activated without --start' +fi +[[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during service registration' + +: > "$SYSTEMCTL_LOG" +"$payload/install.sh" --mode portable --prefix "$service_prefix" \ + --data-layout standard --register-service user --start --non-interactive +assert_contains "$SYSTEMCTL_LOG" '--user enable echoion.service' +assert_contains "$SYSTEMCTL_LOG" '--user restart echoion.service' +assert_contains "$SYSTEMCTL_LOG" '--user is-active --quiet echoion.service' + +: > "$SYSTEMCTL_LOG" +"$service_prefix/uninstall.sh" --non-interactive +assert_not_exists "$unit" +assert_not_exists "$service_prefix/versions" +assert_file "$XDG_CONFIG_HOME/echoion/config.json" +[[ -d $XDG_STATE_HOME/echoion ]] || fail 'state directory was not preserved' + +purge_retry_prefix=$TEST_ROOT/purge-retry +purge_retry_config=$TEST_ROOT/purge-retry-config +purge_retry_state=$TEST_ROOT/purge-retry-state +"$payload/install.sh" --mode portable --prefix "$purge_retry_prefix" \ + --config-dir "$purge_retry_config" --state-dir "$purge_retry_state" \ + --register-service user --non-interactive >/dev/null +marker_backup=$TEST_ROOT/config-marker.backup +cp -a -- "$purge_retry_config/.echoion-managed" "$marker_backup" +printf 'tampered\n' >> "$purge_retry_config/.echoion-managed" +if "$purge_retry_prefix/uninstall.sh" --purge --non-interactive >/dev/null 2>&1; then + fail 'purge accepted a modified ownership marker' +fi +assert_file "$unit" +assert_file "$purge_retry_prefix/current/bin/echoiond" +assert_file "$purge_retry_prefix/.echoion-install" +cp -a -- "$marker_backup" "$purge_retry_config/.echoion-managed" +"$purge_retry_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$unit" +assert_not_exists "$purge_retry_prefix" +assert_not_exists "$purge_retry_config" +assert_not_exists "$purge_retry_state" + +rollback_prefix=$TEST_ROOT/rollback +"$payload/install.sh" --mode portable --prefix "$rollback_prefix" \ + --register-service user --non-interactive >/dev/null +old_unit_hash=$(sha256sum -- "$unit") +old_unit_hash=${old_unit_hash%% *} +upgrade_payload=$TEST_ROOT/upgrade-payload +cp -a -- "$payload" "$upgrade_payload" +sed -i 's/"version": "1.2.3"/"version": "1.2.4"/' "$upgrade_payload/manifest.json" +printf '# changed in 1.2.4\n' >> "$upgrade_payload/service/echoion.service.in" +printf '# changed installer helper in 1.2.4\n' >> "$upgrade_payload/install.sh" +printf '# changed uninstaller helper in 1.2.4\n' >> "$upgrade_payload/uninstall.sh" +export SYSTEMCTL_FAIL_RESTART=1 +if "$upgrade_payload/install.sh" --mode portable --prefix "$rollback_prefix" \ + --register-service user --start --non-interactive >/dev/null 2>&1; then + fail 'installer accepted a failed service restart' +fi +unset SYSTEMCTL_FAIL_RESTART +[[ $(readlink -- "$rollback_prefix/current") == versions/1.2.3 ]] || + fail 'failed service upgrade did not restore current' +restored_unit_hash=$(sha256sum -- "$unit") +restored_unit_hash=${restored_unit_hash%% *} +[[ $restored_unit_hash == "$old_unit_hash" ]] || fail 'failed upgrade did not restore unit bytes' +assert_contains "$rollback_prefix/.echoion-install" 'version=1.2.3' +"$rollback_prefix/uninstall.sh" --non-interactive >/dev/null + +record_rollback_prefix=$TEST_ROOT/record-rollback +"$payload/install.sh" --mode portable --prefix "$record_rollback_prefix" \ + --register-service user --non-interactive >/dev/null +record_old_unit_hash=$(sha256sum -- "$unit") +record_old_unit_hash=${record_old_unit_hash%% *} +record_old_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh") +record_old_install_hash=${record_old_install_hash%% *} +record_old_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh") +record_old_uninstall_hash=${record_old_uninstall_hash%% *} +export RECORD_COMMIT_FAIL=1 +if "$upgrade_payload/install.sh" --mode portable --prefix "$record_rollback_prefix" \ + --register-service user --non-interactive >/dev/null 2>&1; then + fail 'installer accepted a failed atomic record commit' +fi +unset RECORD_COMMIT_FAIL +[[ $(readlink -- "$record_rollback_prefix/current") == versions/1.2.3 ]] || + fail 'record-commit failure did not restore current' +record_restored_unit_hash=$(sha256sum -- "$unit") +record_restored_unit_hash=${record_restored_unit_hash%% *} +[[ $record_restored_unit_hash == "$record_old_unit_hash" ]] || + fail 'record-commit failure did not restore unit bytes' +assert_contains "$record_rollback_prefix/.echoion-install" 'version=1.2.3' +assert_not_exists "$record_rollback_prefix/versions/1.2.4" +record_restored_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh") +record_restored_install_hash=${record_restored_install_hash%% *} +record_restored_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh") +record_restored_uninstall_hash=${record_restored_uninstall_hash%% *} +[[ $record_restored_install_hash == "$record_old_install_hash" ]] || + fail 'record-commit failure did not restore installer helper bytes' +[[ $record_restored_uninstall_hash == "$record_old_uninstall_hash" ]] || + fail 'record-commit failure did not restore uninstaller helper bytes' +"$record_rollback_prefix/uninstall.sh" --non-interactive >/dev/null + +scope_rollback_prefix=$TEST_ROOT/scope-rollback +"$payload/install.sh" --mode portable --prefix "$scope_rollback_prefix" \ + --register-service user --non-interactive >/dev/null +scope_old_unit_hash=$(sha256sum -- "$unit") +scope_old_unit_hash=${scope_old_unit_hash%% *} +export RECORD_COMMIT_FAIL=1 +if "$upgrade_payload/install.sh" --mode portable --prefix "$scope_rollback_prefix" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'scope migration accepted a failed record commit' +fi +unset RECORD_COMMIT_FAIL +assert_file "$unit" +scope_restored_unit_hash=$(sha256sum -- "$unit") +scope_restored_unit_hash=${scope_restored_unit_hash%% *} +[[ $scope_restored_unit_hash == "$scope_old_unit_hash" ]] || + fail 'scope migration failure did not restore old unit bytes' +[[ $(readlink -- "$scope_rollback_prefix/current") == versions/1.2.3 ]] || + fail 'scope migration failure did not restore current' +assert_contains "$scope_rollback_prefix/.echoion-install" 'service_scope=user' +"$scope_rollback_prefix/uninstall.sh" --non-interactive >/dev/null + +tamper_prefix=$TEST_ROOT/tamper +"$payload/install.sh" --mode portable --prefix "$tamper_prefix" \ + --register-service user --non-interactive >/dev/null +printf '# local change\n' >> "$unit" +if "$tamper_prefix/uninstall.sh" --non-interactive >/dev/null 2>&1; then + fail 'uninstaller removed a modified unit' +fi +assert_file "$unit" +rm -f -- "$unit" + +if "$payload/install.sh" --mode portable --prefix "/tmp/echoion-installer-test-$$" \ + --register-service user --non-interactive >/dev/null 2>&1; then + fail 'temporary portable service prefix was accepted' +fi + +unsafe_mutable_prefix=$TEST_ROOT/unsafe-mutable/install +if "$payload/install.sh" --mode portable --prefix "$unsafe_mutable_prefix" \ + --config-dir "$TEST_ROOT/unsafe-mutable" --register-service none \ + --non-interactive >/dev/null 2>&1; then + fail 'mutable directory containing the install prefix was accepted' +fi + +in_place=$TEST_ROOT/in-place +make_payload "$in_place" +"$in_place/install.sh" --mode portable --prefix "$in_place" \ + --data-layout self-contained --register-service none --non-interactive >/dev/null +assert_file "$in_place/versions/1.2.3/bin/echoiond" +assert_not_exists "$in_place/bin" +[[ $(readlink -- "$in_place/current") == versions/1.2.3 ]] || fail 'in-place current target is wrong' + +printf 'installer tests passed\n' diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh new file mode 100755 index 0000000..ef1085e --- /dev/null +++ b/packaging/uninstall.sh @@ -0,0 +1,314 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROGRAM=${0##*/} +SERVICE_NAME=echoion.service +SERVICE_USER=echoion +RECORD_NAME=.echoion-install +MANAGED_MARKER=.echoion-managed + +die() { + printf '%s: %s\n' "$PROGRAM" "$*" >&2 + exit 1 +} + +warn() { + printf '%s: warning: %s\n' "$PROGRAM" "$*" >&2 +} + +usage() { + cat <<'EOF' +Usage: uninstall.sh [--purge] [--non-interactive] + +Remove the Echoion runtime and its matching registered service. Configuration +and state are preserved unless --purge is explicitly supplied. +EOF +} + +sha256_file() { + local result + result=$(sha256sum -- "$1") + printf '%s\n' "${result%% *}" +} + +systemctl_for() { + local scope=$1 + shift + if [[ $scope == user ]]; then + systemctl --user "$@" + else + systemctl "$@" + fi +} + +acquire_prefix_lock() { + local lock_prefix=$1 + command -v flock >/dev/null 2>&1 || die "flock is required for safe uninstallation" + exec {UNINSTALL_LOCK_FD}< "$lock_prefix" + flock -n "$UNINSTALL_LOCK_FD" || die "another Echoion install or uninstall is active for '$lock_prefix'" +} + +safe_unit_path() { + local scope=$1 + local unit=$2 + [[ $unit == /* && $unit != *'/../'* && $unit != *'/./'* ]] || return 1 + case $scope:$unit in + system:/etc/systemd/system/echoion.service) return 0 ;; + user:/*/systemd/user/echoion.service) return 0 ;; + *) return 1 ;; + esac +} + +safe_purge_path() { + local path=$1 + local prefix=$2 + [[ $path == /* && $path != / ]] || return 1 + local relative=${path#/} + [[ $relative == */* ]] || return 1 + case $path in + /etc | /var | /home | /root | /usr | /usr/local | /opt | /tmp | /var/tmp | /run) + return 1 + ;; + esac + case $path in + "$prefix" | "$prefix/current" | "$prefix/current"/* | "$prefix/versions" | "$prefix/versions"/*) + return 1 + ;; + esac + return 0 +} + +validate_managed_purge_path() { + local kind=$1 + local path=$2 + local safety_prefix=$3 + local marker_prefix=$4 + local install_id=$5 + local allowed=$6 + local expected_device=$7 + local expected_inode=$8 + local expected_uid=$9 + local expected_gid=${10} + local expected_hash=${11} + local marker=$path/$MANAGED_MARKER + local device inode uid gid + + [[ $allowed == 1 ]] || die "$kind directory is not marked as installer-owned: '$path'" + safe_purge_path "$path" "$safety_prefix" || die "refusing unsafe purge path '$path'" + if [[ ! -e $path && ! -L $path ]]; then + return 0 + fi + [[ -d $path && ! -L $path ]] || die "$kind purge path is not a real directory: '$path'" + [[ $expected_device =~ ^[0-9]+$ && $expected_inode =~ ^[0-9]+$ && + $expected_uid =~ ^[0-9]+$ && $expected_gid =~ ^[0-9]+$ && -n $expected_hash ]] || + die "$kind purge identity is incomplete" + device=$(stat -c '%d' -- "$path") + inode=$(stat -c '%i' -- "$path") + uid=$(stat -c '%u' -- "$path") + gid=$(stat -c '%g' -- "$path") + [[ $device == "$expected_device" && $inode == "$expected_inode" && + $uid == "$expected_uid" && $gid == "$expected_gid" ]] || + die "$kind directory identity changed; refusing purge: '$path'" + [[ -f $marker && ! -L $marker ]] || die "$kind ownership marker is missing: '$marker'" + [[ $(sha256_file "$marker") == "$expected_hash" ]] || + die "$kind ownership marker changed: '$marker'" + grep -Fx -- "install_id=$install_id" "$marker" >/dev/null || + die "$kind ownership marker has the wrong install identity" + grep -Fx -- "prefix=$marker_prefix" "$marker" >/dev/null || + die "$kind ownership marker belongs to another prefix" +} + +purge=0 +while [[ $# -gt 0 ]]; do + case $1 in + --purge) purge=1 ;; + --non-interactive) ;; + -h | --help) + usage + exit 0 + ;; + *) die "unknown option: $1" ;; + esac + shift +done + +SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +prefix=$SCRIPT_DIR +[[ $prefix != / ]] || die "refusing to uninstall from the filesystem root" +acquire_prefix_lock "$prefix" +record=$prefix/$RECORD_NAME +[[ -f $record ]] || die "install record is missing: $record" + +record_prefix= +relocatable=0 +service_scope=none +service_unit= +service_unit_sha256= +config_dir= +state_dir= +mode= +data_layout= +launcher= +launcher_sha256= +created_system_user=0 +service_uid= +service_gid= +install_id= +config_purge_allowed=0 +config_dir_device= +config_dir_inode= +config_dir_uid= +config_dir_gid= +config_marker_sha256= +state_purge_allowed=0 +state_dir_device= +state_dir_inode= +state_dir_uid= +state_dir_gid= +state_marker_sha256= +key= +value= +while IFS='=' read -r key value; do + case $key in + prefix) record_prefix=$value ;; + relocatable) relocatable=$value ;; + service_scope) service_scope=$value ;; + service_unit) service_unit=$value ;; + service_unit_sha256) service_unit_sha256=$value ;; + config_dir) config_dir=$value ;; + state_dir) state_dir=$value ;; + mode) mode=$value ;; + data_layout) data_layout=$value ;; + launcher) launcher=$value ;; + launcher_sha256) launcher_sha256=$value ;; + created_system_user) created_system_user=$value ;; + service_uid) service_uid=$value ;; + service_gid) service_gid=$value ;; + install_id) install_id=$value ;; + config_purge_allowed) config_purge_allowed=$value ;; + config_dir_device) config_dir_device=$value ;; + config_dir_inode) config_dir_inode=$value ;; + config_dir_uid) config_dir_uid=$value ;; + config_dir_gid) config_dir_gid=$value ;; + config_marker_sha256) config_marker_sha256=$value ;; + state_purge_allowed) state_purge_allowed=$value ;; + state_dir_device) state_dir_device=$value ;; + state_dir_inode) state_dir_inode=$value ;; + state_dir_uid) state_dir_uid=$value ;; + state_dir_gid) state_dir_gid=$value ;; + state_marker_sha256) state_marker_sha256=$value ;; + esac +done < "$record" + +case $relocatable in + 0) + [[ $record_prefix == "$prefix" ]] || + die "install record belongs to '$record_prefix', not '$prefix'" + ;; + 1) + [[ $record_prefix == . && $mode == portable && $data_layout == self-contained ]] || + die "relocatable install record is incomplete or unsafe" + [[ $config_dir == config && $state_dir == data ]] || + die "relocatable install record has unsafe mutable paths" + config_dir=$prefix/config + state_dir=$prefix/data + ;; + *) die "install record has an invalid relocatable value" ;; +esac +case $service_scope in + none | user | system) ;; + *) die "install record has an invalid service scope" ;; +esac +case $created_system_user in + 0 | 1) ;; + *) die "install record has an invalid created_system_user value" ;; +esac + +if [[ $service_scope == system || $mode == system || $created_system_user == 1 ]]; then + [[ ${EUID:-$(id -u)} -eq 0 ]] || die "uninstalling the system service requires root" +fi + +# Complete every destructive preflight before stopping the service or removing +# any files, so a refused purge leaves the installation fully retryable. +if [[ $service_scope != none ]]; then + [[ -n $service_unit && -n $service_unit_sha256 ]] || die "service record is incomplete" + safe_unit_path "$service_scope" "$service_unit" || die "service record has an unsafe unit path" + [[ -f $service_unit ]] || die "registered service unit is missing: $service_unit" + [[ $(sha256_file "$service_unit") == "$service_unit_sha256" ]] || + die "service unit was modified; refusing to remove it: $service_unit" +fi + +launcher_path= +if [[ -n $launcher ]]; then + [[ $launcher == echoion && $launcher_sha256 =~ ^[0-9a-f]{64}$ ]] || + die "portable launcher record is incomplete or unsafe" + launcher_path=$prefix/$launcher + [[ -f $launcher_path && ! -L $launcher_path && -x $launcher_path ]] || + die "recorded portable launcher is missing or unsafe: $launcher_path" + [[ $(sha256_file "$launcher_path") == "$launcher_sha256" ]] || + die "portable launcher was modified; refusing to remove it: $launcher_path" +elif [[ -n $launcher_sha256 ]]; then + die "portable launcher record is incomplete" +fi + +if [[ -e $prefix/current && ! -L $prefix/current ]]; then + die "current is not a symlink; refusing to remove runtime files" +fi + +if [[ $purge -eq 1 ]]; then + [[ $install_id =~ ^[A-Za-z0-9-]{16,64}$ ]] || die "install record has no safe install identity" + [[ -n $config_dir && -n $state_dir ]] || die "install record has an empty purge path" + validate_managed_purge_path config "$config_dir" "$prefix" "$record_prefix" "$install_id" \ + "$config_purge_allowed" "$config_dir_device" "$config_dir_inode" \ + "$config_dir_uid" "$config_dir_gid" "$config_marker_sha256" + validate_managed_purge_path state "$state_dir" "$prefix" "$record_prefix" "$install_id" \ + "$state_purge_allowed" "$state_dir_device" "$state_dir_inode" \ + "$state_dir_uid" "$state_dir_gid" "$state_marker_sha256" +fi + +service_account_present=0 +if [[ $purge -eq 1 && $created_system_user == 1 ]]; then + [[ $service_uid =~ ^[0-9]+$ && $service_gid =~ ^[0-9]+$ ]] || + die "installer-created service account record has no uid/gid identity" + if id -u "$SERVICE_USER" >/dev/null 2>&1; then + [[ $(id -u "$SERVICE_USER") -eq $service_uid && + $(id -g "$SERVICE_USER") -eq $service_gid ]] || + die "the recorded $SERVICE_USER account was deleted or replaced" + service_account_present=1 + fi +fi + +if [[ $service_scope != none ]]; then + if ! systemctl_for "$service_scope" disable --now "$SERVICE_NAME"; then + die "could not stop and disable $SERVICE_NAME; runtime was not removed" + fi +fi + +rm -f -- "$prefix/current" +rm -rf -- "$prefix/versions" + +if [[ $purge -eq 1 ]]; then + if [[ $config_dir == "$state_dir" ]]; then + rm -rf -- "$config_dir" + else + rm -rf -- "$config_dir" "$state_dir" + fi +fi + +if [[ $purge -eq 1 && $created_system_user == 1 && $service_account_present -eq 1 ]]; then + userdel "$SERVICE_USER" +fi + +if [[ $service_scope != none ]]; then + rm -f -- "$service_unit" + systemctl_for "$service_scope" daemon-reload || warn "systemd daemon-reload failed" +fi + +[[ -z $launcher_path ]] || rm -f -- "$launcher_path" +rm -f -- "$record" "$prefix/install.sh" "$prefix/uninstall.sh" +rmdir -- "$prefix" 2>/dev/null || true + +printf 'Echoion runtime removed from %s.\n' "$prefix" +if [[ $purge -eq 0 ]]; then + printf 'Configuration and state were preserved:\n %s\n %s\n' "$config_dir" "$state_dir" +fi diff --git a/scripts/collect-frontend-licenses.py b/scripts/collect-frontend-licenses.py new file mode 100755 index 0000000..80abe68 --- /dev/null +++ b/scripts/collect-frontend-licenses.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Collect deterministic license notices from an installed npm dependency tree.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import stat +import sys +import tempfile +from typing import Any +from urllib.parse import quote + + +NOTICE_FILE_PATTERN = re.compile( + r"^(?:licen[cs]e|copying|notice|copyright)(?:$|[._-].*)", + re.IGNORECASE, +) + + +class CollectionError(RuntimeError): + """Raised when dependency metadata cannot produce a trustworthy notice.""" + + +def is_package_root(package_json: Path, node_modules: Path) -> bool: + relative_parts = package_json.parent.relative_to(node_modules).parts + node_modules_indices = [ + index + for index, component in enumerate(relative_parts) + if component == "node_modules" + ] + package_start = node_modules_indices[-1] + 1 if node_modules_indices else 0 + package_parts = relative_parts[package_start:] + if len(package_parts) == 1: + return not package_parts[0].startswith("@") + return ( + len(package_parts) == 2 + and package_parts[0].startswith("@") + and len(package_parts[0]) > 1 + ) + + +def package_json_files(node_modules: Path) -> list[Path]: + def fail_walk(error: OSError) -> None: + raise CollectionError(f"cannot scan {error.filename}: {error.strerror}") + + package_files: list[Path] = [] + for directory, child_directories, filenames in os.walk( + node_modules, followlinks=False, onerror=fail_walk + ): + child_directories.sort() + filenames.sort() + if "package.json" not in filenames: + continue + candidate = Path(directory, "package.json") + if not stat.S_ISREG(candidate.lstat().st_mode): + continue + if is_package_root(candidate, node_modules): + package_files.append(candidate) + return package_files + + +def require_metadata_text(metadata: dict[str, Any], field: str, source: Path) -> str: + value = metadata.get(field) + if not isinstance(value, str) or not value.strip(): + raise CollectionError(f"{source}: {field!r} must be a non-empty string") + value = value.strip() + if any(ord(character) < 32 or ord(character) == 127 for character in value): + raise CollectionError(f"{source}: {field!r} contains control characters") + return value + + +def require_plain_text(value: Any, description: str, source: Path) -> str: + if not isinstance(value, str) or not value.strip(): + raise CollectionError(f"{source}: {description} must be a non-empty string") + value = value.strip() + if any(ord(character) < 32 or ord(character) == 127 for character in value): + raise CollectionError(f"{source}: {description} contains control characters") + return value + + +def validate_package_name(name: str, source: Path) -> None: + components = name.split("/") + valid_scope = ( + len(components) == 2 + and components[0].startswith("@") + and len(components[0]) > 1 + ) + if not (len(components) == 1 and not name.startswith("@")) and not valid_scope: + raise CollectionError(f"{source}: invalid npm package name {name!r}") + if any(component in {"", ".", ".."} for component in components): + raise CollectionError(f"{source}: invalid npm package name {name!r}") + if "\\" in name: + raise CollectionError(f"{source}: invalid npm package name {name!r}") + + +def describe_license_entry(value: Any, source: Path) -> str: + if isinstance(value, str): + return require_plain_text(value, "license", source) + if isinstance(value, dict): + description = require_plain_text( + value.get("type"), "license object type", source + ) + license_url = value.get("url") + if license_url is not None: + description += ( + f" ({require_plain_text(license_url, 'license URL', source)})" + ) + return description + raise CollectionError(f"{source}: license metadata has an unsupported form") + + +def declared_license(metadata: dict[str, Any], source: Path) -> str: + if "license" in metadata: + return describe_license_entry(metadata["license"], source) + + legacy_licenses = metadata.get("licenses") + if not isinstance(legacy_licenses, list) or not legacy_licenses: + raise CollectionError(f"{source}: package has no declared license") + descriptions = sorted( + {describe_license_entry(value, source) for value in legacy_licenses} + ) + return "; ".join(descriptions) + + +def notice_files(package_root: Path) -> dict[str, bytes]: + notices: dict[str, bytes] = {} + with os.scandir(package_root) as entries: + for entry in sorted(entries, key=lambda candidate: candidate.name): + if not NOTICE_FILE_PATTERN.match(entry.name): + continue + if not entry.is_file(follow_symlinks=False): + continue + notices[entry.name] = Path(entry.path).read_bytes() + return notices + + +def output_component(value: str, *, safe: str) -> str: + return quote(value, safe=safe) + + +def collect(node_modules: Path, destination: Path) -> int: + if not node_modules.is_dir(): + raise CollectionError(f"node_modules directory does not exist: {node_modules}") + + packages: dict[tuple[str, str], tuple[str, dict[str, bytes], Path]] = {} + for package_file in package_json_files(node_modules): + try: + metadata = json.loads(package_file.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + raise CollectionError(f"cannot read {package_file}: {error}") from error + if not isinstance(metadata, dict): + raise CollectionError(f"{package_file}: package metadata must be an object") + + name = require_metadata_text(metadata, "name", package_file) + version = require_metadata_text(metadata, "version", package_file) + validate_package_name(name, package_file) + license_description = declared_license(metadata, package_file) + notices = notice_files(package_file.parent) + key = (name, version) + + previous = packages.get(key) + if previous is not None: + previous_license, previous_notices, previous_source = previous + if previous_license != license_description or previous_notices != notices: + raise CollectionError( + f"conflicting contents for {name}@{version}: " + f"{previous_source} and {package_file}" + ) + continue + packages[key] = (license_description, notices, package_file) + + if not packages: + raise CollectionError(f"no npm packages found below {node_modules}") + + destination_parent = destination.parent + destination_parent.mkdir(parents=True, exist_ok=True) + temporary = Path( + tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination_parent) + ) + try: + temporary.chmod(0o755) + notice_lines = [ + "Echoion frontend third-party notices", + "", + "Generated from the installed npm dependency tree.", + "Packages are sorted by name and version.", + "", + ] + output_directories: set[str] = set() + for (name, version), (license_description, notices, _) in sorted( + packages.items() + ): + directory_name = ( + output_component(name, safe="@._+-") + + "@" + + output_component(version, safe="._+-") + ) + if directory_name in output_directories: + raise CollectionError( + f"output-name collision while collecting {name}@{version}" + ) + output_directories.add(directory_name) + + package_destination = temporary / directory_name + package_destination.mkdir(mode=0o755) + package_destination.chmod(0o755) + copied_files: list[str] = [] + for filename, contents in sorted(notices.items()): + output_name = output_component(filename, safe="._+-") + target = package_destination / output_name + target.write_bytes(contents) + target.chmod(0o644) + copied_files.append(f"{directory_name}/{output_name}") + + notice_lines.append(f"Package: {name}@{version}") + notice_lines.append(f"Declared license: {license_description}") + if copied_files: + notice_lines.append("Notice files:") + notice_lines.extend(f" {filename}" for filename in copied_files) + else: + notice_lines.append("Notice files: none published at package root") + notice_lines.append("") + + notices_path = temporary / "THIRD-PARTY-NOTICES.txt" + notices_path.write_text("\n".join(notice_lines), encoding="utf-8", newline="\n") + notices_path.chmod(0o644) + + if destination.is_symlink() or ( + destination.exists() and not destination.is_dir() + ): + raise CollectionError( + f"destination is not a regular directory: {destination}" + ) + if destination.exists(): + shutil.rmtree(destination) + os.replace(temporary, destination) + except BaseException: + shutil.rmtree(temporary, ignore_errors=True) + raise + + return len(packages) + + +def parse_arguments() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="collect npm dependency licenses for an Echoion release" + ) + parser.add_argument("--node-modules", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + return parser.parse_args() + + +def main() -> int: + arguments = parse_arguments() + try: + count = collect( + arguments.node_modules.resolve(), + Path(os.path.abspath(arguments.output)), + ) + except (CollectionError, OSError) as error: + print(f"collect-frontend-licenses: {error}", file=sys.stderr) + return 2 + print(f"Collected notices for {count} frontend npm packages.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/configured-cxx-compiler.sh b/scripts/configured-cxx-compiler.sh new file mode 100755 index 0000000..207be29 --- /dev/null +++ b/scripts/configured-cxx-compiler.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + echo "usage: $0 BUILD_DIR" >&2 + exit 2 +fi + +cache=$(realpath -e -- "$1/CMakeCache.txt") +compiler= +while IFS= read -r line; do + case $line in + CMAKE_CXX_COMPILER:FILEPATH=* | CMAKE_CXX_COMPILER:STRING=*) + [[ -z $compiler ]] || { + echo "duplicate CMAKE_CXX_COMPILER entries in $cache" >&2 + exit 2 + } + compiler=${line#*=} + ;; + esac +done <"$cache" + +[[ $compiler == /* && -x $compiler ]] || { + echo "CMake cache has no executable absolute C++ compiler: $cache" >&2 + exit 2 +} +realpath -e -- "$compiler" diff --git a/scripts/generate-release-manifest.py b/scripts/generate-release-manifest.py new file mode 100755 index 0000000..8d019e8 --- /dev/null +++ b/scripts/generate-release-manifest.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Generate Echoion's deterministic v2 immutable-payload manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import stat +import tempfile + + +VERSION_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") +IMMUTABLE_ROOTS = ("bin", "lib", "service", "share") +UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def safe_symlink_target(root: Path, path: Path) -> str: + target = os.readlink(path) + target_path = PurePosixPath(target) + target_components = target.split("/") + if ( + not target + or target_path.is_absolute() + or any(component in ("", ".", "..") for component in target_components) + ): + raise ValueError(f"unsafe symlink target for {path}: {target!r}") + + try: + resolved = path.resolve(strict=True) + resolved.relative_to(root) + except (FileNotFoundError, RuntimeError, ValueError) as error: + raise ValueError(f"symlink escapes the payload or is dangling: {path}") from error + return target + + +def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None: + if metadata.st_mode & UNSAFE_WRITABLE_MODE: + raise ValueError(f"immutable payload path is group- or world-writable: {path}") + + +def collect_entries(root: Path) -> list[dict[str, object]]: + entries: list[dict[str, object]] = [] + root_metadata = root.lstat() + if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink(): + raise ValueError(f"immutable payload root is not a directory: {root}") + reject_unsafe_writable_mode(root, root_metadata) + pending = [root / name for name in IMMUTABLE_ROOTS] + for directory in pending: + try: + metadata = directory.lstat() + except FileNotFoundError as error: + raise ValueError( + f"missing immutable payload directory: {directory}" + ) from error + if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink(): + raise ValueError(f"missing immutable payload directory: {directory}") + reject_unsafe_writable_mode(directory, metadata) + + while pending: + directory = pending.pop() + with os.scandir(directory) as iterator: + children = sorted(iterator, key=lambda item: item.name) + for child in children: + path = Path(child.path) + relative = path.relative_to(root).as_posix() + metadata = path.lstat() + if stat.S_ISLNK(metadata.st_mode): + entries.append( + { + "path": relative, + "type": "symlink", + "target": safe_symlink_target(root, path), + } + ) + elif stat.S_ISDIR(metadata.st_mode): + reject_unsafe_writable_mode(path, metadata) + pending.append(path) + elif stat.S_ISREG(metadata.st_mode): + reject_unsafe_writable_mode(path, metadata) + if metadata.st_size > (1 << 53) - 1: + raise ValueError(f"payload file is too large for the manifest: {path}") + entries.append( + { + "path": relative, + "type": "file", + "size": metadata.st_size, + "sha256": sha256(path), + "mode": f"{stat.S_IMODE(metadata.st_mode):04o}", + } + ) + else: + raise ValueError(f"unsupported special file in payload: {path}") + + entries.sort(key=lambda entry: str(entry["path"])) + return entries + + +def write_manifest(root: Path, version: str, output: Path) -> None: + entries = collect_entries(root) + regular_files = { + str(entry["path"]) for entry in entries if entry["type"] == "file" + } + executable = "bin/echoiond" + core = "lib/Echoion.ts" + web_index = "share/echoion/web/index.html" + for description, required in ( + ("executable", executable), + ("Core library", core), + ("web dashboard entry point", web_index), + ): + if required not in regular_files: + raise ValueError(f"manifest {description} is missing: {required}") + if not os.access(root / executable, os.X_OK): + raise ValueError(f"manifest executable is not executable: {executable}") + + manifest = { + "schemaVersion": 2, + "version": version, + "executable": executable, + "core": core, + "files": entries, + } + output.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{output.name}.", dir=output.parent + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + json.dump(manifest, stream, ensure_ascii=False, indent=2) + stream.write("\n") + os.chmod(temporary_name, 0o644) + os.replace(temporary_name, output) + except BaseException: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass + raise + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--version", required=True) + parser.add_argument("--output", type=Path) + arguments = parser.parse_args() + + if not VERSION_PATTERN.fullmatch(arguments.version): + parser.error("version must contain only letters, digits, dot, underscore, or dash") + root = arguments.root.resolve(strict=True) + output = arguments.output or root / "manifest.json" + write_manifest(root, arguments.version, output) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/package-release-payload.sh b/scripts/package-release-payload.sh new file mode 100755 index 0000000..4eb6353 --- /dev/null +++ b/scripts/package-release-payload.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 6 ]]; then + echo "usage: $0 STAGE ARTIFACT_BASE SOURCE_DATE_EPOCH ARCHIVE INSTALLER WORK_DIR" >&2 + exit 2 +fi + +stage=$(realpath -e -- "$1") +artifact_base=$2 +source_date_epoch=$3 +archive=$(realpath -m -- "$4") +installer=$(realpath -m -- "$5") +work_dir=$(realpath -m -- "$6") + +[[ $artifact_base =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || { + echo "invalid artifact base: $artifact_base" >&2 + exit 2 +} +[[ $source_date_epoch =~ ^[0-9]+$ ]] || { + echo "SOURCE_DATE_EPOCH must be a non-negative integer" >&2 + exit 2 +} +[[ -x $stage/install.sh && -x $stage/uninstall.sh ]] || { + echo "stage is missing executable installer helpers" >&2 + exit 2 +} +[[ -f $stage/manifest.json && -x $stage/bin/echoiond && -f $stage/lib/Echoion.ts ]] || { + echo "stage is missing required Echoion payload files" >&2 + exit 2 +} + +mkdir -p -- "$(dirname -- "$archive")" "$(dirname -- "$installer")" "$work_dir" +archive_tmp="$(dirname -- "$archive")/.$(basename -- "$archive").tmp.$$" +installer_tmp="$(dirname -- "$installer")/.$(basename -- "$installer").tmp.$$" +gzip_payload="$work_dir/$artifact_base.tar.gz.$$" +header="$work_dir/$artifact_base.run-header.$$" +cleanup() { + rm -f -- "$archive_tmp" "$installer_tmp" "$gzip_payload" "$header" +} +trap cleanup EXIT + +tar_options=( + --sort=name + "--mtime=@$source_date_epoch" + --owner=0 + --group=0 + --numeric-owner + --format=posix + '--pax-option=delete=atime,delete=ctime' +) + +tar -C "$stage" "${tar_options[@]}" \ + --transform="s,^\\.$,$artifact_base," \ + --transform="s,^\\./,$artifact_base/," \ + -cf - . | + zstd -T1 -19 --no-progress -o "$archive_tmp" +mv -f -- "$archive_tmp" "$archive" + +tar -C "$stage" "${tar_options[@]}" -cf - . | gzip -n -9 >"$gzip_payload" +cat >"$header" <<'RUN_HEADER' +#!/bin/sh +set -eu + +self=$0 +case $self in + /*) ;; + *) self=$(pwd)/$self ;; +esac +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-installer.XXXXXX") +cleanup() { + rm -rf -- "$temporary" +} +trap cleanup EXIT HUP INT TERM +payload_line=$(awk '/^__ECHOION_PAYLOAD_BELOW__$/ { print NR + 1; exit }' "$self") +if [ -z "$payload_line" ]; then + echo "Echoion installer payload marker is missing" >&2 + exit 2 +fi +tail -n "+$payload_line" "$self" | + tar --same-permissions --no-same-owner -xzf - -C "$temporary" +"$temporary/install.sh" "$@" +status=$? +exit "$status" +__ECHOION_PAYLOAD_BELOW__ +RUN_HEADER +cat "$header" "$gzip_payload" >"$installer_tmp" +chmod 0755 "$installer_tmp" +mv -f -- "$installer_tmp" "$installer" +trap - EXIT diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100755 index 0000000..89679e2 --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,354 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'EOF' +usage: scripts/release.sh --version VERSION [options] + +Options: + --build-dir DIR Clean build directory (default: build-release) + --dist-dir DIR Release output directory (default: dist) + --jobs N Parallel build jobs + --skip-tests Skip CTest and frontend tests + --no-clean Reuse the configured build directory + --container Build with containers/release.Dockerfile (the default) + --host Explicitly build directly on this host + -h, --help Show this help + +The release process never starts echoiond. Runtime validation uses readelf. +EOF +} + +die() { + echo "release: $*" >&2 + exit 2 +} + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +source_dir=$(cd -- "$script_dir/.." && pwd -P) +version= +build_dir="$source_dir/build-release" +dist_dir="$source_dir/dist" +jobs= +run_tests=1 +clean_build=1 +use_container=1 + +while (($#)); do + case $1 in + --version) + (($# >= 2)) || die "--version requires a value" + version=$2 + shift 2 + ;; + --build-dir) + (($# >= 2)) || die "--build-dir requires a value" + build_dir=$2 + shift 2 + ;; + --dist-dir) + (($# >= 2)) || die "--dist-dir requires a value" + dist_dir=$2 + shift 2 + ;; + --jobs) + (($# >= 2)) || die "--jobs requires a value" + jobs=$2 + shift 2 + ;; + --skip-tests) + run_tests=0 + shift + ;; + --no-clean) + clean_build=0 + shift + ;; + --container) + use_container=1 + shift + ;; + --host) + use_container=0 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + die "unknown argument: $1" + ;; + esac +done + +[[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || + die "--version must contain only letters, digits, dot, underscore, or dash" +if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then + die "--jobs must be a positive integer" +fi + +build_dir=$(realpath -m -- "$build_dir") +dist_dir=$(realpath -m -- "$dist_dir") + +container_path() { + local path=$1 + case $path in + "$source_dir") echo /workspace ;; + "$source_dir"/*) echo "/workspace/${path#"$source_dir"/}" ;; + *) die "container build and dist directories must be inside $source_dir" ;; + esac +} + +if ((use_container)); then + command -v docker >/dev/null || die "docker is required for --container" + container_build_dir=$(container_path "$build_dir") + container_dist_dir=$(container_path "$dist_dir") + image="echoion-release-builder:gcc-16.1.0" + docker build \ + --platform linux/amd64 \ + --file "$source_dir/containers/release.Dockerfile" \ + --tag "$image" \ + "$source_dir" + container_args=( + --rm + --user "$(id -u):$(id -g)" + --volume "$source_dir:/workspace" + --workdir /workspace + --env HOME=/tmp/echoion-release-home + --env npm_config_cache=/tmp/echoion-npm-cache + ) + if [[ -n ${SOURCE_DATE_EPOCH:-} ]]; then + container_args+=(--env "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH") + fi + release_args=( + --host + --version "$version" + --build-dir "$container_build_dir" + --dist-dir "$container_dist_dir" + ) + [[ -n $jobs ]] && release_args+=(--jobs "$jobs") + ((run_tests)) || release_args+=(--skip-tests) + ((clean_build)) || release_args+=(--no-clean) + docker run --platform linux/amd64 "${container_args[@]}" "$image" \ + bash scripts/release.sh "${release_args[@]}" + exit +fi + +case "$(uname -s)/$(uname -m)" in + Linux/x86_64|Linux/amd64) ;; + *) die "host release builds require Linux x86_64; use the amd64 container builder" ;; +esac + +required_commands=( + cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum + dpkg-query ldconfig +) +for command_name in "${required_commands[@]}"; do + command -v "$command_name" >/dev/null || die "required command not found: $command_name" +done +[[ -x $source_dir/packaging/install.sh ]] || + die "installer source is missing: packaging/install.sh" +[[ -x $source_dir/packaging/uninstall.sh ]] || + die "uninstaller source is missing: packaging/uninstall.sh" +[[ -f $source_dir/packaging/service/echoion.service.in ]] || + die "service template is missing: packaging/service/echoion.service.in" + +if [[ -z ${SOURCE_DATE_EPOCH:-} ]]; then + SOURCE_DATE_EPOCH=$(git -C "$source_dir" log -1 --format=%ct 2>/dev/null || true) + [[ $SOURCE_DATE_EPOCH =~ ^[0-9]+$ ]] || SOURCE_DATE_EPOCH=0 +fi +export SOURCE_DATE_EPOCH + +safe_remove_tree() { + local path=$1 + case $path in + "$source_dir"/build*|/tmp/*) ;; + *) die "refusing to clean non-build path outside source build*/ or /tmp: $path" ;; + esac + rm -rf -- "$path" +} + +if ((clean_build)); then + safe_remove_tree "$build_dir" +fi +mkdir -p "$build_dir" + +configure_args=(--preset linux-release -B "$build_dir") +npm --prefix "$source_dir/EchoionWeb/frontend" ci --no-audit --no-fund +cmake -E rm -rf "$source_dir/EchoionWeb/frontend/web-dist" +( + cd "$source_dir" + cmake "${configure_args[@]}" +) +build_args=(--build "$build_dir" --config Release) +[[ -n $jobs ]] && build_args+=(--parallel "$jobs") +cmake "${build_args[@]}" + +if ((run_tests)); then + ctest --test-dir "$build_dir" --build-config Release --output-on-failure + npm --prefix "$source_dir/EchoionWeb/frontend" test + npm --prefix "$source_dir/EchoionWeb/frontend" run i18n:check +fi + +stage="$build_dir/runtime-stage" +safe_remove_tree "$stage" +cmake --install "$build_dir" \ + --config Release \ + --component Runtime \ + --prefix "$stage" + +mapfile -t library_directories < <( + find "$build_dir" -type f \( -name '*.so' -o -name '*.so.*' -o -name '*.ts' \) \ + -printf '%h\n' | LC_ALL=C sort -u +) +library_directories+=("$stage/lib") +cxx_compiler=$("$source_dir/scripts/configured-cxx-compiler.sh" "$build_dir") +compiler_runtime_files=() +for runtime_name in libstdc++.so.6 libgcc_s.so.1; do + runtime_path=$( + "$cxx_compiler" -print-file-name="$runtime_name" + ) || die "cannot locate $runtime_name with $cxx_compiler" + [[ $runtime_path == /* && -f $runtime_path ]] || + die "$cxx_compiler did not return an existing absolute path for $runtime_name" + compiler_runtime_files+=("$runtime_path") + library_directories+=("$(dirname -- "$runtime_path")") +done +search_directories=$(IFS=';'; echo "${library_directories[*]}") +compiler_runtimes=$(IFS=';'; echo "${compiler_runtime_files[*]}") +cmake \ + "-DBUNDLE_ROOT=$stage" \ + "-DBUNDLE_RESOLVER_EXECUTABLE=$build_dir/bin/echoiond" \ + "-DBUNDLE_RESOLVER_LIBRARIES=$build_dir/lib/Echoion.ts" \ + "-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \ + "-DBUNDLE_SEED_FILES=$compiler_runtimes" \ + "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ + -P "$source_dir/cmake/BundleRuntimeDependencies.cmake" + +dependency_report="$build_dir/dependency-report.txt" +python3 "$source_dir/scripts/validate-release-elf.py" \ + --root "$stage" \ + --max-glibc 2.35 \ + --report "$dependency_report" + +collect_licenses() { + local destination=$1 + local candidate relative package_name license_name digest target package source_path soname + local -a license_roots=( + "$source_dir/EchoionApi" + "$source_dir/EchoionCore" + "$source_dir/EchoionHost" + "$source_dir/EchoionStandalone" + "$source_dir/EchoionWeb" + "$build_dir/_deps" + ) + if [[ -n ${GCC_ROOT:-} && -d $GCC_ROOT/share/licenses ]]; then + license_roots+=("$GCC_ROOT/share/licenses") + fi + if [[ -n ${BOOST_ROOT:-} && -d $BOOST_ROOT/share/licenses ]]; then + license_roots+=("$BOOST_ROOT/share/licenses") + fi + if [[ -n ${FFMPEG_ROOT:-} && -d $FFMPEG_ROOT/share/licenses ]]; then + license_roots+=("$FFMPEG_ROOT/share/licenses") + fi + mkdir -p "$destination" + + for source_path in "${license_roots[@]}"; do + [[ -d $source_path ]] || continue + while IFS= read -r -d '' candidate; do + relative=${candidate#"$source_path"/} + if [[ $relative == */* ]]; then + package_name=${relative%%/*} + else + package_name=$(basename -- "$source_path") + fi + license_name=$(basename -- "$candidate") + package_name=${package_name//[^A-Za-z0-9._+-]/_} + license_name=${license_name//[^A-Za-z0-9._+-]/_} + digest=$(sha256sum "$candidate" | cut -c1-12) + target="$destination/${package_name}--${license_name}--${digest}" + install -m 0644 -- "$candidate" "$target" + done < <( + find "$source_path" -maxdepth 5 -type f \ + \( -iname 'LICENSE' -o -iname 'LICENSE.txt' -o \ + -iname 'LICENSE.md' -o -iname 'LICENSE.rst' -o \ + -iname 'LICENSE-*' -o -iname 'LICENSE_*' -o \ + -iname 'COPYING' -o -iname 'COPYING.*' -o \ + -iname 'NOTICE' -o -iname 'NOTICE.*' -o \ + -iname 'COPYRIGHT' -o -iname 'COPYRIGHT.*' \) \ + -not -path '*/node_modules/*' -not -path '*/.git/*' \ + -print0 | LC_ALL=C sort -z + ) + done + + if command -v dpkg-query >/dev/null && command -v ldconfig >/dev/null; then + while IFS= read -r soname; do + [[ -n $soname ]] || continue + source_path=$(ldconfig -p 2>/dev/null | + awk -v name="$soname" ' + $1 == name && !path { path = $NF } + END { if (path) print path } + ') + [[ -n $source_path ]] || continue + package=$(dpkg-query -S "$(readlink -f -- "$source_path")" 2>/dev/null | + sed -n '1s/: .*//p') || package= + [[ -n $package ]] || continue + package=${package%%:*} + candidate="/usr/share/doc/${package}/copyright" + [[ -f $candidate ]] || continue + install -m 0644 -- "$candidate" "$destination/${package}--copyright" + done < <( + find "$stage/lib" -maxdepth 1 \( -type f -o -type l \) \ + -printf '%f\n' | LC_ALL=C sort -u + ) + fi +} + +collect_licenses "$stage/share/echoion/licenses" +python3 "$source_dir/scripts/collect-frontend-licenses.py" \ + --node-modules "$source_dir/EchoionWeb/frontend/node_modules" \ + --output "$stage/share/echoion/licenses/frontend" + +python3 "$source_dir/scripts/generate-release-manifest.py" \ + --root "$stage" \ + --version "$version" \ + --output "$stage/manifest.json" + +# Installer helpers are mutable prefix-level files and intentionally are not +# included in manifest.files. They are added only after the immutable manifest. +install -m 0755 "$source_dir/packaging/install.sh" "$stage/install.sh" +install -m 0755 "$source_dir/packaging/uninstall.sh" "$stage/uninstall.sh" + +mkdir -p "$dist_dir" +artifact_base="echoion-${version}-linux-x86_64" +archive="$dist_dir/$artifact_base.tar.zst" +installer="$dist_dir/$artifact_base.run" +external_manifest="$dist_dir/$artifact_base.manifest.json" +external_report="$dist_dir/$artifact_base.dependencies.txt" +rm -f -- \ + "$archive" "$archive.tmp" \ + "$installer" "$installer.tmp" \ + "$external_manifest" "$external_report" \ + "$dist_dir/SHA256SUMS" + +bash "$source_dir/scripts/package-release-payload.sh" \ + "$stage" "$artifact_base" "$SOURCE_DATE_EPOCH" \ + "$archive" "$installer" "$build_dir" + +install -m 0644 "$stage/manifest.json" "$external_manifest" +install -m 0644 "$dependency_report" "$external_report" +( + cd "$dist_dir" + sha256sum \ + "$(basename "$archive")" \ + "$(basename "$installer")" \ + "$(basename "$external_manifest")" \ + "$(basename "$external_report")" >SHA256SUMS +) + +echo "Release created without starting Echoion:" +echo " $archive" +echo " $installer" +echo " $external_manifest" +echo " $external_report" +echo " $dist_dir/SHA256SUMS" diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh index a3040e1..eb29209 100755 --- a/scripts/stage-release.sh +++ b/scripts/stage-release.sh @@ -1,63 +1,242 @@ #!/usr/bin/env bash set -euo pipefail -if [[ $# -lt 4 || $# -gt 5 ]]; then - echo "usage: $0 RELEASE_ROOT VERSION ECHOIOND ECHOION_CORE [MANIFEST]" >&2 +if [[ $# -lt 3 || $# -gt 4 ]]; then + echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2 exit 2 fi -release_root=$1 +release_root=$(realpath -m -- "$1") version=$2 -executable=$3 -core=$4 -manifest=${5:-"$release_root/pending-release.json"} +bundle_root=$(realpath -e -- "$3") +manifest=${4:-"$release_root/pending-release.json"} +manifest=$(realpath -m -- "$manifest") if [[ ! $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then echo "invalid release version: $version" >&2 exit 2 fi -if [[ ! -x $executable ]]; then - echo "echoiond is missing or not executable: $executable" >&2 +if [[ $bundle_root == "$release_root" || + $bundle_root == "$release_root"/* || + $release_root == "$bundle_root"/* ]]; then + echo "bundle root and release root must not overlap" >&2 exit 2 fi -if [[ ! -f $core ]]; then - echo "Core library is missing: $core" >&2 +if [[ $(dirname -- "$manifest") != "$release_root" ]]; then + echo "pending manifest must be written directly below the release root" >&2 + exit 2 +fi +if [[ ! -x $bundle_root/bin/echoiond ]]; then + echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&2 + exit 2 +fi +if [[ ! -f $bundle_root/lib/Echoion.ts ]]; then + echo "Core library is missing: $bundle_root/lib/Echoion.ts" >&2 + exit 2 +fi +if [[ ! -f $bundle_root/manifest.json ]]; then + echo "v2 release manifest is missing: $bundle_root/manifest.json" >&2 exit 2 fi -mkdir -p "$release_root" "$(dirname "$manifest")" +mkdir -p -- "$release_root" "$(dirname -- "$manifest")" staging="$release_root/.staging-$version-$$" destination="$release_root/$version" -trap 'rm -rf -- "$staging"' EXIT +manifest_tmp="$(dirname -- "$manifest")/.$(basename -- "$manifest").tmp.$$" +version_lock="$release_root/.stage-$version.lock" +destination_created=0 +manifest_published=0 +lock_acquired=0 +cleanup() { + rm -rf -- "$staging" + rm -f -- "$manifest_tmp" + if ((destination_created && !manifest_published)); then + rm -rf -- "$destination" + fi + if ((lock_acquired)); then + rmdir -- "$version_lock" 2>/dev/null || true + fi +} +trap cleanup EXIT + +if ! mkdir -- "$version_lock"; then + echo "release staging is already active for version $version" >&2 + exit 2 +fi +lock_acquired=1 if [[ -e $destination ]]; then echo "release already exists: $destination" >&2 exit 2 fi -mkdir "$staging" -install -m 0755 "$executable" "$staging/echoiond" -install -m 0644 "$core" "$staging/Echoion.ts" +mkdir -m 0755 -- "$staging" +cp -a -- "$bundle_root/." "$staging/" -executable_hash=$(sha256sum "$staging/echoiond" | cut -d' ' -f1) -core_hash=$(sha256sum "$staging/Echoion.ts" | cut -d' ' -f1) -mv "$staging" "$destination" +python3 - "$staging" "$version" "$manifest_tmp" <<'PY' +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import stat +import sys -manifest_tmp="$manifest.tmp.$$" -trap 'rm -rf -- "$staging"; rm -f -- "$manifest_tmp"' EXIT -printf '%s\n' \ - '{' \ - " \"version\": \"$version\"," \ - " \"executable\": \"$version/echoiond\"," \ - " \"core\": \"$version/Echoion.ts\"," \ - ' "sha256": {' \ - " \"executable\": \"$executable_hash\"," \ - " \"core\": \"$core_hash\"" \ - ' }' \ - '}' > "$manifest_tmp" -chmod 0644 "$manifest_tmp" -mv -f "$manifest_tmp" "$manifest" +IMMUTABLE_ROOTS = ("bin", "lib", "service", "share") +UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH + + +def reject_unsafe_writable_mode(path, metadata): + if metadata.st_mode & UNSAFE_WRITABLE_MODE: + raise SystemExit( + f"immutable payload path is group- or world-writable: {path}" + ) + + +root = Path(sys.argv[1]).resolve(strict=True) +version = sys.argv[2] +output = Path(sys.argv[3]) +source = root / "manifest.json" +with source.open("r", encoding="utf-8") as stream: + manifest = json.load(stream) + +if manifest.get("schemaVersion") != 2: + raise SystemExit("release manifest must use schemaVersion 2") +if manifest.get("version") != version: + raise SystemExit( + f"release version mismatch: expected {version!r}, got {manifest.get('version')!r}" + ) +entries = manifest.get("files") +if not isinstance(entries, list): + raise SystemExit("release manifest files must be an array") + +root_metadata = root.lstat() +if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink(): + raise SystemExit(f"immutable payload root is not a directory: {root}") +reject_unsafe_writable_mode(root, root_metadata) + +actual = set() +pending_directories = [root / name for name in IMMUTABLE_ROOTS] +for directory in pending_directories: + try: + metadata = directory.lstat() + except FileNotFoundError: + raise SystemExit(f"missing immutable payload directory: {directory}") + if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink(): + raise SystemExit(f"missing immutable payload directory: {directory}") + reject_unsafe_writable_mode(directory, metadata) + +while pending_directories: + directory = pending_directories.pop() + with os.scandir(directory) as iterator: + children = sorted(iterator, key=lambda item: item.name) + for child in children: + path = Path(child.path) + relative = path.relative_to(root).as_posix() + metadata = path.lstat() + if stat.S_ISDIR(metadata.st_mode): + reject_unsafe_writable_mode(path, metadata) + pending_directories.append(path) + elif stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode): + if stat.S_ISREG(metadata.st_mode): + reject_unsafe_writable_mode(path, metadata) + actual.add(relative) + else: + raise SystemExit(f"unsupported special file in payload: {path}") + +seen = set() +entry_types = {} +for entry in entries: + if not isinstance(entry, dict) or not isinstance(entry.get("path"), str): + raise SystemExit("invalid release manifest file entry") + relative = PurePosixPath(entry["path"]) + if ( + relative.is_absolute() + or not relative.parts + or relative.as_posix() != entry["path"] + or any(component in ("", ".", "..") for component in entry["path"].split("/")) + ): + raise SystemExit(f"unsafe manifest path: {entry['path']!r}") + if entry["path"] in seen: + raise SystemExit(f"duplicate manifest path: {entry['path']}") + if relative.parts[0] not in IMMUTABLE_ROOTS: + raise SystemExit( + f"manifest path is outside immutable payload roots: {entry['path']}" + ) + seen.add(entry["path"]) + entry_types[entry["path"]] = entry.get("type") + path = root.joinpath(*relative.parts) + metadata = path.lstat() + if entry.get("type") == "file": + if not stat.S_ISREG(metadata.st_mode): + raise SystemExit(f"manifest regular file is missing: {entry['path']}") + digest = hashlib.sha256(path.read_bytes()).hexdigest() + if digest != entry.get("sha256") or metadata.st_size != entry.get("size"): + raise SystemExit(f"manifest file verification failed: {entry['path']}") + mode = f"{stat.S_IMODE(metadata.st_mode):04o}" + if mode != entry.get("mode"): + raise SystemExit(f"manifest mode verification failed: {entry['path']}") + reject_unsafe_writable_mode(path, metadata) + elif entry.get("type") == "symlink": + if not stat.S_ISLNK(metadata.st_mode): + raise SystemExit(f"manifest symlink is missing: {entry['path']}") + target = entry.get("target") + if not isinstance(target, str): + raise SystemExit(f"invalid manifest symlink target: {entry['path']}") + target_path = PurePosixPath(target) + if ( + target_path.is_absolute() + or any(component in ("", ".", "..") for component in target.split("/")) + ): + raise SystemExit(f"unsafe manifest symlink target: {entry['path']}") + if os.readlink(path) != target: + raise SystemExit(f"manifest symlink verification failed: {entry['path']}") + try: + path.resolve(strict=True).relative_to(root) + except (FileNotFoundError, RuntimeError, ValueError): + raise SystemExit(f"manifest symlink escapes release root: {entry['path']}") + else: + raise SystemExit(f"invalid manifest entry type: {entry.get('type')!r}") + +if seen != actual: + undeclared = sorted(actual - seen) + missing = sorted(seen - actual) + details = [] + if undeclared: + details.append("undeclared=" + ",".join(undeclared)) + if missing: + details.append("missing=" + ",".join(missing)) + raise SystemExit("immutable payload coverage mismatch: " + "; ".join(details)) + +required_files = { + "executable": "bin/echoiond", + "core": "lib/Echoion.ts", + "web dashboard": "share/echoion/web/index.html", +} +for description, required in required_files.items(): + if description in ("executable", "core") and manifest.get(description) != required: + raise SystemExit(f"manifest {description} has a non-canonical path") + if required not in seen or entry_types.get(required) != "file": + raise SystemExit(f"manifest {description} is not declared as a file") + +prefix = f"{version}/" +pending = dict(manifest) +pending["executable"] = prefix + manifest["executable"] +pending["core"] = prefix + manifest["core"] +pending["files"] = [dict(entry, path=prefix + entry["path"]) for entry in entries] +with output.open("w", encoding="utf-8", newline="\n") as stream: + json.dump(pending, stream, ensure_ascii=False, indent=2) + stream.write("\n") +os.chmod(output, 0o644) +PY + +mv -T -- "$staging" "$destination" +destination_created=1 +mv -f -- "$manifest_tmp" "$manifest" +manifest_published=1 +rmdir -- "$version_lock" +lock_acquired=0 trap - EXIT echo "staged release $version" +echo "payload: $destination" echo "manifest: $manifest" diff --git a/scripts/tests/test-frontend-licenses.sh b/scripts/tests/test-frontend-licenses.sh new file mode 100755 index 0000000..72b0e06 --- /dev/null +++ b/scripts/tests/test-frontend-licenses.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + echo "usage: $0 SOURCE_ROOT" >&2 + exit 2 +fi + +source_root=$(realpath -e -- "$1") +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-frontend-licenses.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT +node_modules="$temporary/node_modules" + +mkdir -p \ + "$node_modules/plain/docs" \ + "$node_modules/@scope/example" \ + "$node_modules/parent/node_modules/duplicate" \ + "$node_modules/second/node_modules/duplicate" \ + "$node_modules/no-notice" + +printf '%s\n' \ + '{"name":"plain","version":"1.2.3","license":"MIT"}' \ + >"$node_modules/plain/package.json" +printf '%s\n' 'plain license' >"$node_modules/plain/LICENSE" +printf '%s\n' 'ignored nested file' >"$node_modules/plain/docs/LICENSE" +printf '%s\n' '{"name":"not-a-package-root"}' \ + >"$node_modules/plain/docs/package.json" + +printf '%s\n' \ + '{"name":"@scope/example","version":"2.0.0-beta.1","license":"Apache-2.0"}' \ + >"$node_modules/@scope/example/package.json" +printf '%s\n' 'scoped license' >"$node_modules/@scope/example/LICENCE.md" +printf '%s\n' 'scoped notice' >"$node_modules/@scope/example/NOTICE-extra" + +for package_root in \ + "$node_modules/parent/node_modules/duplicate" \ + "$node_modules/second/node_modules/duplicate"; do + printf '%s\n' \ + '{"name":"duplicate","version":"3.4.5","licenses":[{"type":"BSD-2-Clause"}]}' \ + >"$package_root/package.json" + printf '%s\n' 'duplicate copying' >"$package_root/COPYING.txt" +done + +printf '%s\n' \ + '{"name":"no-notice","version":"4.0.0","license":"ISC"}' \ + >"$node_modules/no-notice/package.json" + +output_one="$temporary/output-one" +output_two="$temporary/output-two" +( + umask 077 + python3 "$source_root/scripts/collect-frontend-licenses.py" \ + --node-modules "$node_modules" \ + --output "$output_one" +) +python3 "$source_root/scripts/collect-frontend-licenses.py" \ + --node-modules "$node_modules" \ + --output "$output_two" +diff -r -- "$output_one" "$output_two" + +[[ -f $output_one/plain@1.2.3/LICENSE ]] +[[ ! -e $output_one/plain@1.2.3/docs ]] +[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/LICENCE.md ]] +[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/NOTICE-extra ]] +[[ -f $output_one/duplicate@3.4.5/COPYING.txt ]] +[[ -d $output_one/no-notice@4.0.0 ]] + +if find "$output_one" -type d ! -perm 0755 -print -quit | grep -q .; then + echo "license collection created a directory with an unstable mode" >&2 + exit 1 +fi +if find "$output_one" -type f ! -perm 0644 -print -quit | grep -q .; then + echo "license collection created a file with an unstable mode" >&2 + exit 1 +fi + +python3 - "$output_one/THIRD-PARTY-NOTICES.txt" <<'PY' +from pathlib import Path +import sys + +contents = Path(sys.argv[1]).read_text(encoding="utf-8") +packages = [ + line.removeprefix("Package: ") + for line in contents.splitlines() + if line.startswith("Package: ") +] +assert packages == sorted(packages) +assert packages == [ + "@scope/example@2.0.0-beta.1", + "duplicate@3.4.5", + "no-notice@4.0.0", + "plain@1.2.3", +] +assert contents.count("Package: duplicate@3.4.5") == 1 +assert "Declared license: BSD-2-Clause" in contents +assert "Notice files: none published at package root" in contents +assert "@scope%2Fexample@2.0.0-beta.1/NOTICE-extra" in contents +PY + +mkdir -p "$temporary/malformed/node_modules/bad" +printf '%s\n' '{"name":"bad","version":"1.0.0"}' \ + >"$temporary/malformed/node_modules/bad/package.json" +error_file="$temporary/malformed.error" +if python3 "$source_root/scripts/collect-frontend-licenses.py" \ + --node-modules "$temporary/malformed/node_modules" \ + --output "$temporary/malformed-output" \ + >/dev/null 2>"$error_file"; then + echo "package without license metadata unexpectedly passed" >&2 + exit 1 +fi +grep -Fq 'package has no declared license' "$error_file" + +mkdir -p \ + "$temporary/conflict/node_modules/first/node_modules/same" \ + "$temporary/conflict/node_modules/second/node_modules/same" +for package_root in \ + "$temporary/conflict/node_modules/first/node_modules/same" \ + "$temporary/conflict/node_modules/second/node_modules/same"; do + printf '%s\n' \ + '{"name":"same","version":"1.0.0","license":"MIT"}' \ + >"$package_root/package.json" +done +printf '%s\n' first \ + >"$temporary/conflict/node_modules/first/node_modules/same/LICENSE" +printf '%s\n' second \ + >"$temporary/conflict/node_modules/second/node_modules/same/LICENSE" +if python3 "$source_root/scripts/collect-frontend-licenses.py" \ + --node-modules "$temporary/conflict/node_modules" \ + --output "$temporary/conflict-output" >/dev/null 2>&1; then + echo "conflicting duplicate package contents unexpectedly passed" >&2 + exit 1 +fi + +echo "frontend npm license collection regressions passed" diff --git a/scripts/tests/test-release-archive.sh b/scripts/tests/test-release-archive.sh new file mode 100755 index 0000000..74a04f6 --- /dev/null +++ b/scripts/tests/test-release-archive.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + echo "usage: $0 SOURCE_ROOT" >&2 + exit 2 +fi + +source_root=$(realpath -e -- "$1") +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-archive.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT +stage="$temporary/stage" +mkdir -p "$stage/bin" "$stage/lib" +install -m 0755 /bin/true "$stage/bin/echoiond" +install -m 0644 /bin/true "$stage/lib/Echoion.ts" +printf '%s\n' '{}' >"$stage/manifest.json" +cat >"$stage/install.sh" <<'INSTALL' +#!/bin/sh +set -eu +payload_root=$(CDPATH= cd -P -- "$(dirname -- "$0")" && pwd -P) +[ "$(stat -c '%a' -- "$payload_root/bin/echoiond")" = 755 ] +[ "$(stat -c '%a' -- "$payload_root/lib/Echoion.ts")" = 644 ] +[ "$1" = --record ] +record=$2 +shift 2 +printf '%s\n' "$@" >"$record" +INSTALL +printf '%s\n' '#!/bin/sh' 'exit 0' >"$stage/uninstall.sh" +chmod 0755 "$stage/install.sh" "$stage/uninstall.sh" + +base=echoion-1.2.3-linux-x86_64 +archive_one="$temporary/one.tar.zst" +installer_one="$temporary/one.run" +archive_two="$temporary/two.tar.zst" +installer_two="$temporary/two.run" +bash "$source_root/scripts/package-release-payload.sh" \ + "$stage" "$base" 1700000000 "$archive_one" "$installer_one" "$temporary" +bash "$source_root/scripts/package-release-payload.sh" \ + "$stage" "$base" 1700000000 "$archive_two" "$installer_two" "$temporary" +cmp "$archive_one" "$archive_two" +cmp "$installer_one" "$installer_two" + +mapfile -t members < <(tar --zstd -tf "$archive_one") +((${#members[@]} > 0)) +for member in "${members[@]}"; do + [[ $member == "$base" || $member == "$base/"* ]] || { + echo "archive member escaped top-level directory: $member" >&2 + exit 1 + } +done +printf '%s\n' "${members[@]}" | grep -Fx "$base/bin/echoiond" + +record="$temporary/installer-arguments" +( + umask 077 + "$installer_one" --record "$record" alpha 'two words' +) +printf '%s\n' alpha 'two words' >"$temporary/expected-arguments" +cmp "$temporary/expected-arguments" "$record" + +echo "release archive layout and .run regressions passed" diff --git a/scripts/tests/test-release-packaging.sh b/scripts/tests/test-release-packaging.sh new file mode 100755 index 0000000..c0e17f8 --- /dev/null +++ b/scripts/tests/test-release-packaging.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + echo "usage: $0 SOURCE_ROOT" >&2 + exit 2 +fi + +source_root=$(realpath -e -- "$1") +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT + +bundle="$temporary/bundle" +mkdir -p \ + "$bundle/bin" \ + "$bundle/lib" \ + "$bundle/service" \ + "$bundle/share/echoion/web" +install -m 0755 /bin/true "$bundle/bin/echoiond" +install -m 0644 /bin/true "$bundle/lib/Echoion.ts" +printf '%s\n' 'Echoion' \ + >"$bundle/share/echoion/web/index.html" +printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in" +ln -s Echoion.ts "$bundle/lib/Echoion-current.ts" + +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$bundle" --version 1.2.3 +cp "$bundle/manifest.json" "$temporary/manifest.first.json" +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$bundle" --version 1.2.3 +cmp "$temporary/manifest.first.json" "$bundle/manifest.json" + +unsafe_file_mode="$temporary/unsafe-file-mode" +cp -a "$bundle" "$unsafe_file_mode" +chmod 0666 "$unsafe_file_mode/lib/Echoion.ts" +if python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$unsafe_file_mode" --version 1.2.3 >/dev/null 2>&1; then + echo "world-writable payload file unexpectedly entered manifest" >&2 + exit 1 +fi + +unsafe_directory_mode="$temporary/unsafe-directory-mode" +cp -a "$bundle" "$unsafe_directory_mode" +chmod 0777 "$unsafe_directory_mode/lib" +if python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$unsafe_directory_mode" --version 1.2.3 >/dev/null 2>&1; then + echo "world-writable payload directory unexpectedly entered manifest" >&2 + exit 1 +fi + +python3 - "$bundle/manifest.json" <<'PY' +import json +import sys + +with open(sys.argv[1], encoding="utf-8") as stream: + manifest = json.load(stream) +assert manifest["schemaVersion"] == 2 +assert manifest["version"] == "1.2.3" +assert manifest["executable"] == "bin/echoiond" +assert manifest["core"] == "lib/Echoion.ts" +paths = [entry["path"] for entry in manifest["files"]] +assert paths == sorted(paths) +assert "share/echoion/web/index.html" in paths +link = next(entry for entry in manifest["files"] if entry["path"].endswith("current.ts")) +assert link == { + "path": "lib/Echoion-current.ts", + "type": "symlink", + "target": "Echoion.ts", +} +for entry in manifest["files"]: + if entry["type"] == "file": + assert set(entry) == {"path", "type", "size", "sha256", "mode"} + assert len(entry["sha256"]) == 64 + assert len(entry["mode"]) == 4 +PY + +printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/install.sh" +printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/uninstall.sh" +chmod 0755 "$bundle/install.sh" "$bundle/uninstall.sh" + +for overlapping_release_root in "$bundle" "$bundle/releases"; do + if bash "$source_root/scripts/stage-release.sh" \ + "$overlapping_release_root" 1.2.3 "$bundle" >/dev/null 2>&1; then + echo "overlapping bundle/release roots unexpectedly staged" >&2 + exit 1 + fi +done + +overlap_parent="$temporary/overlap-parent" +mkdir "$overlap_parent" +cp -a "$bundle" "$overlap_parent/bundle" +if bash "$source_root/scripts/stage-release.sh" \ + "$overlap_parent" 1.2.3 "$overlap_parent/bundle" >/dev/null 2>&1; then + echo "release root containing bundle root unexpectedly staged" >&2 + exit 1 +fi + +release_root="$temporary/releases" +bash "$source_root/scripts/stage-release.sh" \ + "$release_root" 1.2.3 "$bundle" +[[ -x $release_root/1.2.3/bin/echoiond ]] +[[ -L $release_root/1.2.3/lib/Echoion-current.ts ]] +[[ -x $release_root/1.2.3/install.sh ]] +python3 - "$release_root/pending-release.json" <<'PY' +import json +import sys + +with open(sys.argv[1], encoding="utf-8") as stream: + manifest = json.load(stream) +assert manifest["executable"] == "1.2.3/bin/echoiond" +assert manifest["core"] == "1.2.3/lib/Echoion.ts" +assert all(entry["path"].startswith("1.2.3/") for entry in manifest["files"]) +assert not any(entry["path"].endswith("install.sh") for entry in manifest["files"]) +PY + +tampered="$temporary/tampered" +cp -a "$bundle" "$tampered" +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$tampered" --version 1.2.4 +printf '%s\n' tampered >>"$tampered/lib/Echoion.ts" +if bash "$source_root/scripts/stage-release.sh" \ + "$release_root" 1.2.4 "$tampered" >/dev/null 2>&1; then + echo "tampered payload unexpectedly staged" >&2 + exit 1 +fi + +rogue="$temporary/rogue" +cp -a "$bundle" "$rogue" +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$rogue" --version 1.2.6 +printf '%s\n' rogue >"$rogue/lib/rogue.so" +if bash "$source_root/scripts/stage-release.sh" \ + "$release_root" 1.2.6 "$rogue" >/dev/null 2>&1; then + echo "undeclared immutable payload file unexpectedly staged" >&2 + exit 1 +fi +[[ ! -e $release_root/1.2.6 ]] + +outside_entry="$temporary/outside-entry" +cp -a "$bundle" "$outside_entry" +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$outside_entry" --version 1.2.8 +printf '%s\n' outside >"$outside_entry/outside.dat" +python3 - "$outside_entry/manifest.json" "$outside_entry/outside.dat" <<'PY' +import hashlib +import json +from pathlib import Path +import stat +import sys + +manifest_path = Path(sys.argv[1]) +outside = Path(sys.argv[2]) +with manifest_path.open(encoding="utf-8") as stream: + manifest = json.load(stream) +metadata = outside.stat() +manifest["files"].append( + { + "path": "outside.dat", + "type": "file", + "size": metadata.st_size, + "sha256": hashlib.sha256(outside.read_bytes()).hexdigest(), + "mode": f"{stat.S_IMODE(metadata.st_mode):04o}", + } +) +with manifest_path.open("w", encoding="utf-8", newline="\n") as stream: + json.dump(manifest, stream, indent=2) + stream.write("\n") +PY +if bash "$source_root/scripts/stage-release.sh" \ + "$release_root" 1.2.8 "$outside_entry" >/dev/null 2>&1; then + echo "manifest entry outside immutable roots unexpectedly staged" >&2 + exit 1 +fi +[[ ! -e $release_root/1.2.8 ]] + +mkdir "$release_root/.stage-1.2.7.lock" +lock_error="$temporary/stage-lock.error" +if bash "$source_root/scripts/stage-release.sh" \ + "$release_root" 1.2.7 "$bundle" > /dev/null 2>"$lock_error"; then + echo "concurrent same-version staging unexpectedly acquired the lock" >&2 + exit 1 +fi +grep -q 'release staging is already active' "$lock_error" +[[ ! -e $release_root/1.2.7 ]] +rmdir "$release_root/.stage-1.2.7.lock" +if find "$release_root" -mindepth 2 -name '.staging-*' | grep -q .; then + echo "staging directory was nested below a published release" >&2 + exit 1 +fi + +unsafe="$temporary/unsafe" +cp -a "$bundle" "$unsafe" +rm "$unsafe/lib/Echoion-current.ts" +ln -s ../bin/echoiond "$unsafe/lib/Echoion-current.ts" +if python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$unsafe" --version 1.2.5 >/dev/null 2>&1; then + echo "unsafe symlink unexpectedly entered manifest" >&2 + exit 1 +fi + +if bash "$source_root/scripts/stage-release.sh" \ + "$release_root" '../unsafe' "$bundle" >/dev/null 2>&1; then + echo "unsafe version unexpectedly staged" >&2 + exit 1 +fi + +echo "release manifest and staging regressions passed" diff --git a/scripts/tests/test-runtime-dependencies.sh b/scripts/tests/test-runtime-dependencies.sh new file mode 100755 index 0000000..01d4f77 --- /dev/null +++ b/scripts/tests/test-runtime-dependencies.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 ]]; then + echo "usage: $0 SOURCE_ROOT" >&2 + exit 2 +fi + +source_root=$(realpath -e -- "$1") +for command_name in cc cmake patchelf readelf python3; do + command -v "$command_name" >/dev/null || { + echo "missing test command: $command_name" >&2 + exit 2 + } +done + +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-runtime-deps.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT +configured_build="$temporary/configured-build" +mkdir -p "$configured_build" +configured_compiler=$(realpath -e -- "$(command -v c++)") +printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$configured_compiler" \ + >"$configured_build/CMakeCache.txt" +queried_compiler=$(CXX=/bin/false \ + "$source_root/scripts/configured-cxx-compiler.sh" "$configured_build") +[[ $queried_compiler == "$configured_compiler" ]] || { + echo "runtime compiler query followed CXX instead of the configured cache" >&2 + exit 1 +} + +preferred_lib="$temporary/preferred-lib" +other_lib="$temporary/other-lib" +bundle="$temporary/bundle" +resolver="$temporary/resolver" +seed_lib="$temporary/seed-lib" +mkdir -p \ + "$preferred_lib" \ + "$other_lib" \ + "$resolver" \ + "$seed_lib" \ + "$bundle/bin" \ + "$bundle/lib" \ + "$bundle/service" \ + "$bundle/share/echoion/web" + +cat >"$temporary/dependency.c" <<'C' +int echoion_dependency(void) { return 42; } +__attribute__((used, section(".echoion_variant"))) +static const char echoion_variant[] = ECHOION_VARIANT; +C +cat >"$temporary/core.c" <<'C' +extern int echoion_dependency(void); +extern int echoion_compiler_runtime(void); +int echoion_core(void) { + return echoion_dependency() + echoion_compiler_runtime(); +} +C +cat >"$temporary/main.c" <<'C' +int main(void) { return 0; } +C +cat >"$temporary/compiler-runtime.c" <<'C' +int echoion_compiler_runtime(void) { return 7; } +__attribute__((used, section(".echoion_compiler_variant"))) +static const char echoion_compiler_variant[] = ECHOION_VARIANT; +C + +for variant in preferred other; do + case $variant in + preferred) variant_lib=$preferred_lib ;; + other) variant_lib=$other_lib ;; + esac + cc -fPIC -shared "$temporary/dependency.c" \ + '-DECHOION_VARIANT="'"$variant"'-runtime"' \ + -Wl,-soname,libechoion-dependency.so.1 \ + -o "$variant_lib/libechoion-dependency.so.1.2.3" + ln -s libechoion-dependency.so.1.2.3 \ + "$variant_lib/libechoion-dependency.so.1" + ln -s libechoion-dependency.so.1 \ + "$variant_lib/libechoion-dependency.so" +done +for variant in seeded resolver; do + case $variant in + seeded) + variant_lib=$seed_lib + variant_version=100 + ;; + resolver) + variant_lib=$preferred_lib + variant_version=200 + ;; + esac + cc -fPIC -shared "$temporary/compiler-runtime.c" \ + '-DECHOION_VARIANT="'"$variant"'-compiler-runtime"' \ + -Wl,-soname,libstdc++.so.6 \ + -o "$variant_lib/libstdc++.so.6.0.$variant_version" + ln -s "libstdc++.so.6.0.$variant_version" \ + "$variant_lib/libstdc++.so.6" +done +resolver_core="$resolver/Echoion.ts" +cc -fPIC -shared "$temporary/core.c" \ + -L"$preferred_lib" -lechoion-dependency \ + -Wl,-l:libstdc++.so.6 \ + -Wl,-soname,Echoion.ts \ + -Wl,-rpath,"$preferred_lib" \ + -o "$resolver_core" +install -m 0644 "$resolver_core" "$bundle/lib/Echoion.ts" +patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts" +cc "$temporary/main.c" -o "$bundle/bin/echoiond" +printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in" +printf '%s\n' 'Echoion' \ + >"$bundle/share/echoion/web/index.html" + +cmake \ + "-DBUNDLE_ROOT=$bundle" \ + "-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core" \ + "-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \ + "-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \ + "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ + -P "$source_root/cmake/BundleRuntimeDependencies.cmake" + +python3 - "$source_root/scripts/validate-release-elf.py" <<'PY' +import importlib.util +from pathlib import Path +import sys + +module_path = Path(sys.argv[1]) +spec = importlib.util.spec_from_file_location("validate_release_elf", module_path) +assert spec is not None and spec.loader is not None +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + +fixture = """ +Version needs section '.gnu.version_r' contains 2 entries: + 000000: Version: 1 File: libm.so.6 Cnt: 1 + 0x0010: Name: GLIBC_9.99 Flags: none Version: 4 + 0x0020: Version: 1 File: libc.so.6 Cnt: 3 + 0x0030: Name: GLIBC_2.17 Flags: none Version: 3 + 0x0040: Name: GLIBC_2.36 Flags: none Version: 2 + 0x0050: Name: GLIBC_ABI_DT_RELR Flags: none Version: 1 +""" +assert module.required_glibc_versions(fixture) == {(2, 17), (2, 36), (9, 99)} +assert module.parse_version("2.35") == (2, 35) +assert module.is_system_dependency("libc.so.6") +assert module.is_system_dependency("libm.so.6") +assert not module.is_system_dependency("libc.so.evil") +assert not module.is_system_dependency("libm.so.99") + +unknown_abi = """ +Version needs section '.gnu.version_r' contains 1 entry: + 000000: Version: 1 File: libc.so.6 Cnt: 1 + 0x0010: Name: GLIBC_ABI_FUTURE Flags: none Version: 1 +""" +try: + module.required_glibc_versions(unknown_abi) +except ValueError as error: + assert "unknown GLIBC ABI requirement" in str(error) +else: + raise AssertionError("unknown GLIBC ABI requirement was accepted") +PY + +evil_bundle="$temporary/evil-bundle" +evil_build="$temporary/evil-build" +cp -a -- "$bundle" "$evil_bundle" +mkdir "$evil_build" +cat >"$temporary/evil-dependency.c" <<'C' +int echoion_evil_dependency(void) { return 13; } +C +cat >"$temporary/evil-user.c" <<'C' +extern int echoion_evil_dependency(void); +int echoion_evil_user(void) { return echoion_evil_dependency(); } +C +cc -fPIC -shared "$temporary/evil-dependency.c" \ + -Wl,-soname,libc.so.evil -o "$evil_build/libc.so.evil" +cc -fPIC -shared "$temporary/evil-user.c" \ + -L"$evil_build" -Wl,-l:libc.so.evil -Wl,-rpath,"$evil_build" \ + -o "$evil_build/libevil-user.so" +rm "$evil_build/libc.so.evil" +if cmake \ + "-DBUNDLE_ROOT=$evil_bundle" \ + "-DBUNDLE_RESOLVER_LIBRARIES=$evil_build/libevil-user.so" \ + "-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \ + "-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \ + "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ + -P "$source_root/cmake/BundleRuntimeDependencies.cmake" \ + >/dev/null 2>&1; then + echo "fake glibc-like SONAME was treated as a system dependency" >&2 + exit 1 +fi + +report="$temporary/dependencies.txt" +python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" --max-glibc 2.35 --report "$report" +grep -F $'NEEDED\tlib/Echoion.ts\tlibechoion-dependency.so.1\tbundled' "$report" +grep -F $'NEEDED\tbin/echoiond\tlibc.so.6\tsystem' "$report" +[[ -L $bundle/lib/libechoion-dependency.so.1 ]] +[[ $(readlink "$bundle/lib/libechoion-dependency.so.1") != /* ]] +[[ -f $bundle/lib/libechoion-dependency.so.1.2.3 ]] +readelf -p .echoion_variant \ + "$bundle/lib/libechoion-dependency.so.1.2.3" | grep -F preferred-runtime +if readelf -p .echoion_variant \ + "$bundle/lib/libechoion-dependency.so.1.2.3" | grep -Fq other-runtime; then + echo "search-directory runtime replaced the exact build resolver runtime" >&2 + exit 1 +fi +readelf -p .echoion_compiler_variant \ + "$bundle/lib/libstdc++.so.6.0.100" | grep -F seeded-compiler-runtime +if find "$bundle/lib" -maxdepth 1 -name 'libstdc++.so.6.0.200' | grep -q .; then + echo "resolver compiler runtime leaked beside the exact seed" >&2 + exit 1 +fi +if find "$bundle/lib" -maxdepth 1 -name 'libc.so*' | grep -q .; then + echo "glibc was unexpectedly bundled" >&2 + exit 1 +fi + +patchelf --set-rpath /tmp/unsafe-build-path "$bundle/lib/Echoion.ts" +if python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" >/dev/null 2>&1; then + echo "absolute Core RUNPATH unexpectedly passed validation" >&2 + exit 1 +fi + +patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts" +python3 - "$bundle/lib/Echoion.ts" <<'PY' +import sys + +with open(sys.argv[1], "r+b") as stream: + stream.seek(18) + stream.write(b"\xb7\x00") # EM_AARCH64 in a little-endian ELF header. +PY +if python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" >/dev/null 2>&1; then + echo "non-x86-64 Core unexpectedly passed validation" >&2 + exit 1 +fi + +echo "runtime dependency bundling regressions passed" diff --git a/scripts/validate-release-elf.py b/scripts/validate-release-elf.py new file mode 100755 index 0000000..818dcad --- /dev/null +++ b/scripts/validate-release-elf.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +"""Validate a relocatable Linux ELF closure without executing its binaries.""" + +from __future__ import annotations + +import argparse +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import subprocess +import tempfile + + +SYSTEM_DEPENDENCIES = tuple( + re.compile(pattern) + for pattern in ( + r"^linux-vdso\.so\.1$", + r"^ld-linux-x86-64\.so\.2$", + r"^libc\.so\.6$", + r"^libm\.so\.6$", + r"^libmvec\.so\.1$", + r"^libdl\.so\.2$", + r"^libpthread\.so\.0$", + r"^librt\.so\.1$", + r"^libresolv\.so\.2$", + r"^libutil\.so\.1$", + r"^libanl\.so\.1$", + r"^libBrokenLocale\.so\.1$", + r"^libthread_db\.so\.1$", + ) +) +NEEDED_PATTERN = re.compile(r"\(NEEDED\).*Shared library: \[([^]]+)]") +RUNPATH_PATTERN = re.compile(r"\((?:RPATH|RUNPATH)\).*Library r(?:un)?path: \[([^]]*)]") +INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]") +GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b") +GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$") +GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)} + + +def parse_version(value: str) -> tuple[int, ...]: + if not re.fullmatch(r"\d+(?:\.\d+){1,2}", value): + raise ValueError(f"invalid ABI version: {value!r}") + return tuple(int(component) for component in value.split(".")) + + +def required_glibc_versions(version_info: str) -> set[tuple[int, ...]]: + versions: set[tuple[int, ...]] = set() + in_needs = False + for line in version_info.splitlines(): + if line.startswith("Version needs section"): + in_needs = True + continue + if in_needs and line.startswith("Version "): + break + if not in_needs: + continue + name_match = GLIBC_NAME_PATTERN.search(line) + if name_match is None: + continue + name = name_match.group(1) + if name in GLIBC_ABI_MINIMUMS: + versions.add(GLIBC_ABI_MINIMUMS[name]) + elif name.startswith("GLIBC_ABI_"): + raise ValueError(f"unknown GLIBC ABI requirement: {name}") + elif version_match := GLIBC_VERSION_PATTERN.fullmatch(name): + versions.add( + tuple( + int(component) + for component in version_match.groups() + if component is not None + ) + ) + return versions + + +def command_output(arguments: list[str]) -> str: + environment = os.environ.copy() + environment["LC_ALL"] = "C" + completed = subprocess.run( + arguments, + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=environment, + ) + if completed.returncode != 0: + message = completed.stderr.strip() or completed.stdout.strip() + raise ValueError(f"{' '.join(arguments)} failed: {message}") + return completed.stdout + + +def is_elf(path: Path) -> bool: + with path.open("rb") as stream: + return stream.read(4) == b"\x7fELF" + + +def is_system_dependency(name: str) -> bool: + return any(pattern.fullmatch(name) for pattern in SYSTEM_DEPENDENCIES) + + +def ensure_inside(path: Path, directory: Path, description: str) -> None: + try: + path.resolve(strict=True).relative_to(directory) + except (FileNotFoundError, RuntimeError, ValueError) as error: + raise ValueError(f"{description} escapes the bundle or is dangling: {path}") from error + + +def validate_symlinks(library_dir: Path) -> None: + for path in sorted(library_dir.iterdir()): + if not path.is_symlink(): + continue + target = os.readlink(path) + pure_target = PurePosixPath(target) + if not target or pure_target.is_absolute() or ".." in pure_target.parts: + raise ValueError(f"unsafe library symlink: {path.name} -> {target}") + ensure_inside(path, library_dir, "library symlink") + + +def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]: + executable = root / "bin/echoiond" + core = root / "lib/Echoion.ts" + library_dir = (root / "lib").resolve(strict=True) + for required in (executable, core): + if not required.is_file() or required.is_symlink() or not is_elf(required): + raise ValueError(f"missing regular ELF payload: {required}") + + validate_symlinks(library_dir) + elf_files: list[Path] = [executable] + for path in sorted(library_dir.iterdir()): + if path.is_symlink(): + continue + if not path.is_file() or not is_elf(path): + raise ValueError(f"unexpected non-ELF entry in lib/: {path}") + elf_files.append(path) + + report: list[str] = [] + for path in elf_files: + relative = path.relative_to(root).as_posix() + header = command_output(["readelf", "-hW", os.fspath(path)]) + if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE): + raise ValueError(f"{relative} is not a 64-bit ELF") + if not re.search( + r"^\s*Machine:\s+Advanced Micro Devices X86-64\s*$", + header, + re.MULTILINE, + ): + raise ValueError(f"{relative} is not an x86-64 ELF") + dynamic = command_output(["readelf", "-dW", os.fspath(path)]) + runpaths = RUNPATH_PATTERN.findall(dynamic) + expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN" + if runpaths != [expected_runpath]: + raise ValueError( + f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}" + ) + report.append(f"ELF\t{relative}\tRUNPATH={expected_runpath}") + + for needed in NEEDED_PATTERN.findall(dynamic): + if "/" in needed or needed in ("", ".", ".."): + raise ValueError(f"unsafe DT_NEEDED entry in {relative}: {needed!r}") + if is_system_dependency(needed): + location = "system" + else: + dependency = library_dir / needed + if not dependency.exists(): + raise ValueError(f"unresolved DT_NEEDED in {relative}: {needed}") + ensure_inside(dependency, library_dir, "DT_NEEDED dependency") + location = "bundled" + report.append(f"NEEDED\t{relative}\t{needed}\t{location}") + + version_info = command_output( + ["readelf", "--version-info", "-W", os.fspath(path)] + ) + glibc_versions = required_glibc_versions(version_info) + if maximum_glibc is not None: + incompatible = sorted( + version for version in glibc_versions if version > maximum_glibc + ) + if incompatible: + rendered = ", ".join( + ".".join(map(str, version)) for version in incompatible + ) + maximum = ".".join(map(str, maximum_glibc)) + raise ValueError( + f"{relative} requires GLIBC newer than {maximum}: {rendered}" + ) + if glibc_versions: + newest = ".".join(map(str, max(glibc_versions))) + report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}") + + program_headers = command_output(["readelf", "-lW", os.fspath(executable)]) + interpreter_match = INTERPRETER_PATTERN.search(program_headers) + if interpreter_match is None: + raise ValueError("echoiond has no ELF interpreter") + interpreter = interpreter_match.group(1) + if not re.fullmatch( + r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)", + interpreter, + ): + raise ValueError(f"unexpected ELF interpreter: {interpreter}") + report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem") + return sorted(report) + + +def write_report(lines: list[str], output: Path) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{output.name}.", dir=output.parent + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + stream.write("# Echoion runtime dependency report\n") + stream.write("# Generated with readelf; no payload executable was run.\n") + for line in lines: + stream.write(f"{line}\n") + os.chmod(temporary_name, 0o644) + os.replace(temporary_name, output) + except BaseException: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass + raise + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--report", type=Path) + parser.add_argument("--max-glibc", type=parse_version) + arguments = parser.parse_args() + + if shutil.which("readelf") is None: + parser.error("readelf is required") + try: + root = arguments.root.resolve(strict=True) + report = validate(root, arguments.max_glibc) + except (OSError, ValueError) as error: + parser.error(str(error)) + if arguments.report: + write_report(report, arguments.report) + else: + print("\n".join(report)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/systemd/README.md b/systemd/README.md index 14c22e1..7bd2951 100644 --- a/systemd/README.md +++ b/systemd/README.md @@ -1,43 +1,11 @@ -# Echoion Standalone systemd service +# Echoion systemd compatibility note -Echoion is deployed as the `echoiond` standalone daemon. The legacy TeamSpeak -client plugin and its graphical/headless TeamSpeak client services are no -longer supported. +Service installation is owned by `packaging/install.sh`; the rendered source +template is `packaging/service/echoion.service.in`. The installer understands +system, user, and portable prefixes, escapes paths correctly, records the unit +hash for safe upgrades/removal, and leaves the service disabled and stopped +unless `--start` is supplied. -## Install - -Build and install Echoion, then copy the user service: - -```bash -mkdir -p ~/.config/systemd/user -cp systemd/echoion-standalone.service ~/.config/systemd/user/ -systemctl --user daemon-reload -systemctl --user enable --now echoion-standalone.service -``` - -For a service that starts before interactive login, enable lingering for the -service account: - -```bash -sudo loginctl enable-linger "$USER" -``` - -The service expects the installed `echoiond` executable, configuration, and -release manifest paths documented in `echoion-standalone.service`. Override -them without editing the tracked unit: - -```bash -systemctl --user edit echoion-standalone.service -``` - -## Operations - -```bash -systemctl --user status echoion-standalone.service -journalctl --user -u echoion-standalone.service -f -systemctl --user restart echoion-standalone.service -``` - -TeamSpeak protocol, query transport, identity, and typed administration are -provided by VoidTeamspeak. EchoionStandalone only adapts those APIs to the -Echoion core contracts. +See the root README installation section for current commands. The old manual +unit and two-file release manifest were removed because they could not describe +the relocatable whole-payload release safely. diff --git a/systemd/echoion-standalone.service b/systemd/echoion-standalone.service deleted file mode 100644 index cb82480..0000000 --- a/systemd/echoion-standalone.service +++ /dev/null @@ -1,35 +0,0 @@ -# Echoion standalone daemon. TeamSpeak transport and protocol behavior are -# provided by VoidTeamspeak; this process hosts the Echoion adapter and core. -# -# Install: copy `echoiond` and `Echoion.ts` (the Core library) somewhere on -# disk, put config.json in ~/.config/echoion/ (or pass --config), then: -# systemctl --user enable --now echoion-standalone -# -# Identity is generated on first run and persisted to -# ~/.config/echoion/identity.txt (override with ECHOION_IDENTITY_PATH). -# Import an existing TeamSpeak-exported identity before enabling the service: -# echoiond --import-identity identity.ini - -[Unit] -Description=Echoion Music Bot (standalone TeamSpeak client) -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple -# Directory holding echoiond and the Core library Echoion.ts. -WorkingDirectory=%h/echoion -Environment=ECHOION_CORE_PATH=%h/echoion/Echoion.ts -# Atomically replace this manifest after staging and hashing a complete release. -Environment=ECHOION_RELEASE_MANIFEST=%h/echoion/releases/pending-release.json -# Optional tuning: -# Environment=ECHOION_SECURITY_LEVEL=8 -# Environment=ECHOION_OPUS_BITRATE=96000 -# Environment=ECHOION_IDENTITY_PATH=%h/.config/echoion/identity.txt -ExecStart=%h/echoion/echoiond --config %h/.config/echoion/config.json -Restart=always -RestartSec=5 -LimitNOFILE=65536 - -[Install] -WantedBy=default.target diff --git a/systemd/release-manifest.example.json b/systemd/release-manifest.example.json deleted file mode 100644 index a37434c..0000000 --- a/systemd/release-manifest.example.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": "1.1.0", - "executable": "1.1.0/echoiond", - "core": "1.1.0/Echoion.ts", - "sha256": { - "executable": "replace-with-lowercase-sha256", - "core": "replace-with-lowercase-sha256" - } -}