diff --git a/.gitignore b/.gitignore index e2a12fb..5d0a6aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *build* .cache .idea -AGENTS.md \ No newline at end of file +AGENTS.md +__pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a15d23..3a58149 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,6 +10,7 @@ set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) find_package(Threads REQUIRED) +find_package(Boost 1.87 CONFIG REQUIRED) # ===== Granular API Libraries ===== # Directory structure: @@ -81,6 +82,31 @@ target_link_libraries(EchoionApiPlugin INTERFACE Void::Plugin ) +# Shared first-party plugin configuration and URL-host safety helpers. Their +# implementation remains in the SDK so independently built plugins do not +# duplicate or diverge from the same validation rules. +add_library(EchoionApiPluginSdk STATIC + src/ShortUrlSupport.cpp +) +add_library(Echoion::ApiPluginSdk ALIAS EchoionApiPluginSdk) +set_target_properties(EchoionApiPluginSdk PROPERTIES + EXPORT_NAME ApiPluginSdk + POSITION_INDEPENDENT_CODE ON +) +target_compile_features(EchoionApiPluginSdk PUBLIC cxx_std_26) +target_include_directories(EchoionApiPluginSdk PUBLIC + $ + $ +) +target_link_libraries(EchoionApiPluginSdk + PUBLIC + Echoion::ApiPlugin + Void::Data + Void::Net + Void::Text +) +target_include_directories(EchoionApiPluginSdk PRIVATE ${Boost_INCLUDE_DIRS}) + # Echoion's discovery symbol and SDK aliases for VoidLibrary's reusable C++ # module descriptor, lifecycle, SemVer, JSON, Result, and service types. add_library(EchoionApiModuleAbi INTERFACE) @@ -241,6 +267,7 @@ target_include_directories(EchoionApi INTERFACE ) target_link_libraries(EchoionApi INTERFACE Echoion::ApiModuleAbi + Echoion::ApiPluginSdk Echoion::ApiBase Echoion::ApiAudio Echoion::ApiTrack @@ -268,6 +295,7 @@ endif() # Install and export all modules install(TARGETS EchoionApiModuleAbi + EchoionApiPluginSdk EchoionApiBase EchoionApiAudio EchoionApiTrack diff --git a/include/echoion/api/plugin/ShortUrlSupport.hpp b/include/echoion/api/plugin/ShortUrlSupport.hpp new file mode 100644 index 0000000..18c3bc4 --- /dev/null +++ b/include/echoion/api/plugin/ShortUrlSupport.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Api::Plugin::ShortUrl +{ + template using Result = std::expected; + + [[nodiscard]] Result + parseConfigObject(const char* config); + [[nodiscard]] Result + requireString(const Void::Json::Value& object, std::string_view key); + [[nodiscard]] Result + optionalString(const Void::Json::Value& object, std::string_view key, + std::string_view fallback = {}); + [[nodiscard]] Result optionalBool(const Void::Json::Value& object, + std::string_view key, + bool fallback); + [[nodiscard]] Result + optionalInteger(const Void::Json::Value& object, std::string_view key, + std::int64_t fallback, std::int64_t minimum, + std::int64_t maximum); + + [[nodiscard]] bool + containsControlCharacters(std::string_view value) noexcept; + [[nodiscard]] std::string trimAscii(std::string_view value); + [[nodiscard]] bool isHeaderName(std::string_view value) noexcept; + [[nodiscard]] bool isBase62(std::string_view value) noexcept; + + /// Validate an absolute HTTP(S) URL without making a network request. + [[nodiscard]] Result + validateHttpUrl(std::string_view value, bool requireHttps, + std::size_t maximumLength = 8192); + + /// Reject address literals and well-known hostnames that are not publicly + /// routable. DNS-backed validation lives in the external provider because + /// only it opens outbound connections. + [[nodiscard]] bool isObviouslyPrivateHost(std::string_view host) noexcept; + + /// Expand ${url} and ${env:NAME}. Environment variables are read without + /// being copied into diagnostics; a missing variable reports only its name. + [[nodiscard]] Result + expandTemplate(std::string_view input, std::string_view url, + bool encodeSubstitutions = false); + +} // namespace Echoion::Api::Plugin::ShortUrl diff --git a/src/ShortUrlSupport.cpp b/src/ShortUrlSupport.cpp new file mode 100644 index 0000000..d2af9c0 --- /dev/null +++ b/src/ShortUrlSupport.cpp @@ -0,0 +1,319 @@ +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api::Plugin::ShortUrl +{ + namespace + { + [[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept + { + if (name.empty() || + !(std::isalpha(static_cast(name.front())) != 0 || + name.front() == '_')) { + return false; + } + return std::ranges::all_of( + name.substr(1), [](const char character) { + const auto value = static_cast(character); + return std::isalnum(value) != 0 || character == '_'; + }); + } + + [[nodiscard]] bool + isPrivateV4(const boost::asio::ip::address_v4 address) noexcept + { + const auto value = address.to_uint(); + const auto first = static_cast((value >> 24U) & 0xffU); + const auto second = static_cast((value >> 16U) & 0xffU); + const auto third = static_cast((value >> 8U) & 0xffU); + + return first == 0U || first == 10U || first == 127U || + (first == 100U && second >= 64U && second <= 127U) || + (first == 169U && second == 254U) || + (first == 172U && second >= 16U && second <= 31U) || + (first == 192U && second == 168U) || + (first == 192U && second == 0U && third <= 2U) || + (first == 198U && (second == 18U || second == 19U)) || + (first == 198U && second == 51U && third == 100U) || + (first == 203U && second == 0U && third == 113U) || + first >= 224U; + } + + [[nodiscard]] bool + isPrivateV6(const boost::asio::ip::address_v6 address) noexcept + { + const auto bytes = address.to_bytes(); + if (address.is_unspecified() || address.is_loopback() || + address.is_link_local() || address.is_multicast()) { + return true; + } + if (address.is_v4_mapped()) { + const boost::asio::ip::address_v4::bytes_type mapped{ + bytes[12], bytes[13], bytes[14], bytes[15]}; + return isPrivateV4(boost::asio::ip::address_v4{mapped}); + } + + const bool uniqueLocal = (bytes[0] & 0xfeU) == 0xfcU; + const bool documentation = bytes[0] == 0x20U && bytes[1] == 0x01U && + bytes[2] == 0x0dU && bytes[3] == 0xb8U; + return uniqueLocal || documentation; + } + } // namespace + + Result parseConfigObject(const char* config) + { + if (config == nullptr || *config == '\0') { + return std::unexpected{"plugin configuration is required"}; + } + auto parsed = Void::Json::parse(config); + if (!parsed) { + return std::unexpected{ + std::format("invalid plugin configuration at {}:{}: {}", + parsed.error().line, parsed.error().col, + parsed.error().message)}; + } + if (!parsed->is_object()) { + return std::unexpected{ + "plugin configuration must be a JSON object"}; + } + return std::move(*parsed); + } + + Result requireString(const Void::Json::Value& object, + const std::string_view key) + { + const auto* value = object.find(key); + if (value == nullptr || !value->is_string() || + value->as_string().empty()) { + return std::unexpected{std::format( + "configuration field '{}' must be a non-empty string", key)}; + } + return value->as_string(); + } + + Result optionalString(const Void::Json::Value& object, + const std::string_view key, + const std::string_view fallback) + { + const auto* value = object.find(key); + if (value == nullptr) { + return std::string{fallback}; + } + if (!value->is_string()) { + return std::unexpected{ + std::format("configuration field '{}' must be a string", key)}; + } + return value->as_string(); + } + + Result optionalBool(const Void::Json::Value& object, + const std::string_view key, const bool fallback) + { + const auto* value = object.find(key); + if (value == nullptr) { + return fallback; + } + if (!value->is_bool()) { + return std::unexpected{ + std::format("configuration field '{}' must be a boolean", key)}; + } + return value->as_bool(); + } + + Result optionalInteger(const Void::Json::Value& object, + const std::string_view key, + const std::int64_t fallback, + const std::int64_t minimum, + const std::int64_t maximum) + { + const auto* value = object.find(key); + if (value == nullptr) { + return fallback; + } + if (!value->is_number()) { + return std::unexpected{std::format( + "configuration field '{}' must be an integer", key)}; + } + const auto number = value->as_number(); + if (!std::isfinite(number) || std::floor(number) != number || + number < static_cast(minimum) || + number > static_cast(maximum)) { + return std::unexpected{std::format( + "configuration field '{}' must be between {} and {}", key, + minimum, maximum)}; + } + return static_cast(number); + } + + bool containsControlCharacters(const std::string_view value) noexcept + { + return std::ranges::any_of(value, [](const char character) { + const auto byte = static_cast(character); + return byte < 0x20U || byte == 0x7fU; + }); + } + + std::string trimAscii(const std::string_view value) + { + const auto isSpace = [](const char character) { + return std::isspace(static_cast(character)) != 0; + }; + const auto first = std::ranges::find_if_not(value, isSpace); + const auto last = + std::find_if_not(value.rbegin(), value.rend(), isSpace).base(); + if (first >= last) { + return {}; + } + return {first, last}; + } + + bool isHeaderName(const std::string_view value) noexcept + { + if (value.empty()) { + return false; + } + constexpr std::string_view separators{"()<>@,;:\\\"/[]?={} \t"}; + return std::ranges::all_of(value, [separators](const char character) { + const auto byte = static_cast(character); + return byte > 0x20U && byte < 0x7fU && + separators.find(character) == std::string_view::npos; + }); + } + + bool isBase62(const std::string_view value) noexcept + { + return !value.empty() && std::ranges::all_of(value, [](const char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z'); + }); + } + + Result validateHttpUrl(const std::string_view value, + const bool requireHttps, + const std::size_t maximumLength) + { + if (value.empty() || value.size() > maximumLength || + containsControlCharacters(value) || + std::ranges::any_of(value, [](const char c) { + return std::isspace(static_cast(c)) != 0; + })) { + return std::unexpected{ + "URL is empty, too long, or contains whitespace"}; + } + const auto parsed = Void::Net::Url::parse(value); + if (!parsed || parsed->host.empty() || + (parsed->scheme != "http" && parsed->scheme != "https")) { + return std::unexpected{"URL must be an absolute HTTP(S) URL"}; + } + if (requireHttps && parsed->scheme != "https") { + return std::unexpected{"URL must use HTTPS"}; + } + + const auto schemeEnd = value.find("://"); + const auto authorityEnd = value.find_first_of("/?#", schemeEnd + 3U); + const auto authority = + value.substr(schemeEnd + 3U, authorityEnd == std::string_view::npos + ? std::string_view::npos + : authorityEnd - schemeEnd - 3U); + if (authority.find('@') != std::string_view::npos) { + return std::unexpected{"URL userinfo is not allowed"}; + } + return {}; + } + + bool isObviouslyPrivateHost(const std::string_view host) noexcept + { + std::string lower; + lower.reserve(host.size()); + std::ranges::transform( + host, std::back_inserter(lower), [](const char c) { + return static_cast( + std::tolower(static_cast(c))); + }); + while (!lower.empty() && lower.back() == '.') { + lower.pop_back(); + } + if (lower == "localhost" || lower.ends_with(".localhost") || + lower.ends_with(".local") || lower.ends_with(".internal")) { + return true; + } + + boost::system::error_code error; + const auto address = boost::asio::ip::make_address(lower, error); + if (error) { + return false; + } + return address.is_v4() ? isPrivateV4(address.to_v4()) + : isPrivateV6(address.to_v6()); + } + + Result expandTemplate(const std::string_view input, + const std::string_view url, + const bool encodeSubstitutions) + { + const auto appendReplacement = + [encodeSubstitutions](std::string& destination, + const std::string_view replacement) { + if (encodeSubstitutions) { + destination.append( + Void::Encoding::Url::query_encode(replacement)); + } else { + destination.append(replacement); + } + }; + std::string output; + output.reserve(input.size() + url.size()); + std::size_t position{}; + while (position < input.size()) { + const auto marker = input.find("${", position); + if (marker == std::string_view::npos) { + output.append(input.substr(position)); + break; + } + output.append(input.substr(position, marker - position)); + const auto end = input.find('}', marker + 2U); + if (end == std::string_view::npos) { + return std::unexpected{"unterminated template placeholder"}; + } + const auto token = input.substr(marker + 2U, end - marker - 2U); + if (token == "url") { + appendReplacement(output, url); + } else if (token.starts_with("env:")) { + const auto name = token.substr(4U); + if (!validEnvironmentName(name)) { + return std::unexpected{ + "invalid environment placeholder name"}; + } + const std::string ownedName{name}; + const char* value = std::getenv(ownedName.c_str()); + if (value == nullptr) { + return std::unexpected{std::format( + "required environment variable '{}' is not set", name)}; + } + if (containsControlCharacters(value)) { + return std::unexpected{std::format( + "environment variable '{}' contains control characters", + name)}; + } + appendReplacement(output, value); + } else { + return std::unexpected{std::format( + "unsupported template placeholder '${{{}}}'", token)}; + } + position = end + 1U; + } + return output; + } + +} // namespace Echoion::Api::Plugin::ShortUrl