#include "echoion/standalone/ReleaseManifest.hpp" #include #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()); } 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) { return Api::fail(Api::ErrorCode::UnknownError, "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 && EVP_DigestUpdate(context.get(), buffer.data(), static_cast(count)) != 1) { return Api::fail(Api::ErrorCode::UnknownError, "cannot hash release artifact"); } } std::array digest{}; unsigned int size{}; if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) { return Api::fail(Api::ErrorCode::UnknownError, "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]); } 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) { auto contents = Void::FileSystem::read_file(manifestPath); if (!contents) { 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); } 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()); } const auto* schema = json->find("schemaVersion"); if (!schema) { return loadVersionOne(*json, root); } if (!schema->is_number() || schema->as_number() != 2.0) { return Api::fail(Api::ErrorCode::IncompatibleVersion, "unsupported release manifest schema version"); } return loadVersionTwo(*json, root); } Api::Result ReleaseManifest::validate() const { 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, "cannot resolve release root: " + rootError.message()); } 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 != entry.sha256) { return Api::fail(Api::ErrorCode::IncompatibleVersion, "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