From e953c56a30c3cbbc0f33fe0a583a51350c017576 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 00:26:58 -0300 Subject: [PATCH 1/2] feat(http): lift the HTTP module loader's policy into the core Response classification (MIME rules, failure texts, the empty-module rule), the remote-module allowlist, registry-key canonicalization and fetch host classes, moved from both runtimes' HttpLoader with identical behavior and failure texts. The core reaches the runtime through link-time platform functions (ns/Platform.h): logging, trace categories, and the runtime's URL normalization and origin. Host tests link a fake platform. --- CMakeLists.txt | 27 +++- include/ns/Platform.h | 35 +++++ include/ns/http/ModuleFetch.h | 99 +++++++++++++ src/Trace.cpp | 46 ++++++ src/Trace.h | 16 +++ src/http/Canonicalize.cpp | 105 ++++++++++++++ src/http/HostClass.cpp | 52 +++++++ src/http/Internal.h | 29 ++++ src/http/ModuleResponse.cpp | 126 ++++++++++++++++ src/http/RemoteModuleAllowlist.cpp | 65 +++++++++ tests/FakePlatform.cpp | 110 ++++++++++++++ tests/FakePlatform.h | 19 +++ tests/HttpPolicyTest.cpp | 223 +++++++++++++++++++++++++++++ 13 files changed, 946 insertions(+), 6 deletions(-) create mode 100644 include/ns/Platform.h create mode 100644 include/ns/http/ModuleFetch.h create mode 100644 src/Trace.cpp create mode 100644 src/Trace.h create mode 100644 src/http/Canonicalize.cpp create mode 100644 src/http/HostClass.cpp create mode 100644 src/http/Internal.h create mode 100644 src/http/ModuleResponse.cpp create mode 100644 src/http/RemoteModuleAllowlist.cpp create mode 100644 tests/FakePlatform.cpp create mode 100644 tests/FakePlatform.h create mode 100644 tests/HttpPolicyTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 661b9c4..8c5d3de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,6 +26,11 @@ set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES "") set(NS_RUNTIME_COMMON_V8_FREE_SOURCES src/Base64.cpp + src/Trace.cpp + src/http/Canonicalize.cpp + src/http/HostClass.cpp + src/http/ModuleResponse.cpp + src/http/RemoteModuleAllowlist.cpp ) set(NS_RUNTIME_COMMON_V8_SOURCES @@ -61,16 +66,26 @@ else () endif () target_include_directories(ns_runtime_common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_include_directories(ns_runtime_common PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) target_compile_features(ns_runtime_common PRIVATE cxx_std_20) set_target_properties(ns_runtime_common PROPERTIES CXX_EXTENSIONS OFF) target_compile_options(ns_runtime_common PRIVATE ${NS_RUNTIME_COMMON_WARNINGS}) if (NS_RUNTIME_COMMON_HOST_TESTS) enable_testing() - add_executable(ns_runtime_common_tests tests/Base64Test.cpp) - target_link_libraries(ns_runtime_common_tests PRIVATE ns_runtime_common) - target_compile_features(ns_runtime_common_tests PRIVATE cxx_std_20) - set_target_properties(ns_runtime_common_tests PROPERTIES CXX_EXTENSIONS OFF) - target_compile_options(ns_runtime_common_tests PRIVATE ${NS_RUNTIME_COMMON_WARNINGS}) - add_test(NAME ns_runtime_common_tests COMMAND ns_runtime_common_tests) + # The core resolves its platform functions (ns/Platform.h) at the final + # link; tests/FakePlatform.cpp stands in for a runtime's. + set(NS_RUNTIME_COMMON_TESTS + Base64Test + HttpPolicyTest + ) + foreach (test ${NS_RUNTIME_COMMON_TESTS}) + add_executable(${test} tests/${test}.cpp tests/FakePlatform.cpp) + target_link_libraries(${test} PRIVATE ns_runtime_common) + target_include_directories(${test} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_features(${test} PRIVATE cxx_std_20) + set_target_properties(${test} PROPERTIES CXX_EXTENSIONS OFF) + target_compile_options(${test} PRIVATE ${NS_RUNTIME_COMMON_WARNINGS}) + add_test(NAME ${test} COMMAND ${test}) + endforeach () endif () diff --git a/include/ns/Platform.h b/include/ns/Platform.h new file mode 100644 index 0000000..b6c7dc4 --- /dev/null +++ b/include/ns/Platform.h @@ -0,0 +1,35 @@ +#ifndef NATIVESCRIPT_COMMON_PLATFORM_H_ +#define NATIVESCRIPT_COMMON_PLATFORM_H_ + +#include +#include + +// Implemented once by each runtime, in the binary the core links into. None of +// these may call back into the core. +namespace nativescript::common::platform { + +enum class TraceCategory { + kEsm, // module resolution, compilation, linking, evaluation + kFetch, // the HTTP module transport +}; + +// One unconditional diagnostic line (iOS os_log, Android logcat). +void Log(std::string_view message); + +// Whether `category` is being traced. Called on every traced path, from any +// thread, so it should cost no more than a load. +bool TraceEnabled(TraceCategory category); +void Trace(TraceCategory category, std::string_view message); + +// The loader's spelling of `input` as an absolute http(s) module URL: the +// WHATWG href with the authority as written; `input` itself when the parser +// rejects it but it starts with a lowercase http(s) scheme; empty when it is +// not an http(s) URL. +std::string NormalizeHttpModuleUrl(const std::string& input); + +// The WHATWG origin of an absolute http(s) URL; empty for anything else. +std::string HttpUrlOrigin(const std::string& url); + +} // namespace nativescript::common::platform + +#endif // NATIVESCRIPT_COMMON_PLATFORM_H_ diff --git a/include/ns/http/ModuleFetch.h b/include/ns/http/ModuleFetch.h new file mode 100644 index 0000000..72a37c4 --- /dev/null +++ b/include/ns/http/ModuleFetch.h @@ -0,0 +1,99 @@ +#ifndef NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ +#define NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ + +#include +#include +#include +#include + +// The HTTP module loader's policy: which URLs may be fetched, what a response +// means, and the module registry key of an HTTP URL. The transport is the +// platform's (ns/http/ModuleTransport.h). +namespace nativescript::common::http { + +// ─── Responses ────────────────────────────────────────────────────────────── + +enum class ModuleResponseKind { + kJavaScript, + kJson, +}; + +// One module fetch's verdict, the same for every fetch path and transport. +struct ModuleFetchResult { + bool ok = false; + int status = 0; + ModuleResponseKind kind = ModuleResponseKind::kJavaScript; + // An empty 2xx JavaScript body becomes the canonical empty module. + // Meaningful only when `ok`. + std::string body; + std::string contentType; // as received, parameters included + // Reader-facing explanation, non-empty exactly when `!ok`. It reaches the + // importer's rejection verbatim, so it names the URL and the cause. + std::string failureReason; +}; + +// ─── Remote-module gate ───────────────────────────────────────────────────── + +// The allowlist the gate applies once remote modules are enabled. +struct RemoteModuleAllowlist { + // False only when `security.remoteModuleAllowlist` is absent, not an array, + // or an empty array: then every URL is allowed. + bool inForce = false; + // The usable items, each spelled the way the loader spells the URLs it + // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against + // resolved paths, or kept verbatim when it is not an http(s) URL. An item + // that is not a string, is empty or has no exact UTF-8 form is not here: it + // matches nothing but still keeps the list in force. + std::vector entries; +}; + +// The allowlist for the raw `security.remoteModuleAllowlist` value: nullopt +// when it is absent or not an array, otherwise its items in order, each +// nullopt when it is not a string or has no exact UTF-8 form. +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( + const std::optional>>& items); + +// Whether `url` (as fetched) passes `allowlist`: always when it is not in +// force, otherwise when one entry is a prefix of it that ends at a +// URL-component boundary. +bool RemoteUrlAllowedByAllowlist(const std::string& url, + const RemoteModuleAllowlist& allowlist); + +// ─── Registry keys ────────────────────────────────────────────────────────── + +// Which query params are cache busters, which path prefixes are dev endpoints +// whose queries may be normalized, and which paths keep their query verbatim +// because the query is the identity. Supplied per isolate by the dev client +// (ns:module `configureLoader({ canonicalization })`). +struct CanonicalizationConfig { + std::vector stripParams; // query param names to drop + std::vector devPathPrefixes; // StartsWith → normalize query + std::vector preserveQueryPrefixes; // contains → keep query +}; + +// The module registry key of a URL already spelled by NormalizeHttpModuleUrl. +// The fragment is always stripped. The query survives unless `vocabulary` +// says otherwise: a path containing a `preserveQueryPrefixes` entry keeps it +// verbatim; a path under a `devPathPrefixes` entry drops every `stripParams` +// name and sorts what remains. A null `vocabulary` keeps every query. +std::string CanonicalizeNormalizedHttpUrlKey( + const std::string& normalizedUrl, const CanonicalizationConfig* vocabulary); + +// ─── Fetch concurrency ────────────────────────────────────────────────────── + +// Which concurrency cap a module URL's fetches share when the transport +// blocks a thread per request. +// kLoopback: 127.0.0.1, [::1], localhost, or the development machine as seen +// from the Android emulator (10.0.2.2) or Genymotion (10.0.3.2). On a +// device that is almost always `adb reverse`, whose listener overflows +// under a burst of connects, each overflow costing a ~1 s SYN retry. +// kRemote: any other host, where a fetch is bound by its round trip and +// more connections in flight hide more of it. +enum class ModuleFetchHostClass { kLoopback, kRemote }; + +ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url); +const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass); + +} // namespace nativescript::common::http + +#endif // NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ diff --git a/src/Trace.cpp b/src/Trace.cpp new file mode 100644 index 0000000..325132f --- /dev/null +++ b/src/Trace.cpp @@ -0,0 +1,46 @@ +#include "Trace.h" + +#include +#include +#include + +namespace nativescript::common { + +namespace { + +std::string Format(const char* format, va_list args) { + va_list measure; + va_copy(measure, args); + const int length = std::vsnprintf(nullptr, 0, format, measure); + va_end(measure); + if (length <= 0) { + return std::string(); + } + std::string out(static_cast(length) + 1, '\0'); + std::vsnprintf(out.data(), out.size(), format, args); + out.resize(static_cast(length)); + return out; +} + +} // namespace + +void Tracef(platform::TraceCategory category, const char* format, ...) { + if (!platform::TraceEnabled(category)) { + return; + } + va_list args; + va_start(args, format); + const std::string message = Format(format, args); + va_end(args); + platform::Trace(category, message); +} + +void Logf(const char* format, ...) { + va_list args; + va_start(args, format); + const std::string message = Format(format, args); + va_end(args); + platform::Log(message); +} + +} // namespace nativescript::common diff --git a/src/Trace.h b/src/Trace.h new file mode 100644 index 0000000..35beea2 --- /dev/null +++ b/src/Trace.h @@ -0,0 +1,16 @@ +#ifndef NATIVESCRIPT_COMMON_SRC_TRACE_H_ +#define NATIVESCRIPT_COMMON_SRC_TRACE_H_ + +#include "ns/Platform.h" + +namespace nativescript::common { + +// printf-style front ends to platform::Trace and platform::Log. Tracef formats +// nothing unless the category is on. +void Tracef(platform::TraceCategory category, const char* format, ...) + __attribute__((format(printf, 2, 3))); +void Logf(const char* format, ...) __attribute__((format(printf, 1, 2))); + +} // namespace nativescript::common + +#endif // NATIVESCRIPT_COMMON_SRC_TRACE_H_ diff --git a/src/http/Canonicalize.cpp b/src/http/Canonicalize.cpp new file mode 100644 index 0000000..88a3101 --- /dev/null +++ b/src/http/Canonicalize.cpp @@ -0,0 +1,105 @@ +#include +#include +#include + +#include "ns/http/ModuleFetch.h" + +// The query can be part of an HTTP module's identity (auth, content +// versioning, routing), so it is normalized only for the endpoints the client +// names. Which params are cache busters and which paths are dev endpoints is +// knowledge only the client has; guessing would silently collapse two distinct +// modules onto one registry key. +// +// `preserveQueryPrefixes` is checked before the dev-endpoint test so it also +// covers endpoints nested under a dev prefix: a framework that refetches +// recompiled component metadata under a timestamped query would otherwise +// collapse every refetch onto the boot-time key and replay stale metadata. + +namespace nativescript::common::http { + +std::string CanonicalizeNormalizedHttpUrlKey( + const std::string& normalizedUrl, + const CanonicalizationConfig* vocabulary) { + const size_t hashPos = normalizedUrl.find('#'); + const std::string noHash = hashPos == std::string::npos + ? normalizedUrl + : normalizedUrl.substr(0, hashPos); + + const size_t schemePos = noHash.find("://"); + if (schemePos == std::string::npos) { + const size_t q = noHash.find('?'); + return q == std::string::npos ? noHash : noHash.substr(0, q); + } + const size_t pathStart = noHash.find('/', schemePos + 3); + if (pathStart == std::string::npos) { + return noHash; + } + const size_t qPos = noHash.find('?', pathStart); + const std::string originAndPath = + qPos == std::string::npos ? noHash : noHash.substr(0, qPos); + const std::string query = + qPos == std::string::npos ? std::string() : noHash.substr(qPos + 1); + + if (vocabulary == nullptr) { + return noHash; + } + + const std::string pathOnly = originAndPath.substr(pathStart); + for (const std::string& p : vocabulary->preserveQueryPrefixes) { + if (!p.empty() && pathOnly.find(p) != std::string::npos) { + return noHash; + } + } + bool isDevEndpoint = false; + for (const std::string& p : vocabulary->devPathPrefixes) { + if (!p.empty() && pathOnly.compare(0, p.size(), p) == 0) { + isDevEndpoint = true; + break; + } + } + if (!isDevEndpoint) { + return noHash; + } + + if (query.empty()) { + return originAndPath; + } + + std::vector kept; + size_t start = 0; + while (start <= query.size()) { + const size_t amp = query.find('&', start); + const std::string pair = amp == std::string::npos + ? query.substr(start) + : query.substr(start, amp - start); + if (!pair.empty()) { + const size_t eq = pair.find('='); + const std::string name = + eq == std::string::npos ? pair : pair.substr(0, eq); + const bool drop = std::find(vocabulary->stripParams.begin(), + vocabulary->stripParams.end(), + name) != vocabulary->stripParams.end(); + if (!drop) { + kept.push_back(pair); + } + } + if (amp == std::string::npos) { + break; + } + start = amp + 1; + } + if (kept.empty()) { + return originAndPath; + } + std::sort(kept.begin(), kept.end()); + std::string rebuilt = originAndPath + "?"; + for (size_t i = 0; i < kept.size(); i++) { + if (i > 0) { + rebuilt += "&"; + } + rebuilt += kept[i]; + } + return rebuilt; +} + +} // namespace nativescript::common::http diff --git a/src/http/HostClass.cpp b/src/http/HostClass.cpp new file mode 100644 index 0000000..e0cade6 --- /dev/null +++ b/src/http/HostClass.cpp @@ -0,0 +1,52 @@ +#include +#include + +#include "ns/http/ModuleFetch.h" + +namespace nativescript::common::http { + +namespace { + +std::string LowercaseHostOf(const std::string& url) { + const size_t schemeEnd = url.find("://"); + if (schemeEnd == std::string::npos) { + return ""; + } + const size_t start = schemeEnd + 3; + const size_t end = url.find_first_of("/?#", start); + std::string authority = url.substr( + start, end == std::string::npos ? std::string::npos : end - start); + const size_t at = authority.rfind('@'); + if (at != std::string::npos) { + authority.erase(0, at + 1); + } + std::string host; + if (!authority.empty() && authority[0] == '[') { + const size_t close = authority.find(']'); + host = + close == std::string::npos ? authority : authority.substr(0, close + 1); + } else { + host = authority.substr(0, authority.find(':')); + } + for (char& c : host) { + c = static_cast(std::tolower(static_cast(c))); + } + return host; +} + +} // namespace + +ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url) { + const std::string host = LowercaseHostOf(url); + if (host == "127.0.0.1" || host == "[::1]" || host == "localhost" || + host == "10.0.2.2" || host == "10.0.3.2") { + return ModuleFetchHostClass::kLoopback; + } + return ModuleFetchHostClass::kRemote; +} + +const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass) { + return hostClass == ModuleFetchHostClass::kLoopback ? "loopback" : "remote"; +} + +} // namespace nativescript::common::http diff --git a/src/http/Internal.h b/src/http/Internal.h new file mode 100644 index 0000000..2d4e1d7 --- /dev/null +++ b/src/http/Internal.h @@ -0,0 +1,29 @@ +#ifndef NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ +#define NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ + +#include + +#include "ns/http/ModuleFetch.h" + +namespace nativescript::common::http { + +// "text/javascript; charset=utf-8" → "text/javascript": parameters stripped, +// trimmed, lowercased. +std::string MimeEssence(const std::string& contentType); + +// The HTML spec's JavaScript MIME type essence list. +bool IsJavaScriptMimeEssence(const std::string& essence); + +// application/json, text/json, or any `+json` subtype. +bool IsJsonMimeEssence(const std::string& essence); + +// Judges one response. `arrived` means a status line arrived and, for a 2xx, +// the whole body; everything else (status, MIME, emptiness) is decided here. +// `body` is moved into `result` on success. +void ClassifyModuleResponse(const std::string& url, bool arrived, int status, + const std::string& contentType, std::string& body, + ModuleFetchResult& result); + +} // namespace nativescript::common::http + +#endif // NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ diff --git a/src/http/ModuleResponse.cpp b/src/http/ModuleResponse.cpp new file mode 100644 index 0000000..ddebddd --- /dev/null +++ b/src/http/ModuleResponse.cpp @@ -0,0 +1,126 @@ +#include +#include +#include + +#include "Trace.h" +#include "http/Internal.h" + +// Module scripts are strict about MIME: the HTML spec's "fetch a single module +// script" fails outright for anything that is not a JavaScript or JSON MIME +// type, where a classic script would sniff and run it anyway. An SPA dev server +// answering an unknown path with `200 text/html` must say so, not hand HTML to +// the parser and produce `Unexpected token '<'` from deep in the graph. + +namespace nativescript::common::http { + +std::string MimeEssence(const std::string& contentType) { + const size_t semi = contentType.find(';'); + std::string essence = + semi == std::string::npos ? contentType : contentType.substr(0, semi); + const size_t begin = essence.find_first_not_of(" \t"); + if (begin == std::string::npos) { + return ""; + } + const size_t end = essence.find_last_not_of(" \t"); + essence = essence.substr(begin, end - begin + 1); + for (char& c : essence) { + c = static_cast(std::tolower(static_cast(c))); + } + return essence; +} + +bool IsJavaScriptMimeEssence(const std::string& essence) { + static const char* const kJavaScriptEssences[] = {"application/ecmascript", + "application/javascript", + "application/x-ecmascript", + "application/x-javascript", + "text/ecmascript", + "text/javascript", + "text/javascript1.0", + "text/javascript1.1", + "text/javascript1.2", + "text/javascript1.3", + "text/javascript1.4", + "text/javascript1.5", + "text/jscript", + "text/livescript", + "text/x-ecmascript", + "text/x-javascript"}; + for (const char* candidate : kJavaScriptEssences) { + if (essence == candidate) { + return true; + } + } + return false; +} + +bool IsJsonMimeEssence(const std::string& essence) { + if (essence == "application/json" || essence == "text/json") { + return true; + } + const std::string suffix = "+json"; + return essence.size() > suffix.size() && + essence.compare(essence.size() - suffix.size(), suffix.size(), + suffix) == 0; +} + +void ClassifyModuleResponse(const std::string& url, bool arrived, int status, + const std::string& contentType, std::string& body, + ModuleFetchResult& result) { + result.status = status; + result.contentType = contentType; + + if (!arrived) { + result.failureReason = "HTTP import failed: " + url + " (network error)"; + return; + } + if (status == 204 || status == 205) { + // "No content" carries no module, which the web treats as a network error + // for a module script rather than as an empty module. + result.failureReason = "HTTP import failed: " + url + + " (status=" + std::to_string(status) + + ", no content)"; + return; + } + if (status < 200 || status >= 300) { + result.failureReason = "HTTP import failed: " + url + + " (status=" + std::to_string(status) + ")"; + return; + } + + const std::string essence = MimeEssence(contentType); + if (essence.empty()) { + result.failureReason = "Expected a JavaScript module but '" + url + + "' responded with no MIME type"; + return; + } + + if (IsJsonMimeEssence(essence)) { + if (body.empty()) { + result.failureReason = "Expected a JSON module but '" + url + + "' responded with an empty body"; + return; + } + result.kind = ModuleResponseKind::kJson; + } else if (IsJavaScriptMimeEssence(essence)) { + result.kind = ModuleResponseKind::kJavaScript; + // Type-only TypeScript modules transform to zero runtime code and dev + // servers serve them as empty 200s. + if (body.empty()) { + body = "export {};\n"; + Tracef(platform::TraceCategory::kEsm, + "[http-loader] empty 2xx body for %s — serving canonical empty " + "module", + url.c_str()); + } + } else { + result.failureReason = "Expected a JavaScript module but '" + url + + "' responded with MIME type '" + essence + "'"; + return; + } + + result.ok = true; + result.body = std::move(body); +} + +} // namespace nativescript::common::http diff --git a/src/http/RemoteModuleAllowlist.cpp b/src/http/RemoteModuleAllowlist.cpp new file mode 100644 index 0000000..48fe85f --- /dev/null +++ b/src/http/RemoteModuleAllowlist.cpp @@ -0,0 +1,65 @@ +#include + +#include "ns/Platform.h" +#include "ns/http/ModuleFetch.h" + +namespace nativescript::common::http { + +namespace { + +// Stricter than a string prefix: after the entry, `url` must end or continue +// at a URL-component boundary ('/', '?', '#'), unless the entry itself ends in +// '/'. An entry of "https://cdn.example.com" must not authorize +// "https://cdn.example.com.attacker.com/x.js" or +// "https://cdn.example.com:9999/x.js"; a port has to be listed to be allowed. +bool RemoteUrlMatchesAllowlistEntry(const std::string& url, + const std::string& entry) { + if (entry.empty() || url.size() < entry.size()) { + return false; + } + if (url.compare(0, entry.size(), entry) != 0) { + return false; + } + if (url.size() == entry.size() || entry.back() == '/') { + return true; + } + const char next = url[entry.size()]; + return next == '/' || next == '?' || next == '#'; +} + +std::string NormalizeAllowlistEntry(const std::string& entry) { + const std::string url = platform::NormalizeHttpModuleUrl(entry); + return url.empty() ? entry : url; +} + +} // namespace + +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( + const std::optional>>& items) { + RemoteModuleAllowlist allowlist; + if (!items.has_value() || items->empty()) { + return allowlist; + } + allowlist.inForce = true; + for (const std::optional& item : *items) { + if (item.has_value() && !item->empty()) { + allowlist.entries.push_back(NormalizeAllowlistEntry(*item)); + } + } + return allowlist; +} + +bool RemoteUrlAllowedByAllowlist(const std::string& url, + const RemoteModuleAllowlist& allowlist) { + if (!allowlist.inForce) { + return true; + } + for (const std::string& entry : allowlist.entries) { + if (RemoteUrlMatchesAllowlistEntry(url, entry)) { + return true; + } + } + return false; +} + +} // namespace nativescript::common::http diff --git a/tests/FakePlatform.cpp b/tests/FakePlatform.cpp new file mode 100644 index 0000000..aa7ba4b --- /dev/null +++ b/tests/FakePlatform.cpp @@ -0,0 +1,110 @@ +#include "FakePlatform.h" + +#include +#include +#include +#include + +#include "ns/Platform.h" + +namespace { + +std::mutex& Mutex() { + static std::mutex* mutex = new std::mutex(); + return *mutex; +} + +std::vector& Logged() { + static auto* messages = new std::vector(); + return *messages; +} + +std::vector& Traced() { + static auto* messages = new std::vector(); + return *messages; +} + +bool traceEnabled = true; + +bool StartsWith(const std::string& s, const char* prefix) { + return s.rfind(prefix, 0) == 0; +} + +} // namespace + +namespace fake_platform { + +std::vector LoggedMessages() { + std::lock_guard lock(Mutex()); + return Logged(); +} + +std::vector TracedMessages() { + std::lock_guard lock(Mutex()); + return Traced(); +} + +void ClearMessages() { + std::lock_guard lock(Mutex()); + Logged().clear(); + Traced().clear(); +} + +void SetTraceEnabled(bool enabled) { + std::lock_guard lock(Mutex()); + traceEnabled = enabled; +} + +} // namespace fake_platform + +namespace nativescript::common::platform { + +void Log(std::string_view message) { + std::lock_guard lock(Mutex()); + Logged().emplace_back(message); +} + +bool TraceEnabled(TraceCategory) { + std::lock_guard lock(Mutex()); + return traceEnabled; +} + +void Trace(TraceCategory, std::string_view message) { + std::lock_guard lock(Mutex()); + Traced().emplace_back(message); +} + +// Enough of WHATWG URL parsing for the tests: http(s) URLs pass through with +// the scheme and host lowercased, anything else is not a URL. +std::string NormalizeHttpModuleUrl(const std::string& input) { + std::string url = input; + const size_t schemeEnd = url.find("://"); + if (schemeEnd == std::string::npos) { + return ""; + } + const size_t hostEnd = url.find_first_of("/?#", schemeEnd + 3); + const size_t lowerEnd = hostEnd == std::string::npos ? url.size() : hostEnd; + for (size_t i = 0; i < lowerEnd; i++) { + url[i] = + static_cast(std::tolower(static_cast(url[i]))); + } + if (!StartsWith(url, "http://") && !StartsWith(url, "https://")) { + return ""; + } + if (hostEnd == std::string::npos) { + url += "/"; + } + return url; +} + +std::string HttpUrlOrigin(const std::string& url) { + const std::string normalized = NormalizeHttpModuleUrl(url); + if (normalized.empty()) { + return ""; + } + const size_t schemeEnd = normalized.find("://"); + const size_t hostEnd = normalized.find_first_of("/?#", schemeEnd + 3); + return normalized.substr(0, hostEnd); +} + +} // namespace nativescript::common::platform diff --git a/tests/FakePlatform.h b/tests/FakePlatform.h new file mode 100644 index 0000000..8b488f9 --- /dev/null +++ b/tests/FakePlatform.h @@ -0,0 +1,19 @@ +#ifndef NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ +#define NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ + +#include +#include + +// The host tests' stand-in for a runtime's platform functions (ns/Platform.h). +namespace fake_platform { + +// Every Log() and enabled Trace() message, in order. Not thread-safe to read +// while fetches are in flight. +std::vector LoggedMessages(); +std::vector TracedMessages(); +void ClearMessages(); +void SetTraceEnabled(bool enabled); + +} // namespace fake_platform + +#endif // NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ diff --git a/tests/HttpPolicyTest.cpp b/tests/HttpPolicyTest.cpp new file mode 100644 index 0000000..e475de5 --- /dev/null +++ b/tests/HttpPolicyTest.cpp @@ -0,0 +1,223 @@ +#include +#include +#include +#include + +#include "FakePlatform.h" +#include "http/Internal.h" +#include "ns/http/ModuleFetch.h" + +using namespace nativescript::common::http; + +namespace { + +int failures = 0; + +void Check(bool ok, const char* what, const std::string& detail) { + if (!ok) { + failures++; + std::fprintf(stderr, "FAIL %s: \"%s\"\n", what, detail.c_str()); + } +} + +void ExpectEqual(const std::string& actual, const std::string& expected, + const char* what) { + if (actual != expected) { + failures++; + std::fprintf(stderr, "FAIL %s:\n actual: \"%s\"\n expected: \"%s\"\n", + what, actual.c_str(), expected.c_str()); + } +} + +ModuleFetchResult Classify(bool arrived, int status, + const std::string& contentType, std::string body) { + ModuleFetchResult result; + ClassifyModuleResponse("http://h/m.js", arrived, status, contentType, body, + result); + return result; +} + +void TestMime() { + ExpectEqual(MimeEssence("Text/JavaScript; charset=utf-8"), "text/javascript", + "essence lowercases and drops parameters"); + ExpectEqual(MimeEssence(" \tapplication/json \t"), "application/json", + "essence trims"); + ExpectEqual(MimeEssence(" ; charset=utf-8"), "", "essence of nothing"); + Check(IsJavaScriptMimeEssence("text/javascript1.5"), "js essence", + "text/javascript1.5"); + Check(!IsJavaScriptMimeEssence("text/typescript"), "not a js essence", + "text/typescript"); + Check(IsJsonMimeEssence("application/manifest+json"), "+json is json", + "application/manifest+json"); + Check(!IsJsonMimeEssence("+json"), "a bare suffix is not json", "+json"); +} + +void TestClassify() { + ModuleFetchResult r = Classify(false, 0, "", ""); + Check(!r.ok, "transport failure fails", ""); + ExpectEqual(r.failureReason, + "HTTP import failed: http://h/m.js (network error)", + "transport failure text"); + + r = Classify(true, 204, "text/javascript", ""); + ExpectEqual(r.failureReason, + "HTTP import failed: http://h/m.js (status=204, no content)", + "204 text"); + Check(r.status == 204, "status kept", "204"); + + r = Classify(true, 404, "text/html", ""); + ExpectEqual(r.failureReason, "HTTP import failed: http://h/m.js (status=404)", + "404 text"); + + r = Classify(true, 200, "", "x"); + ExpectEqual(r.failureReason, + "Expected a JavaScript module but 'http://h/m.js' responded " + "with no MIME type", + "missing MIME text"); + + r = Classify(true, 200, "text/html; charset=utf-8", ""); + ExpectEqual(r.failureReason, + "Expected a JavaScript module but 'http://h/m.js' responded " + "with MIME type 'text/html'", + "wrong MIME text"); + + r = Classify(true, 200, "application/json", ""); + ExpectEqual(r.failureReason, + "Expected a JSON module but 'http://h/m.js' responded with an " + "empty body", + "empty JSON text"); + + r = Classify(true, 200, "application/json", "{}"); + Check(r.ok && r.kind == ModuleResponseKind::kJson && r.body == "{}", + "json module", r.failureReason); + + fake_platform::ClearMessages(); + r = Classify(true, 200, "text/javascript", ""); + Check(r.ok && r.kind == ModuleResponseKind::kJavaScript, "empty js is ok", + r.failureReason); + ExpectEqual(r.body, "export {};\n", "empty js becomes the empty module"); + Check(fake_platform::TracedMessages().size() == 1, "empty js is traced", ""); + + r = Classify(true, 299, "text/javascript; charset=utf-8", "export {}"); + Check(r.ok && r.body == "export {}" && r.failureReason.empty(), "2xx js", + r.failureReason); + ExpectEqual(r.contentType, "text/javascript; charset=utf-8", + "content type kept with parameters"); +} + +void TestAllowlist() { + RemoteModuleAllowlist absent = RemoteModuleAllowlistFromConfig(std::nullopt); + Check(!absent.inForce, "absent list is not in force", ""); + Check(RemoteUrlAllowedByAllowlist("https://any.example/x.js", absent), + "absent list allows all", ""); + + RemoteModuleAllowlist empty = RemoteModuleAllowlistFromConfig( + std::vector>{}); + Check(!empty.inForce, "empty list is not in force", ""); + + RemoteModuleAllowlist unusable = RemoteModuleAllowlistFromConfig( + std::vector>{std::nullopt, std::string()}); + Check(unusable.inForce && unusable.entries.empty(), + "unusable items keep the list in force", ""); + Check(!RemoteUrlAllowedByAllowlist("https://cdn.example.com/x.js", unusable), + "unusable items match nothing", ""); + + RemoteModuleAllowlist list = + RemoteModuleAllowlistFromConfig(std::vector>{ + std::string("HTTPS://CDN.example.com"), + std::string("https://assets.example.com/pkg/"), + std::string("not a url")}); + Check(list.inForce && list.entries.size() == 3, "usable items kept", ""); + ExpectEqual(list.entries[0], "https://cdn.example.com/", + "entry spelled like a fetched URL"); + ExpectEqual(list.entries[2], "not a url", "non-URL entry kept verbatim"); + + const struct { + const char* url; + bool allowed; + } cases[] = { + {"https://cdn.example.com/x.js", true}, + {"https://cdn.example.com.attacker.com/x.js", false}, + {"https://cdn.example.com:9999/x.js", false}, + {"https://assets.example.com/pkg/a/b.js", true}, + {"https://assets.example.com/pkgx/a.js", false}, + {"https://assets.example.com/other.js", false}, + {"not a url", true}, + {"not a urlx", false}, + {"not a url?q", true}, + }; + for (const auto& c : cases) { + Check(RemoteUrlAllowedByAllowlist(c.url, list) == c.allowed, + c.allowed ? "allowlist allows" : "allowlist refuses", c.url); + } +} + +void TestCanonicalize() { + CanonicalizationConfig vocabulary; + vocabulary.stripParams = {"t", "v"}; + vocabulary.devPathPrefixes = {"/@ns/", "/src/"}; + vocabulary.preserveQueryPrefixes = {"/@ns/sfc-meta"}; + + ExpectEqual( + CanonicalizeNormalizedHttpUrlKey("http://h/a.js?b=1#frag", nullptr), + "http://h/a.js?b=1", "no vocabulary keeps the query"); + ExpectEqual( + CanonicalizeNormalizedHttpUrlKey("http://h/lib/a.js?t=1", &vocabulary), + "http://h/lib/a.js?t=1", "outside dev prefixes keeps the query"); + ExpectEqual(CanonicalizeNormalizedHttpUrlKey("http://h/src/a.js?z=2&t=1&a=1", + &vocabulary), + "http://h/src/a.js?a=1&z=2", "dev endpoint strips and sorts"); + ExpectEqual(CanonicalizeNormalizedHttpUrlKey("http://h/src/a.js?t=1&v=2", + &vocabulary), + "http://h/src/a.js", "dev endpoint with only busters"); + ExpectEqual( + CanonicalizeNormalizedHttpUrlKey("http://h/src/a.js?&&", &vocabulary), + "http://h/src/a.js", "empty pairs dropped"); + ExpectEqual(CanonicalizeNormalizedHttpUrlKey("http://h/@ns/sfc-meta/x?t=9", + &vocabulary), + "http://h/@ns/sfc-meta/x?t=9", + "preserved prefix wins over dev prefix"); + ExpectEqual(CanonicalizeNormalizedHttpUrlKey("http://h", &vocabulary), + "http://h", "no path"); + ExpectEqual(CanonicalizeNormalizedHttpUrlKey("weird?q#f", &vocabulary), + "weird", "no scheme drops the query"); +} + +void TestHostClass() { + const struct { + const char* url; + ModuleFetchHostClass hostClass; + } cases[] = { + {"http://localhost:5173/a.js", ModuleFetchHostClass::kLoopback}, + {"http://LOCALHOST/a.js", ModuleFetchHostClass::kLoopback}, + {"http://127.0.0.1:5173", ModuleFetchHostClass::kLoopback}, + {"http://[::1]:5173/a.js", ModuleFetchHostClass::kLoopback}, + {"http://10.0.2.2:5173/a.js", ModuleFetchHostClass::kLoopback}, + {"http://10.0.3.2/a.js", ModuleFetchHostClass::kLoopback}, + {"http://user:pw@localhost/a.js", ModuleFetchHostClass::kLoopback}, + {"http://localhost.example.com/a.js", ModuleFetchHostClass::kRemote}, + {"http://localhost@evil.example/a.js", ModuleFetchHostClass::kRemote}, + {"https://cdn.example.com/a.js", ModuleFetchHostClass::kRemote}, + {"no scheme", ModuleFetchHostClass::kRemote}, + }; + for (const auto& c : cases) { + Check(ModuleFetchHostClassOf(c.url) == c.hostClass, + ModuleFetchHostClassName(c.hostClass), c.url); + } +} + +} // namespace + +int main() { + TestMime(); + TestClassify(); + TestAllowlist(); + TestCanonicalize(); + TestHostClass(); + if (failures > 0) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::printf("all HTTP policy tests passed\n"); + return 0; +} From ac7baf50507302789210e7fb2c3a52bff84d73ff Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 00:35:04 -0300 Subject: [PATCH 2/2] feat(http): own the module fetch orchestration behind a transport seam The core now runs every HTTP module fetch and a platform transport only performs single attempts (ns/http/ModuleTransport.h): the gate, the request headers, timeouts, the single transport-error retry, deadline clamping, the synchronous fallback's wait bound, classification, the cache switch with its holders, and Clear-Site-Data. Transports that block run on fetch threads capped per host class; transports that schedule themselves get their retry delay from a core timer thread. Decisions D1-D10 from the design (docs/DESIGN.md section 7 D), including changes from today's runtimes: - the gate is re-checked against the URL a redirect ended at; - User-Agent: NativeScript-HTTP-ESM on every transport; - Clear-Site-Data clears the response and the fetching origin; - failed cache clears are reported through CacheOpResult. --- CMakeLists.txt | 5 +- docs/DESIGN.md | 92 ++-- include/ns/http/ModuleFetch.h | 62 +++ include/ns/http/ModuleTransport.h | 146 +++++ src/http/Internal.h | 23 + src/http/ModuleFetch.cpp | 851 ++++++++++++++++++++++++++++++ tests/FakePlatform.cpp | 113 ++++ tests/FakePlatform.h | 70 ++- tests/HttpFetchTest.cpp | 565 ++++++++++++++++++++ 9 files changed, 1887 insertions(+), 40 deletions(-) create mode 100644 include/ns/http/ModuleTransport.h create mode 100644 src/http/ModuleFetch.cpp create mode 100644 tests/HttpFetchTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c5d3de..7d09936 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,7 @@ set(NS_RUNTIME_COMMON_V8_FREE_SOURCES src/Trace.cpp src/http/Canonicalize.cpp src/http/HostClass.cpp + src/http/ModuleFetch.cpp src/http/ModuleResponse.cpp src/http/RemoteModuleAllowlist.cpp ) @@ -73,15 +74,17 @@ target_compile_options(ns_runtime_common PRIVATE ${NS_RUNTIME_COMMON_WARNINGS}) if (NS_RUNTIME_COMMON_HOST_TESTS) enable_testing() + find_package(Threads REQUIRED) # The core resolves its platform functions (ns/Platform.h) at the final # link; tests/FakePlatform.cpp stands in for a runtime's. set(NS_RUNTIME_COMMON_TESTS Base64Test + HttpFetchTest HttpPolicyTest ) foreach (test ${NS_RUNTIME_COMMON_TESTS}) add_executable(${test} tests/${test}.cpp tests/FakePlatform.cpp) - target_link_libraries(${test} PRIVATE ns_runtime_common) + target_link_libraries(${test} PRIVATE ns_runtime_common Threads::Threads) target_include_directories(${test} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) target_compile_features(${test} PRIVATE cxx_std_20) set_target_properties(${test} PROPERTIES CXX_EXTENSIONS OFF) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index de3e935..e836d4c 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,9 +1,10 @@ # A shared module-loader core for the iOS and Android runtimes Status: proposal, 2026-12-04, updated 2026-12-05. Step 1 of §9 (this -repository and its build wiring) is under way. F3 (a private submodule -repository) and F7 (the `nativescript::common` namespace) are decided; the -rest of §7 is open. iOS #622 has since merged (052675a1); its Android port is +repository and its build wiring) is done, and step 5 (the HTTP policy core) +is built in `ns/http/`. F3 (a submodule repository), F7 (the +`nativescript::common` namespace) and D1–D10 are decided; the rest of §7 is +open. iOS #622 has since merged (052675a1); its Android port is NativeScript/android #2177. Baseline: NativeScript/ios `origin/main` 73c99f9f, NativeScript/android @@ -381,15 +382,17 @@ using Deadline = std::optional; ### 4.5 HTTP transport (report C §3) -The cut is at **one attempt**. The core owns: -- the gate and allowlist; -- the header set; +Built: `ns/http/ModuleTransport.h` (the seam) and `ns/http/ModuleFetch.h` (the +loader's API). The cut is at **one attempt**. The core owns: +- the gate and allowlist, re-checked against the URL a redirect ended at; +- the header set, `User-Agent: NativeScript-HTTP-ESM` included; - the timeout, retry and deadline policy; - classification; -- the cache switch and its inspector holders; -- Clear-Site-Data parsing. +- the cache switch and its holders; +- Clear-Site-Data parsing and scope; +- the fetch threads for transports that block, capped per host class. -The transport only performs attempts. +The transport only performs attempts and stores the cache. ```cpp namespace nativescript::common::http { @@ -397,42 +400,56 @@ namespace nativescript::common::http { struct AttemptRequest { std::string url; // gated, NormalizeHttpModuleUrl spelling, never canonicalized FetchPath path; // kGraphWalk | kSynchronousFallback (separate connections) - std::chrono::milliseconds timeout; - bool useCache; // sampled once per fetch by the core - const Headers* headers; + std::chrono::milliseconds timeout; // idle bound, > 0, clamped to the deadline + std::chrono::milliseconds waitBound; // sync only: timeout + 5 s, honoured if cancellable + bool useCache; // sampled once per fetch, when it is issued + std::vector headers; // core-built, no-cache pair included when off }; struct AttemptOutcome { - bool arrived; int status; std::string contentType, body, finalUrl; + bool arrived; // status line, and for a 2xx the whole body + int status; std::string contentType, body; + std::string finalUrl; // after redirects, set whenever `arrived` std::vector clearSiteData; // raw; the core parses and applies + bool malformedUrl, waitExpired; // neither is retried std::string errorDescription; }; class ModuleTransport { public: + virtual const char* Name() const = 0; virtual AttemptOutcome FetchBlocking(const AttemptRequest&) = 0; - // Default (in core): FetchBlocking on per-host-class lanes (Android's lanes, moved). - virtual void FetchAsync(AttemptRequest, std::function anyThreadOnce); virtual bool SchedulesItself() const { return false; } // NSURLSession: true + // Only used when SchedulesItself(); otherwise the core runs FetchBlocking on its + // fetch threads (Android's lanes, moved). + virtual void FetchAsync(AttemptRequest, std::function anyThreadOnce); + // The retry delay of a self-scheduling transport. Default: one core timer thread; + // iOS overrides it with dispatch_after so each task gets an autorelease pool. + virtual bool PostDelayed(std::chrono::milliseconds, std::function); virtual CacheOpResult ClearAll() = 0; virtual CacheOpResult ClearOrigin(const std::string& origin) = 0; + virtual void OnFetchThreadStart() {} // Android: JVM attach + virtual void OnFetchThreadExit() {} // Android: JVM detach }; } // namespace nativescript::common::http namespace nativescript::common::platform { +http::HttpLoaderConfig ReadHttpLoaderConfig(); // once per process, before any cache setter http::ModuleTransport& HttpTransport(); -void OnLaneThreadStart(); // Android: JVM attach -void OnLaneThreadExit(); // Android: JVM detach } ``` -- **iOS** keeps its NSURLSession partitions, NSURLCache generations and - delegate queues inside the transport. +- **iOS** keeps its NSURLSession partitions, NSURLCache generations, launch + options and delegate queues inside the transport. - **Android** keeps OkHttp, HttpURLConnection, StrictMode and JNI frame - handling inside it. + handling inside it. Its transport cannot cancel a blocking attempt yet, so + its synchronous fallback still has no total-wait bound (D7). - Both already satisfy this contract (report C §2): completion exactly once, on any thread, possibly inline; never canonicalize; the sync path never shares the walk's connections. +- The retry delay of a self-scheduling transport runs through its + `PostDelayed`, holding no connection. On the fetch threads it still sleeps, + holding the slot for 120 ms (D1, v1). ### 4.6 Threads @@ -714,22 +731,25 @@ the #383/#444 ↔ android#1965/#2021 work): | C4 | File `import()` pumping | #622: async; Android main: sync pump | #622 | | C5 | Boot backstop: rejection on the first poll | Android fatal; iOS not | Android | -### D. HTTP (report C §3 D1–D10, condensed) - -- **Sync fallback total wait bound:** take iOS's timeout + 5 s. Android needs a - cancellable call for it. -- **What counts as a transport error:** take Android's rule; a status-bearing - response is never one. -- **Clear-Site-Data scope:** take iOS's rule, response origin plus requesting - origin. -- **Failed cache clears:** report them, as Android does. JS throws and the - inspector answers `-32000`. -- **Inspector bookkeeping:** take iOS's shape, a holder set keyed by connection - id. -- **User-Agent:** one value on both. iOS sends none today. -- **Queue time counts against the deadline,** as on Android. -- **Open, neither side does it:** re-check the gate after redirects. Expose - `finalUrl` now so the check can be added. +### D. HTTP (report C §3 D1–D10): decided 2026-12-05 + +All ten as report C recommends, built in `ns/http/`: + +| # | Decision | +|---|---| +| D1 | The retry delay runs off-thread on a core timer for self-scheduling transports. Fetch threads sleep through it for now. | +| D2 | Queue time counts against the deadline: each attempt's timeout is computed when it starts. | +| D3 | The cache switch is sampled once per fetch, when it is issued; a retry reuses it. | +| D4 | Clear-Site-Data clears the response's origin plus the fetching origin, each once, before the fetch is reported. | +| D5 | Failed cache clears are reported (`CacheOpResult`). JS throws and the inspector answers `-32000`. | +| D6 | Cache holders are a set keyed by an opaque id (`SetModuleHttpCacheDisabledBy`), idempotent per id. | +| D7 | The sync fallback's total wait is the attempt timeout + 5 s. Android cannot cancel an attempt yet, so its wait stays unbounded until its transport can. | +| D8 | `User-Agent: NativeScript-HTTP-ESM` on both. | +| D9 | Deadlines are `optional` everywhere. | +| D10 | The gate is re-checked against the final URL after redirects. A transport that does not report it fails closed while an allowlist is in force. The redirect is still followed first, so the request reaches the target before the check. | + +Also: a transport error is a response that did not arrive (Android's rule): a +status-bearing answer never is, unless it is a 2xx whose body failed. ### E. Error policy diff --git a/include/ns/http/ModuleFetch.h b/include/ns/http/ModuleFetch.h index 72a37c4..c8964d4 100644 --- a/include/ns/http/ModuleFetch.h +++ b/include/ns/http/ModuleFetch.h @@ -1,11 +1,16 @@ #ifndef NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ #define NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ +#include #include +#include +#include #include #include #include +#include "ns/http/ModuleTransport.h" + // The HTTP module loader's policy: which URLs may be fetched, what a response // means, and the module registry key of an HTTP URL. The transport is the // platform's (ns/http/ModuleTransport.h). @@ -94,6 +99,63 @@ enum class ModuleFetchHostClass { kLoopback, kRemote }; ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url); const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass); +// The fetch thread cap for `hostClass`: the platform's configured value, or +// the default (loopback 6, remote 32). Unused while the transport schedules +// itself. +size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass); + +// ─── Gate ─────────────────────────────────────────────────────────────────── + +// Debug builds always allow remote modules; release builds only when the app +// config enables them. +bool IsRemoteModulesAllowed(); + +// Whether `url` (NormalizeHttpModuleUrl spelling) may be fetched: in debug +// builds always, otherwise when remote modules are enabled and the allowlist +// passes it. +bool IsRemoteUrlAllowed(const std::string& url); + +// ─── Fetching ─────────────────────────────────────────────────────────────── +// +// `url` is gated, fetched and reported in NormalizeHttpModuleUrl spelling; +// nothing here canonicalizes. Both primitives judge responses alike and share +// the cache. Either retries once, only for a transport error and never for an +// HTTP status. + +// Blocks the calling thread for one module. The wait is bounded by the +// attempt timeout plus a margin when the transport can cancel an attempt. +// Returns `result.ok`. +bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); + +// The graph load's fetch budget; nullopt is unbounded. Each attempt's timeout +// is clamped to what remains when it starts, so time spent queued counts, and +// no attempt starts past it. A response that lands late is still reported. +using ModuleFetchDeadline = + std::optional; + +// Never blocks. `completion` runs exactly once, on any thread, possibly +// before this returns (a blocked URL, a deadline already passed). It must not +// touch the engine. +void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline deadline, + std::function completion); + +// ─── HTTP cache ───────────────────────────────────────────────────────────── +// +// Process-wide, from any thread. Each fetch reads the switch once, when it is +// issued, so a change never affects a fetch already in flight. + +// The setting, and no holder disabling it. +bool ModuleHttpCacheEnabled(); + +void SetModuleHttpCacheEnabled(bool enabled); + +// Holders (an inspector connection) disable the cache for as long as any +// holds it. Idempotent per id; a holder going away passes false. +void SetModuleHttpCacheDisabledBy(uint64_t holderId, bool disabled); + +// Everything the module cache stores, durably before returning. +CacheOpResult ClearModuleHttpCache(); + } // namespace nativescript::common::http #endif // NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_ diff --git a/include/ns/http/ModuleTransport.h b/include/ns/http/ModuleTransport.h new file mode 100644 index 0000000..dfffc23 --- /dev/null +++ b/include/ns/http/ModuleTransport.h @@ -0,0 +1,146 @@ +#ifndef NATIVESCRIPT_COMMON_HTTP_MODULE_TRANSPORT_H_ +#define NATIVESCRIPT_COMMON_HTTP_MODULE_TRANSPORT_H_ + +#include +#include +#include +#include +#include +#include + +// The seam between the core's HTTP module loader and a platform's HTTP stack. +// The core owns everything about a module fetch except performing one attempt: +// the gate, the request headers, timeouts, retry, deadlines, classification, +// the cache switch and Clear-Site-Data. A transport performs single attempts +// and stores the cache. +namespace nativescript::common::http { + +// Which caller an attempt serves. A transport keeps the synchronous fallback +// off the connections the graph walk holds, or a blocking fallback fetch can +// wait behind the very walk that is waiting for it. +enum class FetchPath { kGraphWalk, kSynchronousFallback }; + +struct RequestHeader { + std::string name; + std::string value; +}; + +struct AttemptRequest { + // Gated, in NormalizeHttpModuleUrl spelling, never canonicalized. + std::string url; + FetchPath path = FetchPath::kGraphWalk; + // Idle bound for the connect and for each read, always > 0. + std::chrono::milliseconds timeout{0}; + // kSynchronousFallback only: how long the caller may be blocked in total. A + // transport that can cancel an attempt stops waiting after this and reports + // `waitExpired`; one that cannot may block longer. + std::chrono::milliseconds waitBound{0}; + // Off: read nothing from and write nothing to the cache. `headers` then + // already carries the no-cache pair. + bool useCache = true; + // Sent as given, in order, on every attempt. + std::vector headers; +}; + +struct AttemptOutcome { + // A status line arrived and, for a 2xx, the whole body did too. Everything + // else is a transport error, which the core may retry. + bool arrived = false; + int status = 0; + std::string contentType; // as received + std::string body; + // After redirects; set whenever `arrived`. The core re-checks the gate + // against it and scopes Clear-Site-Data by it. + std::string finalUrl; + // Every Clear-Site-Data header value of the final response, unparsed. + std::vector clearSiteData; + // The transport could not form a request for the URL at all. Not retried. + bool malformedUrl = false; + // The attempt was abandoned at `waitBound`. Not retried. + bool waitExpired = false; + // For logs only. + std::string errorDescription; +}; + +struct CacheOpResult { + bool ok = true; + std::string error; // reader-facing, set when !ok +}; + +class ModuleTransport { + public: + virtual ~ModuleTransport() = default; + + // Short and stable, for diagnostics ("nsurlsession", "okhttp", ...). + virtual const char* Name() const = 0; + + // One attempt, blocking the calling thread. Called for every + // kSynchronousFallback attempt, and for graph-walk attempts on the core's + // fetch threads when the transport does not schedule itself. + virtual AttemptOutcome FetchBlocking(const AttemptRequest& request) = 0; + + // True when the transport queues and caps its own connections. The core then + // starts graph-walk attempts through FetchAsync; otherwise it runs them on + // its own fetch threads, capped per ModuleFetchHostClass. + virtual bool SchedulesItself() const { return false; } + + // One attempt without blocking the caller. `done` runs exactly once, on any + // thread, possibly before FetchAsync returns. It must not throw. The default + // runs FetchBlocking inline. + virtual void FetchAsync(AttemptRequest request, + std::function done); + + // Runs `task` once, on any thread, no sooner than `delay` from now, without + // blocking the caller; false when it cannot, and `task` then never runs. + // Used for the retry delay of a transport that schedules itself. The task + // starts the next attempt and may deliver the fetch's result. The default + // uses one core thread, which sets up nothing for it (no autorelease pool). + virtual bool PostDelayed(std::chrono::milliseconds delay, + std::function task); + + // Cache storage, from any thread. Durable before returning. Attempts already + // in flight may still complete from, or store into, what was cleared. + virtual CacheOpResult ClearAll() = 0; + // May clear more than `origin`. + virtual CacheOpResult ClearOrigin(const std::string& origin) = 0; + + // Run on each core fetch thread, before its first attempt and after its + // last. + virtual void OnFetchThreadStart() {} + virtual void OnFetchThreadExit() {} +}; + +// What the platform knows about the app, read once per process, the first +// time the loader needs any of it. +struct HttpLoaderConfig { + // Debuggable app: the remote-module gate is open and attempts get the long + // timeout. + bool isDebug = false; + // security.allowRemoteModules. A platform that cannot read the whole + // allowlist reports false here rather than enable it with a partial list. + bool allowRemoteModules = false; + // security.remoteModuleAllowlist, raw: see RemoteModuleAllowlistFromConfig. + std::optional>> remoteModuleAllowlist; + // The cache setting before anything changes it: the app config's + // `moduleHttpCache`, overridden by a no-cache launch option. + bool moduleHttpCacheAtStartup = true; + // Fetch thread caps per ModuleFetchHostClass ({loopback, remote}) when the + // transport does not schedule itself; 0 keeps the default. + size_t fetchConcurrency[2] = {0, 0}; +}; + +} // namespace nativescript::common::http + +// Implemented by each runtime, alongside ns/Platform.h's functions. +namespace nativescript::common::platform { + +http::HttpLoaderConfig ReadHttpLoaderConfig(); + +// The transport for every attempt. Lives for the rest of the process; it may +// change what it does internally (fall back to another HTTP stack), but the +// same object is returned on every call. +http::ModuleTransport& HttpTransport(); + +} // namespace nativescript::common::platform + +#endif // NATIVESCRIPT_COMMON_HTTP_MODULE_TRANSPORT_H_ diff --git a/src/http/Internal.h b/src/http/Internal.h index 2d4e1d7..8896ba5 100644 --- a/src/http/Internal.h +++ b/src/http/Internal.h @@ -1,7 +1,9 @@ #ifndef NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ #define NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ +#include #include +#include #include "ns/http/ModuleFetch.h" @@ -24,6 +26,27 @@ void ClassifyModuleResponse(const std::string& url, bool arrived, int status, const std::string& contentType, std::string& body, ModuleFetchResult& result); +// Whether any Clear-Site-Data value, each a comma-separated list of quoted +// strings, holds "cache" or "*". +bool ClearSiteDataClearsCache(const std::vector& values); + +namespace testing { + +struct Timing { + std::chrono::milliseconds debugTimeout{30000}; + std::chrono::milliseconds releaseTimeout{5000}; + std::chrono::milliseconds retryDelay{120}; + std::chrono::milliseconds syncWaitMargin{5000}; +}; + +void SetTiming(const Timing& timing); + +// Forgets the platform config and the cache switch; the next call reads +// platform::ReadHttpLoaderConfig() again. Only while no fetch is in flight. +void Reset(); + +} // namespace testing + } // namespace nativescript::common::http #endif // NATIVESCRIPT_COMMON_SRC_HTTP_INTERNAL_H_ diff --git a/src/http/ModuleFetch.cpp b/src/http/ModuleFetch.cpp new file mode 100644 index 0000000..c15bf15 --- /dev/null +++ b/src/http/ModuleFetch.cpp @@ -0,0 +1,851 @@ +#include "ns/http/ModuleFetch.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Trace.h" +#include "http/Internal.h" +#include "ns/Platform.h" +#include "ns/http/ModuleTransport.h" + +// Everything here is process-wide and reached from any thread: isolate +// threads, transport callback threads, the core's fetch and timer threads, and +// an inspector's socket thread. Process-lifetime objects are leaked so nothing +// is destroyed under a thread still running at exit. + +namespace nativescript::common::http { + +using platform::TraceCategory; +using std::chrono::milliseconds; +using std::chrono::steady_clock; + +namespace { + +// ── Timing ────────────────────────────────────────────────────────────────── + +// Debug builds talk to dev servers that transform cold modules on demand, +// measured at 5-9 s; release builds fetch opt-in remote modules that should +// fail fast. Both are idle timeouts, not bounds on the whole response. +std::atomic g_debugTimeoutMs{30000}; +std::atomic g_releaseTimeoutMs{5000}; +// Long enough for a transient hiccup to pass, short against any timeout. +std::atomic g_retryDelayMs{120}; +// How long the synchronous fallback waits past the attempt timeout: an idle +// timeout lets a trickling response outlast it, and this keeps the blocked +// thread's wait finite regardless. +std::atomic g_syncWaitMarginMs{5000}; + +milliseconds RetryDelay() { return milliseconds(g_retryDelayMs.load()); } +milliseconds SyncWaitMargin() { + return milliseconds(g_syncWaitMarginMs.load()); +} + +// ── Config and cache switch ───────────────────────────────────────────────── + +struct LoaderState { + explicit LoaderState(HttpLoaderConfig loaderConfig) + : config(std::move(loaderConfig)), + allowlist( + RemoteModuleAllowlistFromConfig(config.remoteModuleAllowlist)), + cacheSetting(config.moduleHttpCacheAtStartup) {} + + const HttpLoaderConfig config; + const RemoteModuleAllowlist allowlist; + + std::mutex cacheMutex; + bool cacheSetting; + std::set cacheDisabledBy; +}; + +std::mutex& StateMutex() { + static auto* mutex = new std::mutex(); + return *mutex; +} + +std::atomic g_state{nullptr}; + +// Reads the platform config on first use, so the startup cache setting is +// in place before any setter can run. +LoaderState& State() { + LoaderState* state = g_state.load(std::memory_order_acquire); + if (state != nullptr) { + return *state; + } + std::lock_guard lock(StateMutex()); + state = g_state.load(std::memory_order_relaxed); + if (state == nullptr) { + state = new LoaderState(platform::ReadHttpLoaderConfig()); + g_state.store(state, std::memory_order_release); + } + return *state; +} + +milliseconds PolicyTimeout() { + return milliseconds(State().config.isDebug ? g_debugTimeoutMs.load() + : g_releaseTimeoutMs.load()); +} + +// ── Gate ──────────────────────────────────────────────────────────────────── + +const char* const kBlockedPrefix = + "HTTP import blocked: remote module loading is not allowed for "; + +void Block(const std::string& url, ModuleFetchResult& result) { + result.status = 403; + result.failureReason = kBlockedPrefix + url; + Tracef(TraceCategory::kEsm, "[http-esm][security][blocked] %s", url.c_str()); +} + +std::atomic g_reportedMissingFinalUrl{false}; + +// The gate again, for the URL a redirect ended at. A transport that cannot +// report it fails closed while an allowlist is in force. That only bites in +// release builds, so the omission is logged in every build. +bool RedirectTargetAllowed(const std::string& url, + const AttemptOutcome& outcome) { + if (outcome.finalUrl.empty() && !g_reportedMissingFinalUrl.exchange(true)) { + Logf( + "NativeScript: the %s module transport did not report the final URL " + "of %s; release builds with a remote module allowlist refuse such " + "responses", + platform::HttpTransport().Name(), url.c_str()); + } + const LoaderState& state = State(); + if (state.config.isDebug || !state.allowlist.inForce || + outcome.finalUrl == url) { + return true; + } + if (outcome.finalUrl.empty()) { + return false; + } + const std::string finalUrl = + platform::NormalizeHttpModuleUrl(outcome.finalUrl); + return !finalUrl.empty() && + RemoteUrlAllowedByAllowlist(finalUrl, state.allowlist); +} + +// ── Attempts ──────────────────────────────────────────────────────────────── + +const char* const kUserAgent = "NativeScript-HTTP-ESM"; + +AttemptRequest MakeRequest(const std::string& url, FetchPath path, + milliseconds timeout, bool useCache) { + AttemptRequest request; + request.url = url; + request.path = path; + request.timeout = timeout; + request.useCache = useCache; + request.headers = { + {"Accept", "application/javascript, text/javascript, */*;q=0.1"}, + // Bodies are compiled as received, and a transparent decoder would hide + // a truncated compressed body behind a short but "complete" one. + {"Accept-Encoding", "identity"}, + {"User-Agent", kUserAgent}, + }; + if (!useCache) { + request.headers.push_back({"Cache-Control", "no-cache"}); + request.headers.push_back({"Pragma", "no-cache"}); + } + return request; +} + +AttemptOutcome TransportThrew(const std::string& url, const char* what) { + Logf("[http-loader][fetch] %s transport threw fetching %s: %s", + platform::HttpTransport().Name(), url.c_str(), what); + AttemptOutcome outcome; + outcome.errorDescription = what; + return outcome; +} + +AttemptOutcome FetchBlocking(const AttemptRequest& request) { + try { + return platform::HttpTransport().FetchBlocking(request); + } catch (const std::exception& e) { + return TransportThrew(request.url, e.what()); + } catch (...) { + return TransportThrew(request.url, "unknown exception"); + } +} + +// A response's Clear-Site-Data takes effect before the fetch is reported, so +// nothing requested from then on can come from the cleared cache. It clears +// the final response's origin, and the origin the fetch was issued for when +// that differs: the carrier is stored under the latter after a cross-origin +// redirect, and left there it would replay from the cache and clear again on +// every hit. Each origin once. +void ApplyClearSiteData(const std::string& url, bool useCache, + const AttemptOutcome& outcome) { + if (outcome.clearSiteData.empty()) { + return; + } + try { + if (!ClearSiteDataClearsCache(outcome.clearSiteData)) { + return; + } + const std::string responseOrigin = platform::HttpUrlOrigin( + outcome.finalUrl.empty() ? url : outcome.finalUrl); + std::vector origins{responseOrigin}; + if (useCache) { + const std::string fetchingOrigin = platform::HttpUrlOrigin(url); + if (fetchingOrigin != responseOrigin) { + origins.push_back(fetchingOrigin); + } + } + for (const std::string& origin : origins) { + if (origin.empty()) { + continue; + } + const CacheOpResult cleared = + platform::HttpTransport().ClearOrigin(origin); + if (!cleared.ok) { + Logf( + "NativeScript: could not apply Clear-Site-Data from a module " + "response: %s", + cleared.error.c_str()); + } + } + } catch (...) { + Logf( + "NativeScript: could not apply Clear-Site-Data from a module " + "response"); + } +} + +// The verdict on an attempt that will not be retried. +void JudgeOutcome(const std::string& url, AttemptOutcome& outcome, + ModuleFetchResult& result) { + if (outcome.malformedUrl) { + result.failureReason = + "HTTP import failed: " + url + " (malformed request URL)"; + return; + } + if (outcome.arrived && !RedirectTargetAllowed(url, outcome)) { + const std::string target = + outcome.finalUrl.empty() ? "" : outcome.finalUrl; + result.status = 403; + result.failureReason = + kBlockedPrefix + target + " (redirected from " + url + ")"; + Tracef(TraceCategory::kEsm, + "[http-esm][security][blocked] %s (redirected from %s)", + target.c_str(), url.c_str()); + return; + } + ClassifyModuleResponse(url, outcome.arrived, outcome.status, + outcome.contentType, outcome.body, result); +} + +bool IsTransportError(const AttemptOutcome& outcome) { + return !outcome.arrived && !outcome.malformedUrl && !outcome.waitExpired; +} + +uint64_t ElapsedMs(steady_clock::time_point since) { + const auto elapsed = steady_clock::now() - since; + return elapsed.count() > 0 + ? static_cast( + std::chrono::duration_cast(elapsed).count()) + : 0; +} + +// ── Synchronous fallback ──────────────────────────────────────────────────── + +// Coarse on purpose, summarized once per kFetchSyncSummaryEvery fetches: +// mostly "fast" (<10 ms) means kept-alive connections are reused; mostly +// "slow" (>=100 ms) means handshakes or large bodies. +std::atomic g_fetchSyncCount{0}; +std::atomic g_fetchSyncTotalMs{0}; +std::atomic g_fetchSyncFast{0}; +std::atomic g_fetchSyncMedium{0}; +std::atomic g_fetchSyncSlow{0}; +constexpr size_t kFetchSyncSummaryEvery = 100; + +void RecordSyncFetchTime(uint64_t fetchMs) { + g_fetchSyncTotalMs.fetch_add(fetchMs, std::memory_order_relaxed); + if (fetchMs < 10) { + g_fetchSyncFast.fetch_add(1, std::memory_order_relaxed); + } else if (fetchMs < 100) { + g_fetchSyncMedium.fetch_add(1, std::memory_order_relaxed); + } else { + g_fetchSyncSlow.fetch_add(1, std::memory_order_relaxed); + } + const size_t syncCount = + g_fetchSyncCount.fetch_add(1, std::memory_order_relaxed) + 1; + if (syncCount % kFetchSyncSummaryEvery == 0) { + const uint64_t totalMs = g_fetchSyncTotalMs.load(std::memory_order_relaxed); + Tracef(TraceCategory::kEsm, + "[http-loader][fetch-sync][summary] count=%lu avg=%llums " + "fast(<10ms)=%lu medium=%lu slow(>=100ms)=%lu", + static_cast(syncCount), + static_cast(totalMs / syncCount), + static_cast( + g_fetchSyncFast.load(std::memory_order_relaxed)), + static_cast( + g_fetchSyncMedium.load(std::memory_order_relaxed)), + static_cast( + g_fetchSyncSlow.load(std::memory_order_relaxed))); + } +} + +AttemptOutcome SyncAttempt(const std::string& url, milliseconds timeout, + bool useCache) { + AttemptRequest request = + MakeRequest(url, FetchPath::kSynchronousFallback, timeout, useCache); + request.waitBound = timeout + SyncWaitMargin(); + const auto start = steady_clock::now(); + AttemptOutcome outcome = FetchBlocking(request); + ApplyClearSiteData(url, useCache, outcome); + if (outcome.waitExpired) { + Logf( + "NativeScript: synchronous module fetch of %s got no response within " + "%.0fs", + url.c_str(), std::chrono::duration(request.waitBound).count()); + return outcome; + } + const uint64_t fetchMs = ElapsedMs(start); + RecordSyncFetchTime(fetchMs); + if (!outcome.arrived) { + Tracef(TraceCategory::kEsm, + "[http-loader][fetch-error] url=%s %s status=%d bodyEmpty=%d " + "ms=%llu", + url.c_str(), outcome.errorDescription.c_str(), outcome.status, + outcome.body.empty() ? 1 : 0, + static_cast(fetchMs)); + } + return outcome; +} + +// ── Asynchronous fetches ──────────────────────────────────────────────────── + +struct AsyncFetch { + std::string url; + ModuleFetchDeadline deadline; + bool useCache = true; + ModuleFetchHostClass hostClass = ModuleFetchHostClass::kRemote; + steady_clock::time_point start; + std::function completion; +}; +using AsyncFetchPtr = std::shared_ptr; + +// The timeout for an attempt starting now, or nullopt once `deadline` has +// passed. Rounded up: a sub-millisecond remainder must not become 0, which +// some HTTP stacks read as no timeout at all. +std::optional AttemptTimeout( + const ModuleFetchDeadline& deadline) { + const milliseconds policy = PolicyTimeout(); + if (!deadline) { + return policy; + } + const auto now = steady_clock::now(); + if (now >= *deadline) { + return std::nullopt; + } + return std::min(policy, std::chrono::ceil(*deadline - now)); +} + +bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) { + return !deadline || *deadline - steady_clock::now() > RetryDelay(); +} + +// One retry, for a transport error on the first attempt, while the deadline +// still fits the delay. The retry clamps to whatever remains when it starts. +bool WantsRetry(const AsyncFetch& fetch, int attempt, + const AttemptOutcome& outcome) { + if (attempt > 0 || !IsTransportError(outcome)) { + return false; + } + if (!RetryFitsDeadline(fetch.deadline)) { + Tracef(TraceCategory::kEsm, + "[http-loader][fetch-async] no budget left to retry %s", + fetch.url.c_str()); + return false; + } + Tracef(TraceCategory::kEsm, + "[http-loader][fetch-async] retrying %s after transport error: %s", + fetch.url.c_str(), + outcome.errorDescription.empty() ? "" + : outcome.errorDescription.c_str()); + return true; +} + +ModuleFetchResult DeadlineExceeded(const std::string& url) { + ModuleFetchResult result; + result.failureReason = + "HTTP import failed: " + url + " (module graph fetch deadline exceeded)"; + return result; +} + +ModuleFetchResult InternalError(const std::string& url) { + ModuleFetchResult result; + result.failureReason = + "HTTP import failed: " + url + " (internal error handling the response)"; + return result; +} + +// Settles `fetch`. Its completion is released here, so whatever it captured +// is destroyed on this thread whichever thread holds the last reference. +void Deliver(const AsyncFetchPtr& fetch, int attempt, + ModuleFetchResult result) { + if (!result.ok) { + Tracef(TraceCategory::kEsm, + "[http-loader][fetch-async][reject] attempt=%d %s", attempt, + result.failureReason.c_str()); + } else { + Tracef(TraceCategory::kFetch, + "[http-loader][fetch][async] %s bytes=%lu " + "ms=%llu", + fetch->url.c_str(), static_cast(result.body.size()), + static_cast(ElapsedMs(fetch->start))); + } + std::function completion = + std::move(fetch->completion); + fetch->completion = nullptr; + try { + completion(std::move(result)); + } catch (const std::exception& e) { + Logf("NativeScript: module fetch completion threw for %s: %s", + fetch->url.c_str(), e.what()); + } catch (...) { + Logf("NativeScript: module fetch completion threw for %s", + fetch->url.c_str()); + } +} + +// ── Retry timer, for transports that schedule themselves ──────────────────── + +class DelayedTasks { + public: + // False when the task could not be scheduled; it then never runs. + bool Post(milliseconds delay, std::function task) { + try { + std::lock_guard lock(mutex_); + if (!started_) { + std::thread([this] { Run(); }).detach(); + started_ = true; + } + tasks_.emplace(steady_clock::now() + delay, std::move(task)); + } catch (...) { + return false; + } + wake_.notify_one(); + return true; + } + + private: + void Run() { + std::unique_lock lock(mutex_); + for (;;) { + if (tasks_.empty()) { + wake_.wait(lock); + continue; + } + const auto due = tasks_.begin()->first; + if (steady_clock::now() < due) { + wake_.wait_until(lock, due); + continue; + } + std::function task = std::move(tasks_.begin()->second); + tasks_.erase(tasks_.begin()); + lock.unlock(); + try { + task(); + } catch (...) { + } + task = nullptr; + lock.lock(); + } + } + + std::mutex mutex_; + std::condition_variable wake_; + std::multimap> tasks_; + bool started_ = false; +}; + +DelayedTasks& Timer() { + static auto* timer = new DelayedTasks(); + return *timer; +} + +} // namespace + +void ModuleTransport::FetchAsync(AttemptRequest request, + std::function done) { + done(FetchBlocking(request)); +} + +bool ModuleTransport::PostDelayed(milliseconds delay, + std::function task) { + return Timer().Post(delay, std::move(task)); +} + +namespace { + +void StartSelfScheduledAttempt(const AsyncFetchPtr& fetch, int attempt); + +bool PostRetry(const AsyncFetchPtr& fetch) { + try { + return platform::HttpTransport().PostDelayed( + RetryDelay(), [fetch] { StartSelfScheduledAttempt(fetch, 1); }); + } catch (...) { + return false; + } +} + +// Runs on the transport's callback thread, or the caller's for an attempt that +// failed inline. A retry, once posted, owns the completion. +void OnSelfScheduledOutcome(const AsyncFetchPtr& fetch, int attempt, + AttemptOutcome outcome) { + ModuleFetchResult result; + try { + ApplyClearSiteData(fetch->url, fetch->useCache, outcome); + if (WantsRetry(*fetch, attempt, outcome) && PostRetry(fetch)) { + return; + } + JudgeOutcome(fetch->url, outcome, result); + } catch (...) { + result = InternalError(fetch->url); + } + Deliver(fetch, attempt, std::move(result)); +} + +void StartSelfScheduledAttempt(const AsyncFetchPtr& fetch, int attempt) { + const std::optional timeout = AttemptTimeout(fetch->deadline); + if (!timeout) { + Deliver(fetch, attempt, DeadlineExceeded(fetch->url)); + return; + } + // A transport that throws may or may not have taken the attempt; whichever + // of it and the throw comes first settles it. + auto settled = std::make_shared>(false); + std::function done = [fetch, attempt, + settled](AttemptOutcome outcome) { + if (!settled->exchange(true)) { + OnSelfScheduledOutcome(fetch, attempt, std::move(outcome)); + } + }; + AttemptRequest request = + MakeRequest(fetch->url, FetchPath::kGraphWalk, *timeout, fetch->useCache); + try { + platform::HttpTransport().FetchAsync(std::move(request), done); + } catch (const std::exception& e) { + done(TransportThrew(fetch->url, e.what())); + } catch (...) { + done(TransportThrew(fetch->url, "unknown exception")); + } +} + +// ── Fetch threads, for transports that block ──────────────────────────────── + +// One queue and thread count per ModuleFetchHostClass, under one mutex. +struct FetchLane { + std::deque queue; + size_t threadCount = 0; +}; + +struct FetchLanes { + std::mutex mutex; + FetchLane lanes[2]; + + FetchLane& For(ModuleFetchHostClass hostClass) { + return lanes[hostClass == ModuleFetchHostClass::kLoopback ? 0 : 1]; + } +}; + +FetchLanes& Lanes() { + static auto* lanes = new FetchLanes(); + return *lanes; +} + +// The retry sleeps on the fetch thread, holding its slot for the delay. +void RunLaneFetch(const AsyncFetchPtr& fetch) { + ModuleFetchResult result; + int attempt = 0; + try { + std::optional timeout = AttemptTimeout(fetch->deadline); + AttemptOutcome outcome; + if (timeout) { + outcome = FetchBlocking(MakeRequest(fetch->url, FetchPath::kGraphWalk, + *timeout, fetch->useCache)); + ApplyClearSiteData(fetch->url, fetch->useCache, outcome); + if (WantsRetry(*fetch, attempt, outcome)) { + std::this_thread::sleep_for(RetryDelay()); + attempt = 1; + timeout = AttemptTimeout(fetch->deadline); + if (timeout) { + outcome = FetchBlocking(MakeRequest(fetch->url, FetchPath::kGraphWalk, + *timeout, fetch->useCache)); + ApplyClearSiteData(fetch->url, fetch->useCache, outcome); + } + } + } + if (timeout) { + JudgeOutcome(fetch->url, outcome, result); + } else { + result = DeadlineExceeded(fetch->url); + } + } catch (...) { + result = InternalError(fetch->url); + } + Deliver(fetch, attempt, std::move(result)); +} + +// A fetch thread runs its own fetch and then drains its lane, so per-thread +// setup is paid once per thread and the cap bounds threads, not just sockets. +// The exit check and the decrement are ONE critical section: a producer that +// queues always observes, and is observed by, a thread that has not exited, so +// nothing queued is stranded behind a thread on its way out. +void FetchThreadMain(AsyncFetchPtr fetch) { + ModuleTransport& transport = platform::HttpTransport(); + try { + transport.OnFetchThreadStart(); + } catch (...) { + } + FetchLanes& lanes = Lanes(); + FetchLane& lane = lanes.For(fetch->hostClass); + for (;;) { + RunLaneFetch(fetch); + std::lock_guard lock(lanes.mutex); + if (lane.queue.empty()) { + lane.threadCount--; + break; + } + fetch = std::move(lane.queue.front()); + lane.queue.pop_front(); + } + try { + transport.OnFetchThreadExit(); + } catch (...) { + } +} + +void FailSpawn(const AsyncFetchPtr& fetch) { + ModuleFetchResult failed; + failed.failureReason = "Could not fetch " + fetch->url + + ": the runtime could not start a fetch thread"; + Tracef(TraceCategory::kEsm, "[http-loader][fetch-async][spawn-fail] %s", + fetch->url.c_str()); + Deliver(fetch, 0, std::move(failed)); +} + +void StartLaneFetch(const AsyncFetchPtr& fetch) { + const size_t cap = ModuleFetchConcurrency(fetch->hostClass); + FetchLanes& lanes = Lanes(); + FetchLane& lane = lanes.For(fetch->hostClass); + { + std::lock_guard lock(lanes.mutex); + if (lane.threadCount >= cap) { + lane.queue.push_back(fetch); + return; + } + lane.threadCount++; + } + + try { + std::thread(FetchThreadMain, fetch).detach(); + return; + } catch (...) { + } + + // A counted slot with no thread behind it: if it was the last, nothing is + // left to drain the queue, so what waits there fails now instead of never. + std::deque orphaned; + { + std::lock_guard lock(lanes.mutex); + lane.threadCount--; + if (lane.threadCount == 0) { + orphaned.swap(lane.queue); + } + } + FailSpawn(fetch); + for (const AsyncFetchPtr& orphan : orphaned) { + FailSpawn(orphan); + } +} + +} // namespace + +// ── Public API ────────────────────────────────────────────────────────────── + +bool ClearSiteDataClearsCache(const std::vector& values) { + for (const std::string& value : values) { + size_t start = 0; + while (start <= value.size()) { + const size_t comma = value.find(',', start); + const size_t end = comma == std::string::npos ? value.size() : comma; + const size_t first = value.find_first_not_of(" \t\r\n", start); + if (first != std::string::npos && first < end) { + const size_t last = value.find_last_not_of(" \t\r\n", end - 1); + const std::string directive = value.substr(first, last - first + 1); + if (directive == "\"cache\"" || directive == "\"*\"") { + return true; + } + } + if (comma == std::string::npos) { + break; + } + start = comma + 1; + } + } + return false; +} + +size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass) { + const size_t index = hostClass == ModuleFetchHostClass::kLoopback ? 0 : 1; + const size_t configured = State().config.fetchConcurrency[index]; + if (configured > 0) { + return configured; + } + return hostClass == ModuleFetchHostClass::kLoopback ? 6 : 32; +} + +bool IsRemoteModulesAllowed() { + const LoaderState& state = State(); + return state.config.isDebug || state.config.allowRemoteModules; +} + +bool IsRemoteUrlAllowed(const std::string& url) { + const LoaderState& state = State(); + if (state.config.isDebug) { + return true; + } + return state.config.allowRemoteModules && + RemoteUrlAllowedByAllowlist(url, state.allowlist); +} + +bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { + result = ModuleFetchResult(); + if (!IsRemoteUrlAllowed(url)) { + Block(url, result); + return false; + } + + const auto start = steady_clock::now(); + const bool useCache = ModuleHttpCacheEnabled(); + const milliseconds timeout = PolicyTimeout(); + AttemptOutcome outcome = SyncAttempt(url, timeout, useCache); + if (IsTransportError(outcome)) { + // An HTTP status is an answer, so only a transport error is retried, and + // an expired wait already blocked this thread longer than an attempt may + // take. + Tracef(TraceCategory::kEsm, + "[http-loader] retrying %s after initial fetch error", url.c_str()); + std::this_thread::sleep_for(RetryDelay()); + outcome = SyncAttempt(url, timeout, useCache); + } + + JudgeOutcome(url, outcome, result); + if (outcome.waitExpired) { + const auto waited = std::chrono::duration_cast( + timeout + SyncWaitMargin()); + result.ok = false; + result.body.clear(); + result.failureReason = "HTTP import failed: " + url + + " (no response within " + + std::to_string(waited.count()) + "s)"; + } + + if (!result.ok) { + Tracef(TraceCategory::kEsm, "[http-loader][fetch-sync][reject] %s", + result.failureReason.c_str()); + return false; + } + Tracef(TraceCategory::kEsm, + "[http-loader] fetched status=%d content-type=%s bytes=%llu", + result.status, + result.contentType.empty() ? "" : result.contentType.c_str(), + static_cast(result.body.size())); + Tracef(TraceCategory::kFetch, + "[http-loader][fetch][network] %s bytes=%lu ms=%llu", url.c_str(), + static_cast(result.body.size()), + static_cast(ElapsedMs(start))); + return true; +} + +void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline deadline, + std::function completion) { + if (!IsRemoteUrlAllowed(url)) { + ModuleFetchResult blocked; + Block(url, blocked); + completion(std::move(blocked)); + return; + } + + auto fetch = std::make_shared(); + fetch->url = url; + fetch->deadline = deadline; + fetch->useCache = ModuleHttpCacheEnabled(); + fetch->hostClass = ModuleFetchHostClassOf(url); + fetch->start = steady_clock::now(); + fetch->completion = std::move(completion); + + if (platform::HttpTransport().SchedulesItself()) { + StartSelfScheduledAttempt(fetch, 0); + } else { + StartLaneFetch(fetch); + } +} + +bool ModuleHttpCacheEnabled() { + LoaderState& state = State(); + std::lock_guard lock(state.cacheMutex); + return state.cacheSetting && state.cacheDisabledBy.empty(); +} + +void SetModuleHttpCacheEnabled(bool enabled) { + LoaderState& state = State(); + std::lock_guard lock(state.cacheMutex); + state.cacheSetting = enabled; +} + +void SetModuleHttpCacheDisabledBy(uint64_t holderId, bool disabled) { + LoaderState& state = State(); + std::lock_guard lock(state.cacheMutex); + if (disabled) { + state.cacheDisabledBy.insert(holderId); + } else { + state.cacheDisabledBy.erase(holderId); + } +} + +CacheOpResult ClearModuleHttpCache() { + try { + return platform::HttpTransport().ClearAll(); + } catch (const std::exception& e) { + return CacheOpResult{false, e.what()}; + } catch (...) { + return CacheOpResult{false, "could not clear the module HTTP cache"}; + } +} + +namespace testing { + +void SetTiming(const Timing& timing) { + g_debugTimeoutMs.store(timing.debugTimeout.count()); + g_releaseTimeoutMs.store(timing.releaseTimeout.count()); + g_retryDelayMs.store(timing.retryDelay.count()); + g_syncWaitMarginMs.store(timing.syncWaitMargin.count()); +} + +void Reset() { + std::lock_guard lock(StateMutex()); + delete g_state.exchange(nullptr, std::memory_order_acq_rel); + g_reportedMissingFinalUrl = false; +} + +} // namespace testing + +} // namespace nativescript::common::http diff --git a/tests/FakePlatform.cpp b/tests/FakePlatform.cpp index aa7ba4b..5f5b373 100644 --- a/tests/FakePlatform.cpp +++ b/tests/FakePlatform.cpp @@ -2,10 +2,14 @@ #include #include +#include #include +#include +#include #include #include "ns/Platform.h" +#include "ns/http/ModuleTransport.h" namespace { @@ -26,6 +30,11 @@ std::vector& Traced() { bool traceEnabled = true; +nativescript::common::http::HttpLoaderConfig& Config() { + static auto* config = new nativescript::common::http::HttpLoaderConfig(); + return *config; +} + bool StartsWith(const std::string& s, const char* prefix) { return s.rfind(prefix, 0) == 0; } @@ -55,6 +64,99 @@ void SetTraceEnabled(bool enabled) { traceEnabled = enabled; } +void SetConfig(const http::HttpLoaderConfig& config) { + std::lock_guard lock(Mutex()); + Config() = config; +} + +http::AttemptOutcome Ok(const std::string& url, const std::string& body) { + http::AttemptOutcome outcome; + outcome.arrived = true; + outcome.status = 200; + outcome.contentType = "text/javascript"; + outcome.body = body; + outcome.finalUrl = url; + return outcome; +} + +http::AttemptOutcome FakeTransport::Respond( + const http::AttemptRequest& request) { + Responder responder; + { + std::lock_guard lock(mutex_); + requests_.push_back(request); + responder = responder_; + } + return responder(request); +} + +http::AttemptOutcome FakeTransport::FetchBlocking( + const http::AttemptRequest& request) { + return Respond(request); +} + +void FakeTransport::FetchAsync(http::AttemptRequest request, + std::function done) { + if (throwFromFetchAsync) { + throw std::runtime_error("refused"); + } + std::thread([this, request = std::move(request), done = std::move(done)] { + done(Respond(request)); + }).detach(); +} + +http::CacheOpResult FakeTransport::ClearAll() { + clearAllCalls++; + if (!clearResult.ok && clearResult.error == "throw") { + throw std::runtime_error("disk full"); + } + return clearResult; +} + +http::CacheOpResult FakeTransport::ClearOrigin(const std::string& origin) { + std::lock_guard lock(mutex_); + clearedOrigins_.push_back(origin); + return http::CacheOpResult{}; +} + +void FakeTransport::Reset() { + std::lock_guard lock(mutex_); + requests_.clear(); + clearedOrigins_.clear(); + responder_ = [](const http::AttemptRequest& request) { + return Ok(request.url, "export {}"); + }; + schedulesItself = false; + throwFromFetchAsync = false; + clearAllCalls = 0; + postDelayedCalls = 0; + clearResult = http::CacheOpResult{}; +} + +std::vector FakeTransport::Requests() { + std::lock_guard lock(mutex_); + return requests_; +} + +std::vector FakeTransport::ClearedOrigins() { + std::lock_guard lock(mutex_); + return clearedOrigins_; +} + +void FakeTransport::SetResponder(Responder responder) { + std::lock_guard lock(mutex_); + responder_ = std::move(responder); +} + +FakeTransport& Transport() { + static auto* transport = [] { + auto* t = new FakeTransport(); + t->Reset(); + return t; + }(); + return *transport; +} + } // namespace fake_platform namespace nativescript::common::platform { @@ -108,3 +210,14 @@ std::string HttpUrlOrigin(const std::string& url) { } } // namespace nativescript::common::platform + +namespace nativescript::common::platform { + +http::HttpLoaderConfig ReadHttpLoaderConfig() { + std::lock_guard lock(Mutex()); + return Config(); +} + +http::ModuleTransport& HttpTransport() { return fake_platform::Transport(); } + +} // namespace nativescript::common::platform diff --git a/tests/FakePlatform.h b/tests/FakePlatform.h index 8b488f9..4a4519d 100644 --- a/tests/FakePlatform.h +++ b/tests/FakePlatform.h @@ -1,19 +1,83 @@ #ifndef NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ #define NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ +#include +#include +#include +#include #include +#include #include -// The host tests' stand-in for a runtime's platform functions (ns/Platform.h). +#include "ns/http/ModuleTransport.h" + +// The host tests' stand-in for a runtime's platform functions (ns/Platform.h, +// ns/http/ModuleTransport.h). namespace fake_platform { -// Every Log() and enabled Trace() message, in order. Not thread-safe to read -// while fetches are in flight. +namespace http = nativescript::common::http; + +// Every Log() and enabled Trace() message, in order. std::vector LoggedMessages(); std::vector TracedMessages(); void ClearMessages(); void SetTraceEnabled(bool enabled); +// Returned by platform::ReadHttpLoaderConfig() from the next read on. +void SetConfig(const http::HttpLoaderConfig& config); + +class FakeTransport : public http::ModuleTransport { + public: + using Responder = + std::function; + + const char* Name() const override { return "fake"; } + http::AttemptOutcome FetchBlocking( + const http::AttemptRequest& request) override; + bool SchedulesItself() const override { return schedulesItself; } + // Answers on a thread of its own. + void FetchAsync(http::AttemptRequest request, + std::function done) override; + bool PostDelayed(std::chrono::milliseconds delay, + std::function task) override { + postDelayedCalls++; + return http::ModuleTransport::PostDelayed(delay, std::move(task)); + } + http::CacheOpResult ClearAll() override; + http::CacheOpResult ClearOrigin(const std::string& origin) override; + void OnFetchThreadStart() override { threadStarts++; } + void OnFetchThreadExit() override { threadExits++; } + + // Forgets every request and clear, and answers 200 text/javascript. + void Reset(); + std::vector Requests(); + std::vector ClearedOrigins(); + + std::atomic schedulesItself{false}; + std::atomic throwFromFetchAsync{false}; + std::atomic clearAllCalls{0}; + std::atomic postDelayedCalls{0}; + std::atomic threadStarts{0}; + std::atomic threadExits{0}; + http::CacheOpResult clearResult; + + // Called for every attempt, on the thread that performs it. + void SetResponder(Responder responder); + + private: + http::AttemptOutcome Respond(const http::AttemptRequest& request); + + std::mutex mutex_; + Responder responder_; + std::vector requests_; + std::vector clearedOrigins_; +}; + +FakeTransport& Transport(); + +// A 2xx JavaScript response that arrived from `url`. +http::AttemptOutcome Ok(const std::string& url, const std::string& body); + } // namespace fake_platform #endif // NATIVESCRIPT_COMMON_TESTS_FAKE_PLATFORM_H_ diff --git a/tests/HttpFetchTest.cpp b/tests/HttpFetchTest.cpp new file mode 100644 index 0000000..58c761e --- /dev/null +++ b/tests/HttpFetchTest.cpp @@ -0,0 +1,565 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FakePlatform.h" +#include "http/Internal.h" +#include "ns/http/ModuleFetch.h" + +using namespace nativescript::common::http; +using fake_platform::Ok; +using fake_platform::Transport; +using std::chrono::milliseconds; +using std::chrono::steady_clock; + +namespace { + +int failures = 0; + +void Check(bool ok, const char* what, const std::string& detail = "") { + if (!ok) { + failures++; + std::fprintf(stderr, "FAIL %s: \"%s\"\n", what, detail.c_str()); + } +} + +void ExpectEqual(const std::string& actual, const std::string& expected, + const char* what) { + if (actual != expected) { + failures++; + std::fprintf(stderr, "FAIL %s:\n actual: \"%s\"\n expected: \"%s\"\n", + what, actual.c_str(), expected.c_str()); + } +} + +HttpLoaderConfig DebugConfig() { + HttpLoaderConfig config; + config.isDebug = true; + return config; +} + +HttpLoaderConfig ReleaseConfig( + bool allowRemoteModules, + std::optional>> allowlist = + std::nullopt) { + HttpLoaderConfig config; + config.allowRemoteModules = allowRemoteModules; + config.remoteModuleAllowlist = std::move(allowlist); + return config; +} + +// Fresh loader state, fake transport and timing scaled down so retries and +// waits take milliseconds. +void Start(const HttpLoaderConfig& config) { + fake_platform::SetConfig(config); + testing::Reset(); + testing::Timing timing; + timing.retryDelay = milliseconds(20); + testing::SetTiming(timing); + Transport().Reset(); + fake_platform::ClearMessages(); +} + +AttemptOutcome TransportError() { + AttemptOutcome outcome; + outcome.errorDescription = "connection refused"; + return outcome; +} + +// The result of an async fetch, and how many times its completion ran. +struct AsyncResult { + ModuleFetchResult result; + int completions = 0; +}; + +AsyncResult FetchAsync(const std::string& url, + ModuleFetchDeadline deadline = std::nullopt) { + struct Shared { + std::mutex mutex; + std::condition_variable cv; + AsyncResult value; + }; + auto shared = std::make_shared(); + FetchModuleBodyAsync(url, deadline, [shared](ModuleFetchResult result) { + std::lock_guard lock(shared->mutex); + shared->value.result = std::move(result); + shared->value.completions++; + shared->cv.notify_all(); + }); + std::unique_lock lock(shared->mutex); + shared->cv.wait_for(lock, std::chrono::seconds(10), + [&] { return shared->value.completions > 0; }); + lock.unlock(); + // A second completion would land within this window. + std::this_thread::sleep_for(milliseconds(50)); + lock.lock(); + return shared->value; +} + +bool HasHeader(const AttemptRequest& request, const std::string& name, + const std::string& value) { + return std::any_of(request.headers.begin(), request.headers.end(), + [&](const RequestHeader& header) { + return header.name == name && header.value == value; + }); +} + +bool HasHeaderNamed(const AttemptRequest& request, const std::string& name) { + return std::any_of( + request.headers.begin(), request.headers.end(), + [&](const RequestHeader& header) { return header.name == name; }); +} + +// ── Gate ──────────────────────────────────────────────────────────────────── + +void TestGateRelease() { + Start(ReleaseConfig(false)); + Check(!IsRemoteModulesAllowed(), "release default-denies remote modules"); + ModuleFetchResult result; + Check(!HttpFetchModule("https://cdn.example.com/a.js", result), + "release blocks sync"); + Check(result.status == 403, "blocked is 403"); + ExpectEqual(result.failureReason, + "HTTP import blocked: remote module loading is not allowed for " + "https://cdn.example.com/a.js", + "blocked text"); + AsyncResult async = FetchAsync("https://cdn.example.com/a.js"); + Check(async.completions == 1 && async.result.status == 403, + "release blocks async"); + Check(Transport().Requests().empty(), "blocked fetches never reach the net"); + + Start(ReleaseConfig(true)); + Check(IsRemoteModulesAllowed(), "allowRemoteModules enables"); + Check(HttpFetchModule("https://any.example/a.js", result), + "no allowlist allows any URL", result.failureReason); + + Start(ReleaseConfig(true, std::vector>{ + std::string("https://cdn.example.com")})); + Check(IsRemoteUrlAllowed("https://cdn.example.com/a.js"), "listed allowed"); + Check(!IsRemoteUrlAllowed("https://cdn.example.com.evil/a.js"), + "lookalike refused"); + Check(!HttpFetchModule("https://other.example/a.js", result) && + result.status == 403, + "unlisted blocked"); + Check(HttpFetchModule("https://cdn.example.com/a.js", result), + "listed fetched", result.failureReason); + + Start(DebugConfig()); + Check(IsRemoteUrlAllowed("https://anything.example/a.js"), + "debug always allows"); +} + +void TestRedirectGate() { + const auto allowlisted = + ReleaseConfig(true, std::vector>{ + std::string("https://cdn.example.com")}); + ModuleFetchResult result; + + Start(allowlisted); + Transport().SetResponder([](const AttemptRequest&) { + return Ok("https://evil.example/x.js", "export {}"); + }); + Check(!HttpFetchModule("https://cdn.example.com/a.js", result), + "redirect off the allowlist is blocked"); + Check(result.status == 403, "redirect block is 403"); + ExpectEqual(result.failureReason, + "HTTP import blocked: remote module loading is not allowed for " + "https://evil.example/x.js (redirected from " + "https://cdn.example.com/a.js)", + "redirect block text"); + AsyncResult async = FetchAsync("https://cdn.example.com/a.js"); + Check(!async.result.ok && async.result.status == 403, + "async redirect off the allowlist is blocked"); + + Transport().SetResponder( + [](const AttemptRequest&) { return Ok("", "export {}"); }); + Check(!HttpFetchModule("https://cdn.example.com/a.js", result), + "unreported final URL fails closed"); + const auto logged = fake_platform::LoggedMessages(); + Check(logged.size() == 1 && + logged[0].find("did not report the final URL") != std::string::npos, + "an unreported final URL is logged once"); + HttpFetchModule("https://cdn.example.com/a.js", result); + Check(fake_platform::LoggedMessages().size() == 1, "logged only once"); + + Transport().SetResponder([](const AttemptRequest&) { + return Ok("https://CDN.example.com/b.js", "export {}"); + }); + Check(HttpFetchModule("https://cdn.example.com/a.js", result), + "redirect within the allowlist is allowed", result.failureReason); + + Start(DebugConfig()); + Transport().SetResponder([](const AttemptRequest&) { + return Ok("https://evil.example/x.js", "export {}"); + }); + Check(HttpFetchModule("https://cdn.example.com/a.js", result), + "debug follows any redirect", result.failureReason); + + Start(ReleaseConfig(true)); + Transport().SetResponder( + [](const AttemptRequest&) { return Ok("", "export {}"); }); + Check(HttpFetchModule("https://cdn.example.com/a.js", result), + "no allowlist needs no final URL", result.failureReason); +} + +// ── Requests ──────────────────────────────────────────────────────────────── + +void TestRequestShape() { + Start(DebugConfig()); + ModuleFetchResult result; + HttpFetchModule("http://localhost:5173/a.js", result); + FetchAsync("http://localhost:5173/b.js"); + std::vector requests = Transport().Requests(); + Check(requests.size() == 2, "one attempt each"); + for (const AttemptRequest& request : requests) { + Check(HasHeader(request, "Accept", + "application/javascript, text/javascript, */*;q=0.1"), + "Accept", request.url); + Check(HasHeader(request, "Accept-Encoding", "identity"), "Accept-Encoding", + request.url); + Check(HasHeader(request, "User-Agent", "NativeScript-HTTP-ESM"), + "User-Agent", request.url); + Check(!HasHeaderNamed(request, "Cache-Control") && + !HasHeaderNamed(request, "Pragma"), + "no no-cache pair while cached", request.url); + Check(request.useCache, "cached", request.url); + Check(request.timeout == milliseconds(30000), "debug timeout", request.url); + } + Check(requests[0].path == FetchPath::kSynchronousFallback && + requests[0].waitBound == milliseconds(35000), + "sync path waits timeout + margin"); + Check(requests[1].path == FetchPath::kGraphWalk, "async path"); + + Start(ReleaseConfig(true)); + SetModuleHttpCacheEnabled(false); + HttpFetchModule("https://cdn.example.com/a.js", result); + requests = Transport().Requests(); + Check(requests.size() == 1 && requests[0].timeout == milliseconds(5000), + "release timeout"); + Check(!requests[0].useCache && + HasHeader(requests[0], "Cache-Control", "no-cache") && + HasHeader(requests[0], "Pragma", "no-cache"), + "uncached carries the no-cache pair"); +} + +// ── Synchronous retry ─────────────────────────────────────────────────────── + +void TestSyncRetry() { + Start(DebugConfig()); + ModuleFetchResult result; + std::atomic calls{0}; + Transport().SetResponder([&](const AttemptRequest& request) { + return calls++ == 0 ? TransportError() : Ok(request.url, "export {}"); + }); + Check(HttpFetchModule("http://h/a.js", result), "transport error retried", + result.failureReason); + Check(calls == 2, "one retry"); + + calls = 0; + Transport().SetResponder([&](const AttemptRequest&) { + calls++; + return TransportError(); + }); + Check(!HttpFetchModule("http://h/a.js", result), "second error fails"); + Check(calls == 2, "only one retry"); + ExpectEqual(result.failureReason, + "HTTP import failed: http://h/a.js (network error)", + "network error text"); + + calls = 0; + Transport().SetResponder([&](const AttemptRequest& request) { + calls++; + AttemptOutcome outcome = Ok(request.url, ""); + outcome.status = 500; + return outcome; + }); + Check(!HttpFetchModule("http://h/a.js", result) && calls == 1, + "an HTTP status is not retried"); + + calls = 0; + Transport().SetResponder([&](const AttemptRequest&) { + calls++; + AttemptOutcome outcome; + outcome.waitExpired = true; + return outcome; + }); + Check(!HttpFetchModule("http://h/a.js", result) && calls == 1, + "an expired wait is not retried"); + ExpectEqual(result.failureReason, + "HTTP import failed: http://h/a.js (no response within 35s)", + "expired wait text"); + const auto logged = fake_platform::LoggedMessages(); + Check(!logged.empty() && + logged.back() == + "NativeScript: synchronous module fetch of http://h/a.js got " + "no response within 35s", + "expired wait is logged"); + + calls = 0; + Transport().SetResponder([&](const AttemptRequest&) { + calls++; + AttemptOutcome outcome; + outcome.malformedUrl = true; + return outcome; + }); + Check(!HttpFetchModule("http://h/a.js", result) && calls == 1, + "a malformed URL is not retried"); + ExpectEqual(result.failureReason, + "HTTP import failed: http://h/a.js (malformed request URL)", + "malformed text"); + + calls = 0; + Transport().SetResponder( + [&](const AttemptRequest& request) -> AttemptOutcome { + if (calls++ == 0) { + throw std::runtime_error("jni"); + } + return Ok(request.url, "export {}"); + }); + Check(HttpFetchModule("http://h/a.js", result) && calls == 2, + "a throwing transport is a retried transport error", + result.failureReason); +} + +// ── Asynchronous fetches, both scheduling modes ───────────────────────────── + +void TestAsync(bool schedulesItself) { + const char* mode = schedulesItself ? "self-scheduled" : "lanes"; + Start(DebugConfig()); + Transport().schedulesItself = schedulesItself; + + AsyncResult r = FetchAsync("http://h/a.js"); + Check(r.completions == 1 && r.result.ok && r.result.body == "export {}", + "async fetch", mode); + + std::atomic calls{0}; + Transport().SetResponder([&](const AttemptRequest& request) { + return calls++ == 0 ? TransportError() : Ok(request.url, "export {}"); + }); + r = FetchAsync("http://h/a.js"); + Check(r.completions == 1 && r.result.ok && calls == 2, + "async retries a transport error once", mode); + Check(Transport().postDelayedCalls == (schedulesItself ? 1 : 0), + "a self-scheduling transport times the retry delay", mode); + + calls = 0; + Transport().SetResponder([&](const AttemptRequest&) { + calls++; + return TransportError(); + }); + r = FetchAsync("http://h/a.js"); + Check(r.completions == 1 && !r.result.ok && calls == 2, + "async gives up after one retry", mode); + ExpectEqual(r.result.failureReason, + "HTTP import failed: http://h/a.js (network error)", mode); + + calls = 0; + r = FetchAsync("http://h/a.js", steady_clock::now() - milliseconds(1)); + Check(r.completions == 1 && calls == 0, "no attempt past the deadline", mode); + ExpectEqual(r.result.failureReason, + "HTTP import failed: http://h/a.js (module graph fetch deadline " + "exceeded)", + mode); + + // A budget shorter than the retry delay: no retry. + calls = 0; + r = FetchAsync("http://h/a.js", steady_clock::now() + milliseconds(10)); + Check(r.completions == 1 && calls == 1, "no retry past the deadline", mode); + + Transport().Reset(); + Transport().schedulesItself = schedulesItself; + r = FetchAsync("http://h/a.js", steady_clock::now() + milliseconds(1500)); + const auto requests = Transport().Requests(); + Check(requests.size() == 1 && requests[0].timeout <= milliseconds(1500) && + requests[0].timeout > milliseconds(1000), + "attempt timeout clamps to the deadline", mode); + + std::atomic completionCalls{0}; + FetchModuleBodyAsync("http://h/a.js", std::nullopt, [&](ModuleFetchResult) { + completionCalls++; + throw std::runtime_error("posted to a dead loop"); + }); + for (int i = 0; i < 200 && completionCalls == 0; i++) { + std::this_thread::sleep_for(milliseconds(5)); + } + std::this_thread::sleep_for(milliseconds(20)); + Check(completionCalls == 1, "a throwing completion is contained", mode); +} + +void TestSelfScheduledThrow() { + Start(DebugConfig()); + Transport().schedulesItself = true; + Transport().throwFromFetchAsync = true; + AsyncResult r = FetchAsync("http://h/a.js"); + Check(r.completions == 1 && !r.result.ok, + "FetchAsync throwing still completes once"); +} + +// ── Fetch thread caps ─────────────────────────────────────────────────────── + +void TestLaneCap() { + HttpLoaderConfig config = DebugConfig(); + config.fetchConcurrency[0] = 2; + Start(config); + Check(ModuleFetchConcurrency(ModuleFetchHostClass::kLoopback) == 2, + "configured loopback cap"); + Check(ModuleFetchConcurrency(ModuleFetchHostClass::kRemote) == 32, + "default remote cap"); + + std::atomic inFlight{0}; + std::atomic maxInFlight{0}; + Transport().SetResponder([&](const AttemptRequest& request) { + const int now = ++inFlight; + int seen = maxInFlight.load(); + while (now > seen && !maxInFlight.compare_exchange_weak(seen, now)) { + } + std::this_thread::sleep_for(milliseconds(20)); + inFlight--; + return Ok(request.url, "export {}"); + }); + + const int starts = Transport().threadStarts; + std::atomic done{0}; + for (int i = 0; i < 8; i++) { + FetchModuleBodyAsync("http://localhost/" + std::to_string(i) + ".js", + std::nullopt, [&](ModuleFetchResult) { done++; }); + } + for (int i = 0; i < 400 && done < 8; i++) { + std::this_thread::sleep_for(milliseconds(5)); + } + Check(done == 8, "every queued fetch completes"); + Check(maxInFlight <= 2, "loopback lane honours its cap", + std::to_string(maxInFlight.load())); + Check(Transport().threadStarts - starts <= 2, "threads bounded by the cap"); + for (int i = 0; + i < 200 && Transport().threadExits != Transport().threadStarts; i++) { + std::this_thread::sleep_for(milliseconds(5)); + } + Check(Transport().threadExits == Transport().threadStarts, + "fetch threads run their exit hook"); +} + +// ── Cache ─────────────────────────────────────────────────────────────────── + +void TestCacheSwitch() { + HttpLoaderConfig config = DebugConfig(); + config.moduleHttpCacheAtStartup = false; + Start(config); + Check(!ModuleHttpCacheEnabled(), "startup setting off"); + SetModuleHttpCacheEnabled(true); + Check(ModuleHttpCacheEnabled(), "setter wins over startup"); + + SetModuleHttpCacheDisabledBy(1, true); + SetModuleHttpCacheDisabledBy(1, true); + SetModuleHttpCacheDisabledBy(2, true); + Check(!ModuleHttpCacheEnabled(), "holders disable"); + SetModuleHttpCacheDisabledBy(1, false); + Check(!ModuleHttpCacheEnabled(), "another holder still disables"); + SetModuleHttpCacheDisabledBy(2, false); + Check(ModuleHttpCacheEnabled(), "idempotent per holder"); + + // Sampled when the fetch is issued. + std::atomic release{false}; + Transport().schedulesItself = false; + Transport().SetResponder([&](const AttemptRequest& request) { + while (!release) { + std::this_thread::sleep_for(milliseconds(1)); + } + return Ok(request.url, "export {}"); + }); + std::atomic done{0}; + FetchModuleBodyAsync("http://h/a.js", std::nullopt, + [&](ModuleFetchResult) { done++; }); + SetModuleHttpCacheEnabled(false); + release = true; + for (int i = 0; i < 400 && done == 0; i++) { + std::this_thread::sleep_for(milliseconds(5)); + } + const auto requests = Transport().Requests(); + Check(requests.size() == 1 && requests[0].useCache, + "in-flight fetch keeps the switch it was issued with"); + + Transport().clearResult = CacheOpResult{false, "permission denied"}; + CacheOpResult cleared = ClearModuleHttpCache(); + Check(!cleared.ok && cleared.error == "permission denied" && + Transport().clearAllCalls == 1, + "clear failures are reported"); + Transport().clearResult = CacheOpResult{false, "throw"}; + cleared = ClearModuleHttpCache(); + Check(!cleared.ok && cleared.error == "disk full", + "a throwing clear is reported"); +} + +void TestClearSiteData() { + Check(ClearSiteDataClearsCache({"\"cookies\", \"cache\""}), "listed cache"); + Check(ClearSiteDataClearsCache({"\"storage\"", " \"*\" "}), + "wildcard on a second header line"); + Check(!ClearSiteDataClearsCache({"cache", "\"cookies\",,"}), + "unquoted or other directives"); + + Start(DebugConfig()); + Transport().SetResponder([](const AttemptRequest&) { + AttemptOutcome outcome = Ok("https://cdn.example.com/x.js", "export {}"); + outcome.clearSiteData = {"\"cache\""}; + return outcome; + }); + ModuleFetchResult result; + HttpFetchModule("http://localhost:5173/a.js", result); + auto origins = Transport().ClearedOrigins(); + Check(origins.size() == 2 && origins[0] == "https://cdn.example.com" && + origins[1] == "http://localhost:5173", + "clears the response and the fetching origin"); + + Transport().Reset(); + Transport().SetResponder([](const AttemptRequest& request) { + AttemptOutcome outcome = Ok(request.url, "export {}"); + outcome.clearSiteData = {"\"*\""}; + return outcome; + }); + FetchAsync("http://localhost:5173/a.js"); + origins = Transport().ClearedOrigins(); + Check(origins.size() == 1 && origins[0] == "http://localhost:5173", + "each origin once"); + + Transport().Reset(); + SetModuleHttpCacheEnabled(false); + Transport().SetResponder([](const AttemptRequest&) { + AttemptOutcome outcome = Ok("https://cdn.example.com/x.js", "export {}"); + outcome.clearSiteData = {"\"cache\""}; + return outcome; + }); + HttpFetchModule("http://localhost:5173/a.js", result); + origins = Transport().ClearedOrigins(); + Check(origins.size() == 1 && origins[0] == "https://cdn.example.com", + "uncached fetch stored nothing under its own origin"); +} + +} // namespace + +int main() { + TestGateRelease(); + TestRedirectGate(); + TestRequestShape(); + TestSyncRetry(); + TestAsync(false); + TestAsync(true); + TestSelfScheduledThrow(); + TestLaneCap(); + TestCacheSwitch(); + TestClearSiteData(); + if (failures > 0) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::printf("all HTTP fetch tests passed\n"); + return 0; +}