From d002c528f5a96ac9d075985cfc907ad8451990e5 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 25 Jul 2026 23:44:48 +0300 Subject: [PATCH] update Signed-off-by: faumaray --- CMakeLists.txt | 60 + .../plugins/short_url/ExternalShortener.hpp | 97 ++ src/ExternalShortener.cpp | 1042 +++++++++++++++++ src/Plugin.cpp | 143 +++ tests/ExternalShortenerTests.cpp | 168 +++ 5 files changed, 1510 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 include/echoion/plugins/short_url/ExternalShortener.hpp create mode 100644 src/ExternalShortener.cpp create mode 100644 src/Plugin.cpp create mode 100644 tests/ExternalShortenerTests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..4402d9d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,60 @@ +set(_external_sources + "${CMAKE_CURRENT_SOURCE_DIR}/../common/src/Common.cpp" + src/ExternalShortener.cpp) + +add_library(EchoionUrlShortenerExternalPlugin MODULE + ${_external_sources} + src/Plugin.cpp) +target_include_directories(EchoionUrlShortenerExternalPlugin PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") +target_compile_features(EchoionUrlShortenerExternalPlugin PRIVATE cxx_std_26) +target_link_libraries(EchoionUrlShortenerExternalPlugin PRIVATE + Echoion::ApiPlugin + Echoion::ApiConfig + Void::ShortUrl + Void::Data + Void::Net + Void::Text + Boost::url + Threads::Threads) +set_target_properties(EchoionUrlShortenerExternalPlugin PROPERTIES + PREFIX "" + OUTPUT_NAME "url-shortener-external" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + BUILD_RPATH_USE_ORIGIN ON + INSTALL_RPATH "" + INSTALL_RPATH_USE_LINK_PATH FALSE) + +if(MSVC) + target_compile_options(EchoionUrlShortenerExternalPlugin PRIVATE /W4 /WX-) +else() + target_compile_options(EchoionUrlShortenerExternalPlugin PRIVATE + -Wall -Wextra -Wpedantic) +endif() + +install(TARGETS EchoionUrlShortenerExternalPlugin + LIBRARY DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}" + COMPONENT Runtime + RUNTIME DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}" + COMPONENT Runtime) + +if(BUILD_TESTS) + add_executable(echoion_url_shortener_external_tests + ${_external_sources} + tests/ExternalShortenerTests.cpp) + target_include_directories(echoion_url_shortener_external_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") + target_compile_features(echoion_url_shortener_external_tests PRIVATE + cxx_std_26) + target_link_libraries(echoion_url_shortener_external_tests PRIVATE + Void::ShortUrl Void::Data Void::Net Void::Text Boost::url Threads::Threads) + add_test(NAME echoion_url_shortener_external_tests + COMMAND echoion_url_shortener_external_tests) + set_tests_properties(echoion_url_shortener_external_tests PROPERTIES + TIMEOUT 20) +endif() diff --git a/include/echoion/plugins/short_url/ExternalShortener.hpp b/include/echoion/plugins/short_url/ExternalShortener.hpp new file mode 100644 index 0000000..cc0efbb --- /dev/null +++ b/include/echoion/plugins/short_url/ExternalShortener.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + enum class ExternalEncoding { query, json, form }; + enum class ExternalResponseKind { plain, header, jsonPointer }; + + struct ExternalFieldTemplate { + std::string name; + std::string value; + }; + + struct ExternalHeaderTemplate { + std::string name; + std::string value; + bool sensitive{}; + }; + + struct ExternalResponseConfig { + ExternalResponseKind kind{ExternalResponseKind::jsonPointer}; + std::string selector{"/shortUrl"}; + }; + + struct ExternalConfig { + std::string endpoint; + Void::Net::Method method{Void::Net::Method::Post}; + ExternalEncoding encoding{ExternalEncoding::json}; + std::vector fields; + std::vector headers; + ExternalResponseConfig response; + bool allowHttp{}; + bool allowPrivateHosts{}; + bool allowPrivateTargets{}; + bool allowCrossHostRedirects{}; + int maxRedirects{}; + std::uint32_t timeoutSeconds{3}; + std::size_t maximumResponseBytes{64U * 1024U}; + std::size_t cacheCapacity{512}; + std::uint32_t cacheTtlSeconds{3600}; + std::size_t maximumConcurrency{4}; + }; + + [[nodiscard]] std::expected + parseExternalConfig(std::string_view payload); + + class ExternalShortener + { + public: + + [[nodiscard]] static std::expected< + std::unique_ptr, std::string> + create(ExternalConfig config); + + ~ExternalShortener(); + ExternalShortener(const ExternalShortener&) = delete; + ExternalShortener& operator=(const ExternalShortener&) = delete; + + [[nodiscard]] Void::ShortUrl::Health health() const; + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request); + + /// Pure request/extraction seams used by focused tests and provider + /// configuration diagnostics. They never perform network I/O. + [[nodiscard]] std::expected + previewRequest(std::string_view targetUrl) const; + [[nodiscard]] std::expected + previewExtract(const Void::Net::Response& response) const; + + private: + + struct ConstructionToken { + explicit ConstructionToken() = default; + }; + struct Impl; + + public: + + ExternalShortener(ConstructionToken, ExternalConfig config); + + private: + + std::unique_ptr impl_; + }; + +} // namespace Echoion::Plugins::ShortUrl diff --git a/src/ExternalShortener.cpp b/src/ExternalShortener.cpp new file mode 100644 index 0000000..01fc454 --- /dev/null +++ b/src/ExternalShortener.cpp @@ -0,0 +1,1042 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kDefaultUrlField{"url"}; + constexpr std::size_t kMaximumConfiguredFields = 64; + constexpr std::size_t kMaximumConfiguredHeaders = 32; + constexpr std::size_t kHardMaximumResponseBytes = 64U * 1024U; + + [[nodiscard]] std::string lowerAscii(const std::string_view value) + { + std::string result; + result.reserve(value.size()); + std::ranges::transform( + value, std::back_inserter(result), [](const char c) { + return static_cast( + std::tolower(static_cast(c))); + }); + return result; + } + + [[nodiscard]] const Void::Json::Value& + settingsObject(const Void::Json::Value& root) noexcept + { + if (const auto* settings = root.child_object("settings")) { + return *settings; + } + return root; + } + + [[nodiscard]] Result + parseMethod(const std::string_view value) + { + const auto method = lowerAscii(value); + if (method == "get") { + return Void::Net::Method::Get; + } + if (method == "post") { + return Void::Net::Method::Post; + } + if (method == "put") { + return Void::Net::Method::Put; + } + if (method == "patch") { + return Void::Net::Method::Patch; + } + return std::unexpected{"method must be GET, POST, PUT, or PATCH"}; + } + + [[nodiscard]] Result + parseEncoding(const std::string_view value) + { + const auto encoding = lowerAscii(value); + if (encoding == "query") { + return ExternalEncoding::query; + } + if (encoding == "json") { + return ExternalEncoding::json; + } + if (encoding == "form") { + return ExternalEncoding::form; + } + return std::unexpected{"encoding must be query, json, or form"}; + } + + [[nodiscard]] Result + parseResponseKind(const std::string_view value) + { + const auto kind = lowerAscii(value); + if (kind == "plain") { + return ExternalResponseKind::plain; + } + if (kind == "header") { + return ExternalResponseKind::header; + } + if (kind == "json" || kind == "json-pointer") { + return ExternalResponseKind::jsonPointer; + } + return std::unexpected{ + "response type must be plain, header, or json"}; + } + + [[nodiscard]] bool containsEnvironmentPlaceholder( + const std::string_view value) noexcept + { + return value.find("${env:") != std::string_view::npos; + } + + [[nodiscard]] Result> + parseFields(const Void::Json::Value& settings) + { + const auto* fields = settings.find("fields"); + if (fields == nullptr) { + return std::vector{ + {.name = std::string{kDefaultUrlField}, .value = "${url}"}, + }; + } + if (!fields->is_object() || fields->as_object().empty() || + fields->as_object().size() > kMaximumConfiguredFields) { + return std::unexpected{"fields must be a non-empty JSON object " + "with at most 64 entries"}; + } + std::vector result; + result.reserve(fields->as_object().size()); + for (const auto& [name, value] : fields->as_object()) { + if (name.empty() || name.size() > 128 || + containsControlCharacters(name) || !value.is_string()) { + return std::unexpected{"field names must be non-empty and " + "field values must be strings"}; + } + result.push_back({.name = name, .value = value.as_string()}); + } + return result; + } + + [[nodiscard]] bool forbiddenHeader(const std::string_view name) noexcept + { + const auto lower = lowerAscii(name); + return lower == "host" || lower == "content-length" || + lower == "transfer-encoding" || lower == "connection" || + lower == "proxy-connection"; + } + + [[nodiscard]] Result> + parseHeaders(const Void::Json::Value& settings) + { + const auto* headers = settings.find("headers"); + if (headers == nullptr) { + return std::vector{}; + } + if (!headers->is_object() || + headers->as_object().size() > kMaximumConfiguredHeaders) { + return std::unexpected{ + "headers must be a JSON object with at most 32 entries"}; + } + std::vector result; + result.reserve(headers->as_object().size()); + for (const auto& [name, value] : headers->as_object()) { + if (!isHeaderName(name) || forbiddenHeader(name) || + !value.is_string()) { + return std::unexpected{"header names must be valid and may " + "not override framing headers"}; + } + result.push_back({ + .name = name, + .value = value.as_string(), + .sensitive = + containsEnvironmentPlaceholder(value.as_string()) || + lowerAscii(name) == "authorization" || + lowerAscii(name) == "cookie" || + lowerAscii(name) == "proxy-authorization", + }); + } + return result; + } + + [[nodiscard]] Result + parseResponse(const Void::Json::Value& settings) + { + const auto* response = settings.child_object("response"); + if (response == nullptr) { + return ExternalResponseConfig{}; + } + auto type = optionalString(*response, "type", "json"); + if (!type) { + return std::unexpected{std::move(type).error()}; + } + auto kind = parseResponseKind(*type); + if (!kind) { + return std::unexpected{std::move(kind).error()}; + } + + std::string selector; + switch (*kind) { + case ExternalResponseKind::plain: + break; + case ExternalResponseKind::header: + { + auto header = requireString(*response, "header"); + if (!header || !isHeaderName(*header)) { + return std::unexpected{ + header ? "response header name is invalid" + : header.error()}; + } + selector = std::move(*header); + break; + } + case ExternalResponseKind::jsonPointer: + { + auto pointer = + optionalString(*response, "pointer", "/shortUrl"); + if (!pointer || + (!pointer->empty() && !pointer->starts_with('/'))) { + return std::unexpected{ + pointer ? "response JSON pointer must be empty " + "or start with '/'" + : pointer.error()}; + } + selector = std::move(*pointer); + break; + } + } + return ExternalResponseConfig{ + .kind = *kind, + .selector = std::move(selector), + }; + } + + [[nodiscard]] Result validateConfig(const ExternalConfig& config) + { + const auto dummyUrl = "https://example.com/media?id=1"; + auto endpoint = expandTemplate(config.endpoint, dummyUrl, true); + if (!endpoint) { + return std::unexpected{std::move(endpoint).error()}; + } + if (auto valid = validateHttpUrl(*endpoint, !config.allowHttp); + !valid) { + return std::unexpected{std::format( + "invalid external endpoint: {}", valid.error())}; + } + const auto parsedEndpoint = Void::Net::Url::parse(*endpoint); + if (!config.allowPrivateHosts && + isObviouslyPrivateHost(parsedEndpoint->host)) { + return std::unexpected{ + "external endpoint resolves to a local or reserved host"}; + } + if (config.method == Void::Net::Method::Get && + config.encoding != ExternalEncoding::query) { + return std::unexpected{"GET requests require query encoding"}; + } + if (config.fields.empty() || + config.fields.size() > kMaximumConfiguredFields) { + return std::unexpected{ + "at least one request field is required"}; + } + + bool usesUrl = config.endpoint.find("${url}") != std::string::npos; + for (const auto& field : config.fields) { + usesUrl = + usesUrl || field.value.find("${url}") != std::string::npos; + if (auto expanded = expandTemplate(field.value, dummyUrl); + !expanded) { + return std::unexpected{std::move(expanded).error()}; + } + } + for (const auto& header : config.headers) { + usesUrl = + usesUrl || header.value.find("${url}") != std::string::npos; + auto expanded = expandTemplate(header.value, dummyUrl); + if (!expanded) { + return std::unexpected{std::move(expanded).error()}; + } + if (containsControlCharacters(*expanded)) { + return std::unexpected{ + "expanded header contains control characters"}; + } + } + if (!usesUrl) { + return std::unexpected{"request templates must contain ${url}"}; + } + if (config.maximumResponseBytes == 0 || + config.maximumResponseBytes > kHardMaximumResponseBytes) { + return std::unexpected{ + "maximumResponseBytes must be between 1 and 65536"}; + } + if (config.timeoutSeconds == 0 || config.timeoutSeconds > 30) { + return std::unexpected{ + "timeoutSeconds must be between 1 and 30"}; + } + if (config.maxRedirects < 0 || config.maxRedirects > 5) { + return std::unexpected{"maxRedirects must be between 0 and 5"}; + } + if (config.cacheCapacity > 4096 || config.cacheTtlSeconds > 86400) { + return std::unexpected{ + "cache bounds exceed the supported maximum"}; + } + if (config.maximumConcurrency == 0 || + config.maximumConcurrency > 32) { + return std::unexpected{ + "maximumConcurrency must be between 1 and 32"}; + } + return {}; + } + + [[nodiscard]] std::string + appendQuery(std::string endpoint, + const std::vector& fields, + const std::string_view targetUrl) + { + char separator = + endpoint.find('?') == std::string::npos ? '?' : '&'; + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return {}; + } + endpoint += separator; + separator = '&'; + endpoint += Void::Encoding::Url::query_encode(field.name); + endpoint += '='; + endpoint += Void::Encoding::Url::query_encode(*value); + } + return endpoint; + } + + [[nodiscard]] std::string contentType(const ExternalEncoding encoding) + { + switch (encoding) { + case ExternalEncoding::query: + return {}; + case ExternalEncoding::json: + return "application/json"; + case ExternalEncoding::form: + return "application/x-www-form-urlencoded"; + } + return {}; + } + + [[nodiscard]] Result + buildBody(const ExternalEncoding encoding, + const std::vector& fields, + const std::string_view targetUrl) + { + if (encoding == ExternalEncoding::query) { + return std::string{}; + } + if (encoding == ExternalEncoding::json) { + Void::Json::Value::Object_t object; + object.reserve(fields.size()); + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + object.emplace_back(field.name, std::move(*value)); + } + return Void::Json::serialize( + Void::Json::object(std::move(object))); + } + + std::string body; + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + if (!body.empty()) { + body += '&'; + } + body += Void::Encoding::Url::query_encode(field.name); + body += '='; + body += Void::Encoding::Url::query_encode(*value); + } + return body; + } + + [[nodiscard]] Result + buildRequest(const ExternalConfig& config, + const std::string_view targetUrl) + { + if (auto valid = validateHttpUrl(targetUrl, false); !valid) { + return std::unexpected{ + std::format("invalid target URL: {}", valid.error())}; + } + const auto target = Void::Net::Url::parse(targetUrl); + if (!config.allowPrivateTargets && + isObviouslyPrivateHost(target->host)) { + return std::unexpected{ + "target URL uses a local or reserved host"}; + } + + auto endpoint = expandTemplate(config.endpoint, targetUrl, true); + if (!endpoint) { + return std::unexpected{std::move(endpoint).error()}; + } + if (config.encoding == ExternalEncoding::query) { + *endpoint = + appendQuery(std::move(*endpoint), config.fields, targetUrl); + if (endpoint->empty()) { + return std::unexpected{"could not expand query fields"}; + } + } + + Void::Net::Request request{ + .method = config.method, + .url = std::move(*endpoint), + .timeout = std::chrono::seconds{config.timeoutSeconds}, + }; + for (const auto& header : config.headers) { + auto value = expandTemplate(header.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + if (containsControlCharacters(*value)) { + return std::unexpected{ + "expanded header contains control characters"}; + } + request.headers.push_back( + {.name = header.name, .value = std::move(*value)}); + } + + if (config.encoding != ExternalEncoding::query) { + auto body = + buildBody(config.encoding, config.fields, targetUrl); + if (!body) { + return std::unexpected{std::move(body).error()}; + } + request.body = std::move(*body); + const bool hasContentType = std::ranges::any_of( + request.headers, [](const auto& header) { + return lowerAscii(header.name) == "content-type"; + }); + if (!hasContentType) { + request.headers.push_back({ + .name = "Content-Type", + .value = contentType(config.encoding), + }); + } + } + return request; + } + + [[nodiscard]] Result + extractResponse(const ExternalResponseConfig& config, + const Void::Net::Response& response) + { + std::string value; + switch (config.kind) { + case ExternalResponseKind::plain: + value = trimAscii(response.body); + break; + case ExternalResponseKind::header: + { + const auto header = response.header(config.selector); + if (!header) { + return std::unexpected{ + "configured response header is missing"}; + } + value = trimAscii(*header); + break; + } + case ExternalResponseKind::jsonPointer: + { + auto document = Void::Json::parse(response.body); + if (!document) { + return std::unexpected{ + "provider returned malformed JSON"}; + } + const auto* selected = document->at(config.selector); + if (selected == nullptr || !selected->is_string()) { + return std::unexpected{"configured JSON pointer " + "does not select a string"}; + } + value = trimAscii(selected->as_string()); + break; + } + } + if (value.empty() || containsControlCharacters(value)) { + return std::unexpected{ + "provider returned an empty or unsafe short URL"}; + } + return value; + } + + [[nodiscard]] Result + validateOutboundUrl(const std::string_view url, + const ExternalConfig& config) + { + if (auto valid = validateHttpUrl(url, !config.allowHttp); !valid) { + return valid; + } + if (config.allowPrivateHosts) { + return {}; + } + const auto parsed = Void::Net::Url::parse(url); + if (isObviouslyPrivateHost(parsed->host)) { + return std::unexpected{ + "external endpoint is local or reserved"}; + } + + boost::asio::io_context context; + boost::asio::ip::tcp::resolver resolver{context}; + boost::asio::steady_timer timer{context}; + std::vector addresses; + boost::system::error_code resolutionError; + bool timedOut{}; + + resolver.async_resolve( + parsed->host, parsed->port, + [&](const boost::system::error_code error, + const boost::asio::ip::tcp::resolver::results_type& + results) { + resolutionError = error; + if (!error) { + for (const auto& result : results) { + addresses.push_back(result.endpoint().address()); + } + } + timer.cancel(); + }); + timer.expires_after(std::chrono::seconds{config.timeoutSeconds}); + timer.async_wait([&](const boost::system::error_code error) { + if (!error) { + timedOut = true; + resolver.cancel(); + } + }); + context.run(); + if (timedOut) { + return std::unexpected{ + "external endpoint DNS lookup timed out"}; + } + if (resolutionError || addresses.empty()) { + return std::unexpected{ + "external endpoint host could not be resolved"}; + } + if (std::ranges::any_of(addresses, [](const auto& address) { + return isObviouslyPrivateHost(address.to_string()); + })) { + return std::unexpected{"external endpoint resolves to a local " + "or reserved address"}; + } + return {}; + } + + [[nodiscard]] Result + resolveRedirect(const std::string_view base, + const std::string_view location) + { + if (location.empty() || containsControlCharacters(location)) { + return std::unexpected{"redirect Location is empty or unsafe"}; + } + auto baseUrl = boost::urls::parse_uri(base); + auto reference = boost::urls::parse_uri_reference(location); + if (!baseUrl || !reference) { + return std::unexpected{"redirect Location is malformed"}; + } + boost::urls::url resolved{*baseUrl}; + const auto result = resolved.resolve(*reference); + if (!result) { + return std::unexpected{ + "redirect Location could not be resolved"}; + } + return std::string{resolved.buffer()}; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + serviceError(const Void::ShortUrl::ErrorCode code, + std::string message, + const std::uint32_t retryAfter = 0) + { + return {.error = { + .code = code, + .message = std::move(message), + .retry_after_seconds = retryAfter, + }}; + } + + [[nodiscard]] std::uint32_t + retryAfterSeconds(const Void::Net::Response& response) noexcept + { + const auto value = response.header("retry-after"); + if (!value) { + return 0; + } + std::uint32_t seconds{}; + const auto [end, error] = std::from_chars( + value->data(), value->data() + value->size(), seconds); + return error == std::errc{} && end == value->data() + value->size() + ? seconds + : 0; + } + + [[nodiscard]] std::string keyFromUrl(const std::string_view url) + { + const auto parsed = Void::Net::Url::parse(url); + if (!parsed) { + return {}; + } + const auto position = parsed->path.find_last_of('/'); + if (position == std::string::npos || + position + 1U >= parsed->path.size()) { + return {}; + } + return parsed->path.substr(position + 1U); + } + } // namespace + + std::expected + parseExternalConfig(const std::string_view payload) + { + const std::string ownedPayload{payload}; + auto root = parseConfigObject(ownedPayload.c_str()); + if (!root) { + return std::unexpected{std::move(root).error()}; + } + const auto& settings = settingsObject(*root); + + auto endpoint = requireString(settings, "endpoint"); + auto methodValue = optionalString(settings, "method", "POST"); + auto encodingValue = optionalString(settings, "encoding", "json"); + if (!endpoint || !methodValue || !encodingValue) { + return std::unexpected{!endpoint ? endpoint.error() + : (!methodValue + ? methodValue.error() + : encodingValue.error())}; + } + auto method = parseMethod(*methodValue); + auto encoding = parseEncoding(*encodingValue); + auto fields = parseFields(settings); + auto headers = parseHeaders(settings); + auto response = parseResponse(settings); + if (!method || !encoding || !fields || !headers || !response) { + if (!method) { + return std::unexpected{std::move(method).error()}; + } + if (!encoding) { + return std::unexpected{std::move(encoding).error()}; + } + if (!fields) { + return std::unexpected{std::move(fields).error()}; + } + if (!headers) { + return std::unexpected{std::move(headers).error()}; + } + return std::unexpected{std::move(response).error()}; + } + + auto allowHttp = optionalBool(settings, "allowHttp", false); + auto allowPrivateHosts = + optionalBool(settings, "allowPrivateHosts", false); + auto allowPrivateTargets = + optionalBool(settings, "allowPrivateTargets", false); + auto allowCrossHost = + optionalBool(settings, "allowCrossHostRedirects", false); + auto maxRedirects = optionalInteger(settings, "maxRedirects", 0, 0, 5); + auto timeout = optionalInteger(settings, "timeoutSeconds", 3, 1, 30); + auto maximumBody = optionalInteger(settings, "maximumResponseBytes", + 64 * 1024, 1, 64 * 1024); + auto cacheCapacity = + optionalInteger(settings, "cacheCapacity", 512, 0, 4096); + auto cacheTtl = + optionalInteger(settings, "cacheTtlSeconds", 3600, 0, 86400); + auto concurrency = + optionalInteger(settings, "maximumConcurrency", 4, 1, 32); + if (!allowHttp || !allowPrivateHosts || !allowPrivateTargets || + !allowCrossHost || !maxRedirects || !timeout || !maximumBody || + !cacheCapacity || !cacheTtl || !concurrency) { + return std::unexpected{ + "one or more external shortener limits are invalid"}; + } + + ExternalConfig config{ + .endpoint = std::move(*endpoint), + .method = *method, + .encoding = *encoding, + .fields = std::move(*fields), + .headers = std::move(*headers), + .response = std::move(*response), + .allowHttp = *allowHttp, + .allowPrivateHosts = *allowPrivateHosts, + .allowPrivateTargets = *allowPrivateTargets, + .allowCrossHostRedirects = *allowCrossHost, + .maxRedirects = static_cast(*maxRedirects), + .timeoutSeconds = static_cast(*timeout), + .maximumResponseBytes = static_cast(*maximumBody), + .cacheCapacity = static_cast(*cacheCapacity), + .cacheTtlSeconds = static_cast(*cacheTtl), + .maximumConcurrency = static_cast(*concurrency), + }; + if (auto valid = validateConfig(config); !valid) { + return std::unexpected{std::move(valid).error()}; + } + return config; + } + + struct ExternalShortener::Impl { + struct CacheEntry { + std::string targetUrl; + std::string shortUrl; + std::chrono::steady_clock::time_point expiresAt; + }; + + class Permit + { + public: + + Permit() = default; + explicit Permit(Impl* owner) : owner_(owner) {} + ~Permit() + { + if (owner_ != nullptr) { + owner_->releasePermit(); + } + } + Permit(const Permit&) = delete; + Permit& operator=(const Permit&) = delete; + Permit(Permit&& other) noexcept + : owner_(std::exchange(other.owner_, nullptr)) + { + } + Permit& operator=(Permit&&) = delete; + + private: + + Impl* owner_{}; + }; + + explicit Impl(ExternalConfig source) + : config(std::move(source)), client{}, activeRequests{}, cache{} + { + client.set_verify_tls(true); + client.set_max_body_size(config.maximumResponseBytes); + client.set_max_redirects(0); + client.set_user_agent("Echoion URL Shortener/1.0"); + } + + [[nodiscard]] std::optional acquirePermit( + const std::chrono::steady_clock::time_point deadline) + { + std::unique_lock lock{permitMutex}; + if (!permitCondition.wait_until(lock, deadline, [this] { + return activeRequests < config.maximumConcurrency; + })) { + return std::nullopt; + } + ++activeRequests; + return Permit{this}; + } + + void releasePermit() + { + { + const std::scoped_lock lock{permitMutex}; + --activeRequests; + } + permitCondition.notify_one(); + } + + [[nodiscard]] std::optional + lookupCache(const std::string_view targetUrl) + { + const std::scoped_lock lock{cacheMutex}; + const auto found = cacheIndex.find(std::string{targetUrl}); + if (found == cacheIndex.end()) { + return std::nullopt; + } + if (found->second->expiresAt <= + std::chrono::steady_clock::now()) { + cache.erase(found->second); + cacheIndex.erase(found); + return std::nullopt; + } + cache.splice(cache.begin(), cache, found->second); + return found->second->shortUrl; + } + + void storeCache(std::string targetUrl, std::string shortUrl) + { + if (config.cacheCapacity == 0 || config.cacheTtlSeconds == 0) { + return; + } + const std::scoped_lock lock{cacheMutex}; + if (const auto found = cacheIndex.find(targetUrl); + found != cacheIndex.end()) { + cache.erase(found->second); + cacheIndex.erase(found); + } + cache.push_front({ + .targetUrl = std::move(targetUrl), + .shortUrl = std::move(shortUrl), + .expiresAt = std::chrono::steady_clock::now() + + std::chrono::seconds{config.cacheTtlSeconds}, + }); + cacheIndex[cache.front().targetUrl] = cache.begin(); + while (cache.size() > config.cacheCapacity) { + cacheIndex.erase(cache.back().targetUrl); + cache.pop_back(); + } + } + + ExternalConfig config; + Void::Net::HttpClient client; + std::mutex permitMutex; + std::condition_variable permitCondition; + std::size_t activeRequests; + std::mutex cacheMutex; + std::list cache; + std::unordered_map::iterator> + cacheIndex; + }; + + ExternalShortener::ExternalShortener(ConstructionToken, + ExternalConfig config) + : impl_(std::make_unique(std::move(config))) + { + } + + ExternalShortener::~ExternalShortener() = default; + + std::expected, std::string> + ExternalShortener::create(ExternalConfig config) + { + if (auto valid = validateConfig(config); !valid) { + return std::unexpected{std::move(valid).error()}; + } + return std::make_unique(ConstructionToken{}, + std::move(config)); + } + + Void::ShortUrl::Health ExternalShortener::health() const + { + return { + .status = Void::ShortUrl::HealthStatus::healthy, + .message = "external shortener adapter is configured", + }; + } + + std::expected + ExternalShortener::previewRequest( + const std::string_view targetUrl) const + { + return buildRequest(impl_->config, targetUrl); + } + + std::expected ExternalShortener::previewExtract( + const Void::Net::Response& response) const + { + return extractResponse(impl_->config.response, response); + } + + Void::ShortUrl::ShortenResult ExternalShortener::shorten( + const Void::ShortUrl::ShortenRequest& request) + { + if (!request.custom_key.empty() || + request.expires_at_unix_seconds != 0) { + return serviceError(Void::ShortUrl::ErrorCode::unsupported, + "external provider adapter cannot guarantee " + "custom keys or expiry"); + } + if (auto cached = impl_->lookupCache(request.target_url)) { + return { + .short_url = *cached, + .key = keyFromUrl(*cached), + }; + } + + const auto timeout = std::chrono::seconds{impl_->config.timeoutSeconds}; + const auto startedAt = std::chrono::steady_clock::now(); + auto permit = impl_->acquirePermit(startedAt + timeout); + if (!permit) { + return serviceError(Void::ShortUrl::ErrorCode::rate_limited, + "external shortener concurrency limit is busy", + 1); + } + if (auto cached = impl_->lookupCache(request.target_url)) { + return { + .short_url = *cached, + .key = keyFromUrl(*cached), + }; + } + + auto built = buildRequest(impl_->config, request.target_url); + if (!built) { + return serviceError(Void::ShortUrl::ErrorCode::invalid_url, + std::move(built).error()); + } + Void::Net::Request outbound = std::move(*built); + const std::unordered_set sensitiveHeaders = [&] { + std::unordered_set names; + for (const auto& header : impl_->config.headers) { + if (header.sensitive) { + names.insert(lowerAscii(header.name)); + } + } + return names; + }(); + + for (int redirect{};; ++redirect) { + if (auto valid = validateOutboundUrl(outbound.url, impl_->config); + !valid) { + return serviceError(Void::ShortUrl::ErrorCode::unavailable, + "external provider endpoint is unavailable " + "or not publicly routable"); + } + const auto elapsed = std::chrono::steady_clock::now() - startedAt; + if (elapsed >= timeout) { + return serviceError(Void::ShortUrl::ErrorCode::timeout, + "external provider request timed out"); + } + outbound.timeout = std::chrono::duration_cast( + timeout - elapsed); + if (outbound.timeout <= std::chrono::seconds::zero()) { + outbound.timeout = std::chrono::seconds{1}; + } + + auto response = impl_->client.send(outbound); + if (!response) { + const auto totalElapsed = + std::chrono::steady_clock::now() - startedAt; + const auto code = + totalElapsed >= timeout + ? Void::ShortUrl::ErrorCode::timeout + : Void::ShortUrl::ErrorCode::provider_error; + return serviceError(code, + code == Void::ShortUrl::ErrorCode::timeout + ? "external provider request timed out" + : "external provider request failed"); + } + if (response->body.size() > impl_->config.maximumResponseBytes) { + return serviceError( + Void::ShortUrl::ErrorCode::response_too_large, + "external provider response exceeds 64 KiB"); + } + + if (response->status >= 300 && response->status < 400) { + if (redirect >= impl_->config.maxRedirects) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider redirect limit was reached"); + } + const auto location = response->header("location"); + if (!location) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider redirect omitted Location"); + } + auto redirected = resolveRedirect(outbound.url, *location); + if (!redirected) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + std::move(redirected).error()); + } + const auto before = Void::Net::Url::parse(outbound.url); + const auto after = Void::Net::Url::parse(*redirected); + const bool changesHost = + !after || !before || + lowerAscii(before->host) != lowerAscii(after->host) || + before->port != after->port || + before->scheme != after->scheme; + if (changesHost && !impl_->config.allowCrossHostRedirects) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider attempted a cross-host redirect"); + } + if (changesHost) { + std::erase_if(outbound.headers, [&](const auto& header) { + return sensitiveHeaders.contains( + lowerAscii(header.name)); + }); + } + outbound.url = std::move(*redirected); + if (response->status == 303 || + ((response->status == 301 || response->status == 302) && + outbound.method == Void::Net::Method::Post)) { + outbound.method = Void::Net::Method::Get; + outbound.body.reset(); + std::erase_if(outbound.headers, [](const auto& header) { + return lowerAscii(header.name) == "content-type"; + }); + } + continue; + } + + if (!response->ok()) { + if (response->status == 429) { + return serviceError( + Void::ShortUrl::ErrorCode::rate_limited, + "external provider rate limit was reached", + retryAfterSeconds(*response)); + } + if (response->status == 408 || response->status == 504) { + return serviceError(Void::ShortUrl::ErrorCode::timeout, + "external provider timed out"); + } + const auto code = + response->status >= 500 + ? Void::ShortUrl::ErrorCode::unavailable + : Void::ShortUrl::ErrorCode::provider_error; + return serviceError(code, + "external provider rejected the request"); + } + + auto extracted = extractResponse(impl_->config.response, *response); + if (!extracted) { + return serviceError(Void::ShortUrl::ErrorCode::provider_error, + std::move(extracted).error()); + } + if (auto valid = + validateHttpUrl(*extracted, !impl_->config.allowHttp); + !valid) { + return serviceError( + Void::ShortUrl::ErrorCode::invalid_url, + "external provider returned an invalid short URL"); + } + const auto parsedShort = Void::Net::Url::parse(*extracted); + if (!impl_->config.allowPrivateTargets && + isObviouslyPrivateHost(parsedShort->host)) { + return serviceError( + Void::ShortUrl::ErrorCode::invalid_url, + "external provider returned a local or reserved short URL"); + } + + const auto key = keyFromUrl(*extracted); + impl_->storeCache(request.target_url, *extracted); + return { + .short_url = std::move(*extracted), + .key = key, + }; + } + } + +} // namespace Echoion::Plugins::ShortUrl diff --git a/src/Plugin.cpp b/src/Plugin.cpp new file mode 100644 index 0000000..5cf70e7 --- /dev/null +++ b/src/Plugin.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kPluginId{"url-shortener-external"}; + } + + class ExternalShortenerPlugin final : public Api::IExtensionPlugin, + public Void::ShortUrl::IShortener + { + public: + + [[nodiscard]] std::string_view name() const noexcept override + { + return kPluginId; + } + + [[nodiscard]] std::string_view provider_id() const noexcept override + { + return kPluginId; + } + + void applyConfig(const char* config) + { + configPayload_ = config != nullptr ? config : ""; + } + + void on_load() override + { + shortener_.reset(); + activationError_.clear(); + auto config = parseExternalConfig(configPayload_); + if (!config) { + activationError_ = std::move(config).error(); + return; + } + auto shortener = ExternalShortener::create(std::move(*config)); + if (!shortener) { + activationError_ = std::move(shortener).error(); + return; + } + shortener_ = std::move(*shortener); + } + + void on_unload() override { shortener_.reset(); } + + [[nodiscard]] Void::ShortUrl::Health health() const override + { + if (shortener_ != nullptr) { + return shortener_->health(); + } + return { + .status = Void::ShortUrl::HealthStatus::unhealthy, + .message = activationError_.empty() + ? "plugin is not configured" + : activationError_, + }; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request) override + { + if (shortener_ == nullptr) { + return {.error = { + .code = Void::ShortUrl::ErrorCode::unavailable, + .message = "external shortener is unavailable", + }}; + } + return shortener_->shorten(request); + } + + private: + + std::string configPayload_; + std::string activationError_; + std::unique_ptr shortener_; + }; + +} // namespace Echoion::Plugins::ShortUrl + +extern "C" { + +void* void_plugin_create() +{ + return std::make_unique< + Echoion::Plugins::ShortUrl::ExternalShortenerPlugin>() + .release(); +} + +void void_plugin_destroy(void* instance) +{ + std::unique_ptr{ + static_cast( + instance)}; +} + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "url-shortener-external", + .plugin_version = "1.0.0", + .description = "Configurable external URL-shortening adapter", + }; +} + +void void_plugin_configure(void* instance, const char* config) +{ + static_cast(instance) + ->applyConfig(config); +} + +int void_plugin_ready(void* instance) +{ + const auto health = + static_cast( + instance) + ->health(); + return health.status == Void::ShortUrl::HealthStatus::healthy ? 0 : 1; +} + +Void::Service::IService* void_plugin_service(void* instance) +{ + auto* plugin = + static_cast( + instance); + return static_cast( + static_cast(plugin)); +} + +} // extern "C" diff --git a/tests/ExternalShortenerTests.cpp b/tests/ExternalShortenerTests.cpp new file mode 100644 index 0000000..21e235a --- /dev/null +++ b/tests/ExternalShortenerTests.cpp @@ -0,0 +1,168 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace +{ + class EnvironmentVariable + { + public: + + EnvironmentVariable(std::string name, std::string value) + : name_(std::move(name)) + { + setenv(name_.c_str(), value.c_str(), 1); + } + + ~EnvironmentVariable() { unsetenv(name_.c_str()); } + + EnvironmentVariable(const EnvironmentVariable&) = delete; + EnvironmentVariable& operator=(const EnvironmentVariable&) = delete; + + private: + + std::string name_; + }; +} // namespace + +int main() +{ + using Echoion::Plugins::ShortUrl::ExternalShortener; + using Echoion::Plugins::ShortUrl::parseExternalConfig; + + int failures{}; + const auto check = [&failures](const bool condition, + const std::string_view message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + + EnvironmentVariable token{"ECHOION_SHORTENER_TEST_TOKEN", "test secret"}; + const auto jsonConfig = R"JSON({ + "endpoint":"https://short.example/api", + "method":"POST", + "encoding":"json", + "fields":{"longUrl":"${url}","tenant":"${env:ECHOION_SHORTENER_TEST_TOKEN}"}, + "headers":{"Authorization":"Bearer ${env:ECHOION_SHORTENER_TEST_TOKEN}"}, + "response":{"type":"json","pointer":"/data/short"} + })JSON"; + auto parsed = parseExternalConfig(jsonConfig); + check(parsed.has_value(), "JSON provider configuration was rejected"); + if (!parsed) { + return 1; + } + auto shortener = ExternalShortener::create(std::move(*parsed)); + check(shortener.has_value(), "external shortener could not be created"); + if (!shortener) { + return 1; + } + + auto request = + (*shortener)->previewRequest("https://example.com/a?x=1&y=2"); + check(request.has_value() && request->body.has_value(), + "JSON request was not constructed"); + if (request && request->body) { + auto body = Void::Json::parse(*request->body); + check(body && + body->get_str("longUrl") == "https://example.com/a?x=1&y=2", + "target URL was not safely represented in JSON"); + check(body && body->get_str("tenant") == "test secret", + "environment template was not expanded in a field"); + check(request->headers.size() == 2, + "configured and automatic Content-Type headers were not emitted"); + } + + Void::Net::Response jsonResponse{ + .status = 200, + .body = R"({"data":{"short":"https://sho.rt/Ab1"}})", + }; + auto extracted = (*shortener)->previewExtract(jsonResponse); + check(extracted && *extracted == "https://sho.rt/Ab1", + "JSON Pointer response extraction failed"); + + const auto formConfig = R"JSON({ + "endpoint":"https://short.example/api", + "method":"PATCH", + "encoding":"form", + "fields":{"long url":"${url}"}, + "response":{"type":"plain"} + })JSON"; + auto form = parseExternalConfig(formConfig); + check(form.has_value(), "form provider configuration was rejected"); + if (form) { + auto formShortener = ExternalShortener::create(std::move(*form)); + auto formRequest = + formShortener + ? (*formShortener) + ->previewRequest("https://example.com/a?x=1&y=2") + : std::expected{ + std::unexpected{"create failed"}}; + check(formRequest && + formRequest->body == + "long+url=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26y%3D2", + "form request was not percent encoded"); + } + + const auto queryConfig = R"JSON({ + "endpoint":"https://short.example/api?token=${env:ECHOION_SHORTENER_TEST_TOKEN}", + "method":"GET", + "encoding":"query", + "fields":{"url":"${url}"}, + "response":{"type":"header","header":"Location"} + })JSON"; + auto query = parseExternalConfig(queryConfig); + check(query.has_value(), "query provider configuration was rejected"); + if (query) { + auto queryShortener = ExternalShortener::create(std::move(*query)); + auto queryRequest = + queryShortener + ? (*queryShortener)->previewRequest("https://example.com/a?x=1") + : std::expected{ + std::unexpected{"create failed"}}; + check(queryRequest && + queryRequest->url.find("token=test+secret") != + std::string::npos && + queryRequest->url.find("url=https%3A%2F%2Fexample.com") != + std::string::npos, + "query and environment values were not percent encoded"); + if (queryShortener) { + Void::Net::Response headerResponse{ + .status = 201, + .headers = {{.name = "Location", .value = "https://sho.rt/Q1"}}, + }; + auto header = (*queryShortener)->previewExtract(headerResponse); + check(header && *header == "https://sho.rt/Q1", + "response-header extraction failed"); + } + } + + check(!parseExternalConfig(R"({"endpoint":"http://short.example/api"})"), + "plain HTTP endpoint was accepted without opt-in"); + check( + !parseExternalConfig( + R"({"endpoint":"https://127.0.0.1/api","fields":{"url":"${url}"}})"), + "private endpoint was accepted without opt-in"); + check( + !parseExternalConfig( + R"({"endpoint":"https://short.example/api","headers":{"Authorization":"${env:ECHOION_MISSING_SHORTENER_TOKEN}"}})"), + "missing environment secret did not reject configuration"); + + const Void::ShortUrl::ShortenRequest unsupportedRequest{ + .target_url = "https://example.com/a", + .custom_key = "wanted", + }; + const auto unsupported = (*shortener)->shorten(unsupportedRequest); + check(!unsupported && + unsupported.error.code == Void::ShortUrl::ErrorCode::unsupported, + "external adapter silently ignored a custom key"); + + return failures == 0 ? 0 : 1; +}