From 48eea66d540c4921c447bebab1811f40ed177cd5 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:13:05 +0100 Subject: [PATCH 1/8] Reformat the C++ sources with clang-format (#653) Behavior-neutral: each file follows the .clang-format of its directory. Generated embedded asset headers and the gzip fixtures are untouched. --- examples/host-loop/BoingCuda.cu | 4 +- examples/host-loop/BoingHost.hpp | 2 +- examples/host-loop/HostLoop.cpp | 45 +- examples/life/LifeDeveloper.cpp | 4 +- examples/life/LifeDeveloperOptions.hpp | 6 +- examples/life/LifeEmbedded.cpp | 2 +- examples/life/react/LifeReact.cpp | 5 +- examples/life/react/LifeReact.hpp | 2 +- include/webfront/BridgeError.hpp | 2 +- include/webfront/Commands.hpp | 28 +- include/webfront/DeferredCalls.hpp | 10 +- include/webfront/DeveloperApp.hpp | 11 +- include/webfront/JsFunction.hpp | 15 +- include/webfront/JsFunctionSender.hpp | 22 +- include/webfront/ReadBinding.hpp | 191 +- include/webfront/Task.hpp | 2 +- include/webfront/UIThread.hpp | 20 +- include/webfront/ViewAssociation.hpp | 26 +- include/webfront/WebFront.hpp | 294 +- include/webfront/automation/Binding.hpp | 8 +- include/webfront/automation/Channel.hpp | 18 +- include/webfront/automation/Contract.hpp | 11 +- include/webfront/automation/Discovery.hpp | 45 +- include/webfront/automation/Enable.hpp | 40 +- include/webfront/automation/Mcp.hpp | 9 +- include/webfront/automation/McpHttp.hpp | 114 +- .../automation/PageAuthentication.hpp | 2 +- include/webfront/automation/Session.hpp | 11 +- include/webfront/components/forms/Form.hpp | 8 +- .../webfront/components/forms/Reflection.hpp | 2 +- include/webfront/components/react/Store.hpp | 4 +- include/webfront/details/C++20Support.hpp | 118 +- include/webfront/details/C++23Support.hpp | 28 +- include/webfront/dom/Document.hpp | 16 +- include/webfront/frontend/CEF.hpp | 119 +- include/webfront/frontend/Capture.hpp | 2 +- include/webfront/frontend/CloseRequest.hpp | 19 +- include/webfront/frontend/DefaultBrowser.hpp | 8 +- include/webfront/frontend/Downloads.hpp | 15 +- .../webfront/frontend/EmbeddedFrontend.hpp | 36 +- include/webfront/frontend/Frontend.hpp | 78 +- include/webfront/frontend/NativeWebView.hpp | 2 +- include/webfront/frontend/NativeWindow.hpp | 4 +- include/webfront/frontend/ProfileLease.hpp | 17 +- include/webfront/frontend/StartupTrace.hpp | 19 +- include/webfront/frontend/UIExecutor.hpp | 30 +- include/webfront/frontend/UILoop.hpp | 85 +- include/webfront/frontend/WKWebView.hpp | 145 +- include/webfront/frontend/WebKitGTK.hpp | 190 +- include/webfront/frontend/WebKitGTKPolicy.hpp | 24 +- include/webfront/frontend/WebView2.hpp | 235 +- include/webfront/frontend/Window.hpp | 20 +- include/webfront/frontend/WindowRegistry.hpp | 33 +- include/webfront/http/BlockingWorker.hpp | 56 +- include/webfront/http/BuffersPolicy.hpp | 46 +- include/webfront/http/Encodings.hpp | 198 +- include/webfront/http/HTTPServer.hpp | 571 ++-- include/webfront/http/MimeType.hpp | 33 +- include/webfront/http/Ranges.hpp | 55 +- include/webfront/http/WebSocket.hpp | 299 +- .../webfront/networking/NetworkingMock.hpp | 74 +- .../networking/TCPNetworkingStdnet.hpp | 15 +- include/webfront/networking/TCPSockets.hpp | 97 +- include/webfront/networking/Tasks.hpp | 2 +- include/webfront/system/DefaultFS.hpp | 16 +- include/webfront/system/DeveloperFS.hpp | 2 +- include/webfront/system/DeveloperFiles.hpp | 2 +- include/webfront/system/DeveloperJournal.hpp | 47 +- include/webfront/system/DeveloperPaths.hpp | 15 +- include/webfront/system/DeveloperStore.hpp | 68 +- include/webfront/system/FileSystem.hpp | 97 +- include/webfront/system/FontStacks.hpp | 22 +- include/webfront/system/IndexFS.hpp | 27 +- include/webfront/system/MemoryStorage.hpp | 6 +- include/webfront/system/NativeFS.hpp | 9 +- include/webfront/system/NativeStorage.hpp | 54 +- include/webfront/system/Storage.hpp | 2 +- include/webfront/system/WindowsCompat.hpp | 56 +- include/webfront/testing/Bdd.hpp | 16 +- include/webfront/testing/Process.hpp | 2 +- include/webfront/tls/Server.hpp | 45 +- include/webfront/tooling/HexDump.hpp | 29 +- include/webfront/tooling/Logger.hpp | 220 +- include/webfront/tooling/PathUtils.hpp | 44 +- include/webfront/utils/Sha256.hpp | 4 +- include/webfront/utils/TypeErasedFunction.hpp | 81 +- include/webfront/weblink/Messages.hpp | 68 +- include/webfront/weblink/WebLink.hpp | 209 +- test/cmake/bdd-consumer/main.cpp | 28 +- test/cmake/consumer/main.cpp | 14 +- test/driver/RequestLog.hpp | 7 +- test/driver/TestFrontend.hpp | 8 +- test/driver/WfDriver.hpp | 24 +- test/fuzz/MessagesFuzz.cpp | 2 +- test/unit/AcceptEncodingTests.cpp | 348 +-- test/unit/ApplicationTaskTests.cpp | 392 +-- test/unit/ApplicationUrlTests.cpp | 64 +- test/unit/AutomationChannelTests.cpp | 251 +- test/unit/AutomationDiscoveryTests.cpp | 931 +++--- test/unit/AutomationMcpHttpTests.cpp | 1246 ++++---- test/unit/AutomationTests.cpp | 1135 ++++---- test/unit/BddDiscoveryProbe.cpp | 8 +- test/unit/BddSelfTest.cpp | 18 +- test/unit/BroadcastTests.cpp | 864 +++--- test/unit/CEFMacrosTests.cpp | 12 +- test/unit/CEFPathsTests.cpp | 42 +- test/unit/CommandsTests.cpp | 789 ++--- test/unit/ContentPolicyTests.cpp | 268 +- test/unit/DefaultFSTests.cpp | 134 +- test/unit/DeferredCallTests.cpp | 465 +-- test/unit/DeveloperTests.cpp | 1993 +++++++------ test/unit/DomBatchTests.cpp | 282 +- test/unit/DomDocumentTests.cpp | 1362 ++++----- test/unit/DownloadsTests.cpp | 288 +- test/unit/EmbeddedAssetChecks.hpp | 2 +- test/unit/EmbeddedCoreAssetsTests.cpp | 32 +- test/unit/EncodingsTests.cpp | 273 +- test/unit/FileSystemTests.cpp | 213 +- test/unit/FormsReflectionTests.cpp | 110 +- test/unit/FormsTests.cpp | 938 +++--- test/unit/FrontendContractTests.cpp | 2570 +++++++++-------- test/unit/FrontendUrlTests.cpp | 192 +- test/unit/GzipExecutorTests.cpp | 975 +++---- test/unit/GzipTests.cpp | 876 +++--- test/unit/HTTPEncodingTests.cpp | 557 ++-- test/unit/HTTPRangeTests.cpp | 833 +++--- test/unit/HTTPRoutesTests.cpp | 1628 ++++++----- test/unit/HTTPServerTests.cpp | 899 +++--- test/unit/HostLoopTests.cpp | 942 +++--- test/unit/HostTests.cpp | 956 +++--- test/unit/IndexFSTests.cpp | 152 +- test/unit/InjectableNetworking.hpp | 91 +- test/unit/JSFunctionTests.cpp | 156 +- test/unit/JasmineConsumerTests.cpp | 1086 +++---- test/unit/JsFunctionSenderTests.cpp | 739 ++--- test/unit/LifeTests.cpp | 210 +- test/unit/LoggerTests.cpp | 649 +++-- test/unit/MddlogLoggerTests.cpp | 335 ++- test/unit/MddlogTransportTests.cpp | 629 ++-- test/unit/MessagesTests.cpp | 1814 ++++++------ test/unit/MimeTypeTests.cpp | 86 +- test/unit/Mocks.hpp | 12 +- test/unit/ModuleHTTPServerTests.cpp | 101 +- test/unit/NativeFSTests.cpp | 615 ++-- test/unit/NativeStorageTests.cpp | 2091 +++++++------- test/unit/NativeWindowTests.cpp | 310 +- test/unit/ProfileLeaseTests.cpp | 230 +- test/unit/PtyTests.cpp | 9 +- test/unit/ReactStoreTests.cpp | 316 +- test/unit/ReadBindingTests.cpp | 1356 +++++---- test/unit/SafePathTests.cpp | 40 +- test/unit/StdnetShutdownTests.cpp | 718 ++--- test/unit/StorageTests.cpp | 682 ++--- test/unit/StructuredShutdownTests.cpp | 102 +- test/unit/TlsTests.cpp | 36 +- test/unit/TypeErasedFunctionTests.cpp | 130 +- test/unit/UIExecutorTests.cpp | 1317 +++++---- test/unit/UISubscribersTests.cpp | 212 +- test/unit/ViewAssociationTests.cpp | 355 +-- test/unit/WebFrontTests.cpp | 1821 ++++++------ test/unit/WebKitGTKPolicyTests.cpp | 204 +- test/unit/WebLinkTests.cpp | 1030 +++---- test/unit/WebSocketTests.cpp | 1216 ++++---- test/unit/WebView2Tests.cpp | 664 +++-- test/unit/WfDriverTests.cpp | 270 +- test/unit/WindowRegistryTests.cpp | 686 +++-- test/web/AutomationHost.cpp | 23 +- test/web/CEFContentPolicy.cpp | 6 +- test/web/CEFFileServices.cpp | 14 +- test/web/DeveloperTest.cpp | 4 +- test/web/FrontendLifecycle.cpp | 231 +- test/web/JasmineTest.cpp | 261 +- test/web/MultiInstance.cpp | 4 +- test/web/NativeIntegrationManual.cpp | 8 +- test/web/RejectedWebSocketServer.hpp | 15 +- test/web/TransportBenchmark.hpp | 2 +- test/web/WKWebViewLifecycle.cpp | 138 +- test/web/WebKitGTKLifecycle.cpp | 127 +- test/web/WebKitGTKTransportBenchmark.cpp | 11 +- test/web/WebView2Lifecycle.cpp | 118 +- test/web/WebView2TransportBenchmark.cpp | 4 +- 181 files changed, 26456 insertions(+), 22744 deletions(-) diff --git a/examples/host-loop/BoingCuda.cu b/examples/host-loop/BoingCuda.cu index 92cdb998..5eccd5c3 100644 --- a/examples/host-loop/BoingCuda.cu +++ b/examples/host-loop/BoingCuda.cu @@ -25,8 +25,8 @@ const char* failure(cudaError_t status) { } // namespace const char* cudaDevice() { - static char name[256] = ""; - int count = 0; + static char name[256] = ""; + int count = 0; cudaDeviceProp properties; if (name[0] == '\0' && cudaGetDeviceCount(&count) == cudaSuccess && count > 0 && cudaGetDeviceProperties(&properties, 0) == cudaSuccess) for (std::size_t i = 0; i + 1 < sizeof name && properties.name[i] != '\0'; ++i) diff --git a/examples/host-loop/BoingHost.hpp b/examples/host-loop/BoingHost.hpp index 79058942..43d2a53d 100644 --- a/examples/host-loop/BoingHost.hpp +++ b/examples/host-loop/BoingHost.hpp @@ -265,7 +265,7 @@ class Host { Settings settings; std::uint32_t revision{0}; std::map waiting; - std::set inFlight; // retained until this consumer's delivery begins + std::set inFlight; // retained until this consumer's delivery begins Displayed lastDisplayed; bool stopping{false}, ended{false}; diff --git a/examples/host-loop/HostLoop.cpp b/examples/host-loop/HostLoop.cpp index fdf0c011..bf6a7789 100644 --- a/examples/host-loop/HostLoop.cpp +++ b/examples/host-loop/HostLoop.cpp @@ -1,6 +1,6 @@ +#include "../PortOption.hpp" #include "HostLoopCapture.hpp" #include "HostLoopUI.hpp" -#include "../PortOption.hpp" #include #include @@ -80,17 +80,18 @@ int runWithBrowser(boing::Host& host, const Options& options) { int runWithWindow(boing::Host& host, const Options& options) { using App = webfront::WebFrontWithFrontend; // The server's connection handler refers to these; keep them alive until after app is destroyed. - std::mutex uiMutex; + std::mutex uiMutex; std::optional captureUI; - App app{webfront::WebFrontConfig{.window = {.title = "WebFront host loop", .width = options.captureDemo ? 640 : 800, .height = options.captureDemo ? 480 : 600}}}; + App app{webfront::WebFrontConfig{ + .window = {.title = "WebFront host loop", .width = options.captureDemo ? 640 : 800, .height = options.captureDemo ? 480 : 600}}}; boing::install(app, host); app.onUIStarted([&](App::UI ui) { const std::scoped_lock lock{uiMutex}; - captureUI = ui; - const std::string mode = options.captureFrames > 1 - ? (options.settings.glass ? "globalThis.hostLoopCapture = {glass: true};" : "globalThis.hostLoopCapture = {glass: false};") : ""; - const std::string style = options.captureDemo - ? "document.querySelector('#host-loop .stats').remove();" : ""; + captureUI = ui; + const std::string mode = options.captureFrames > 1 + ? (options.settings.glass ? "globalThis.hostLoopCapture = {glass: true};" : "globalThis.hostLoopCapture = {glass: false};") + : ""; + const std::string style = options.captureDemo ? "document.querySelector('#host-loop .stats').remove();" : ""; ui.addScript(mode + ownPage + style); }); std::atomic showReturned{false}; @@ -135,7 +136,7 @@ int runWithWindow(boing::Host& host, const Options& options) { return; if (options.captureFrames > 1) { const bool glass = options.captureDemo ? i >= options.captureFrames * 2 / 3 : options.settings.glass; - auto drawn = ui->jsFunction("hostLoop.captureNext")(glass); + auto drawn = ui->jsFunction("hostLoop.captureNext")(glass); if (drawn.wait_for(10s) != std::future_status::ready) throw std::runtime_error("No capture: the browser did not draw the next frame"); (void)drawn.get(); @@ -228,7 +229,7 @@ bool parse(std::span arguments, Options& options) { if (options.captureDemo && !captureFramesSpecified) options.captureFrames = 300; return (!(captureFramesSpecified || options.captureDemo) || !options.capture.empty()) - && (!options.captureDemo || (options.captureFrames >= 3 && options.captureFrames % 3 == 0)); + && (!options.captureDemo || (options.captureFrames >= 3 && options.captureFrames % 3 == 0)); } } // namespace @@ -237,18 +238,18 @@ int main(int argc, char** argv) { return 2; Options options; if (!parse({argv + 1, static_cast(argc - 1)}, options)) { - std::cerr - << "Usage: WebFrontHostLoop [--port ] [--engine cpu|cuda] [--quality 0-3] [--glass] [--browser] [--stats] [--capture ] [--capture-frames 1-600] [--capture-demo]\n" - " WebFrontHostLoop --benchmark\n" - " --engine the renderer at start (default cpu); cuda is an error where it is unavailable\n" - " --quality 0: 320x240, 1: 640x480, 2: 640x480 with 4 rays per pixel, 3: 960x720 with 4 (default)\n" - " --port the port of the browser interface, 0 for a free port (default WEBFRONT_PORT, else 9002)\n" - " --browser open the system browser even when the native window is built\n" - " --stats print the timings of an image every second\n" - " --capture write a PNG of the native window after six seconds, then stop\n" - " --capture-frames save numbered PNGs with a fixed 25 fps scene clock (default 1); requires --capture\n" - " --capture-demo hide statistics and switch to glass after two thirds (default 300 frames)\n" - " --benchmark time both renderers without any interface, and exit\n"; + std::cerr << "Usage: WebFrontHostLoop [--port ] [--engine cpu|cuda] [--quality 0-3] [--glass] [--browser] [--stats] [--capture ] " + "[--capture-frames 1-600] [--capture-demo]\n" + " WebFrontHostLoop --benchmark\n" + " --engine the renderer at start (default cpu); cuda is an error where it is unavailable\n" + " --quality 0: 320x240, 1: 640x480, 2: 640x480 with 4 rays per pixel, 3: 960x720 with 4 (default)\n" + " --port the port of the browser interface, 0 for a free port (default WEBFRONT_PORT, else 9002)\n" + " --browser open the system browser even when the native window is built\n" + " --stats print the timings of an image every second\n" + " --capture write a PNG of the native window after six seconds, then stop\n" + " --capture-frames save numbered PNGs with a fixed 25 fps scene clock (default 1); requires --capture\n" + " --capture-demo hide statistics and switch to glass after two thirds (default 300 frames)\n" + " --benchmark time both renderers without any interface, and exit\n"; return 2; } // WebFront's warnings on the console: a development build says there that its native window has no sandbox. diff --git a/examples/life/LifeDeveloper.cpp b/examples/life/LifeDeveloper.cpp index 754799cb..36050432 100644 --- a/examples/life/LifeDeveloper.cpp +++ b/examples/life/LifeDeveloper.cpp @@ -1,7 +1,7 @@ +#include "../PortOption.hpp" #include "Life.hpp" -#include "LifeFrontend.hpp" #include "LifeDeveloperOptions.hpp" -#include "../PortOption.hpp" +#include "LifeFrontend.hpp" #include #include diff --git a/examples/life/LifeDeveloperOptions.hpp b/examples/life/LifeDeveloperOptions.hpp index 822a328e..c9af9c9d 100644 --- a/examples/life/LifeDeveloperOptions.hpp +++ b/examples/life/LifeDeveloperOptions.hpp @@ -10,9 +10,9 @@ namespace webfront::demo { struct LifeDeveloperOptions { static constexpr const char* defaultProject = "life-project"; - std::filesystem::path project = defaultProject; - std::optional environment; - std::optional integrity; + std::filesystem::path project = defaultProject; + std::optional environment; + std::optional integrity; }; /// Returns nullopt when the arguments do not follow the usage; no argument selects `life-project` in the diff --git a/examples/life/LifeEmbedded.cpp b/examples/life/LifeEmbedded.cpp index 94a80ee5..78509786 100644 --- a/examples/life/LifeEmbedded.cpp +++ b/examples/life/LifeEmbedded.cpp @@ -1,8 +1,8 @@ #include #include WEBFRONT_LIFE_ASSETS_HEADER +#include "../PortOption.hpp" #include "Life.hpp" #include "LifeFrontend.hpp" -#include "../PortOption.hpp" #include diff --git a/examples/life/react/LifeReact.cpp b/examples/life/react/LifeReact.cpp index a69f6d7e..41377360 100644 --- a/examples/life/react/LifeReact.cpp +++ b/examples/life/react/LifeReact.cpp @@ -1,8 +1,8 @@ #include "LifeReact.hpp" +#include "../../PortOption.hpp" #include "../LifeDeveloperOptions.hpp" #include "../LifeFrontend.hpp" -#include "../../PortOption.hpp" #include #include @@ -14,7 +14,8 @@ int main(int argc, char** argv) { if (argc > 2 || (argc == 2 && *argv[1] == '\0')) { std::cerr << "Usage: WebFrontLifeReact [--port ] []\n" "Without argument the project is ./" - << webfront::demo::LifeDeveloperOptions::defaultProject << ", created empty when missing: copy main.tsx and webfront.project.json from examples/life/react/ into it first.\n"; + << webfront::demo::LifeDeveloperOptions::defaultProject + << ", created empty when missing: copy main.tsx and webfront.project.json from examples/life/react/ into it first.\n"; return 2; } try { diff --git a/examples/life/react/LifeReact.hpp b/examples/life/react/LifeReact.hpp index a4f44fb8..99fef398 100644 --- a/examples/life/react/LifeReact.hpp +++ b/examples/life/react/LifeReact.hpp @@ -42,7 +42,7 @@ template panel.append(status); auto session = std::make_shared(Session{ react::Store{ui, "life"}, - {}, + {}, 0, label }); diff --git a/include/webfront/BridgeError.hpp b/include/webfront/BridgeError.hpp index c9e05c6f..45c17c91 100644 --- a/include/webfront/BridgeError.hpp +++ b/include/webfront/BridgeError.hpp @@ -39,7 +39,7 @@ inline constexpr std::string_view cancelled = "webfront.cancelled"; */ class BridgeError : public std::runtime_error { public: - static constexpr std::size_t maxCodeSize = 64; + static constexpr std::size_t maxCodeSize = 64; static constexpr std::string_view reservedPrefix = "webfront."; /// @throws std::invalid_argument for an ill-formed or reserved code diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 0129c6e0..7d8cfe6e 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -81,8 +81,8 @@ inline std::vector parseArguments(std::string_view json) { inline void validateName(std::string_view name) { const auto invalid = name.empty() || std::ranges::any_of(name, [](char c) { - return static_cast(c) <= ' ' || c == '\x7f' || c == '\'' || c == '"' || c == '\\'; - }); + return static_cast(c) <= ' ' || c == '\x7f' || c == '\'' || c == '"' || c == '\\'; + }); if (invalid) throw std::invalid_argument("Invalid command name '" + std::string(name) + "'"); if (std::ranges::find(reservedNames, name) != reservedNames.end()) @@ -98,10 +98,10 @@ struct Run { int exitCode = 0; // The command's own stop source, requested with its task's: a copy of the Context that outlives the task still // reads a valid source. - ex::inplace_stop_source stop; - std::atomic disconnected{false}; + ex::inplace_stop_source stop; + std::atomic disconnected{false}; - Run(UI caller, std::uint32_t commandId, std::vector args) : ui(std::move(caller)), id(commandId), arguments(std::move(args)) { } + Run(UI caller, std::uint32_t commandId, std::vector args) : ui(std::move(caller)), id(commandId), arguments(std::move(args)) {} /// Calls a browser function of the terminal, unless the browser disconnected (Registry::closed): its connection /// is gone, and a later browser may get its identifier. Returns false when the call was not made. @@ -120,7 +120,7 @@ struct Run { template class Context { public: - explicit Context(std::shared_ptr> command) : run(std::move(command)) { } + explicit Context(std::shared_ptr> command) : run(std::move(command)) {} /// The words after the command name, split like a shell line by the terminal. [[nodiscard]] const std::vector& args() const noexcept { @@ -314,19 +314,20 @@ class Registry : public std::enable_shared_from_this> { // command it stopped waiting for. A stopped command still reports: its coroutine was unwound, not this one. struct ForwardStop { Run* run; - void operator()() noexcept { run->stop.request_stop(); } + void operator()() noexcept { + run->stop.request_stop(); + } }; static Task execute(std::weak_ptr registry, std::shared_ptr handler, std::shared_ptr> run) { const auto taskStop = co_await ex::read_env(ex::get_stop_token); // Forwards the task's stop request (Ctrl+C, disconnection, shutdown) to the command's source while it runs. const ex::stop_callback_for_t, ForwardStop> forward{taskStop, ForwardStop{run.get()}}; - bool stopped = false; - std::string error; + bool stopped = false; + std::string error; try { // The command observes its own source: requested before the senders it awaits are stopped. - co_await ex::let_stopped(ex::write_env((*handler)(Context{run}), ex::prop{ex::get_stop_token, run->stop.get_token()}), - [&stopped]() noexcept { + co_await ex::let_stopped(ex::write_env((*handler)(Context{run}), ex::prop{ex::get_stop_token, run->stop.get_token()}), [&stopped]() noexcept { stopped = true; return ex::just(); }); @@ -341,7 +342,7 @@ class Registry : public std::enable_shared_from_this> { const int code = stopped || run->stop.stop_requested() ? interruptedExitCode : !error.empty() ? 1 : run->exitCode; try { run->send("webfront.commands.exit", code, error.empty() ? std::string_view{} : chunks(error).front()); - } catch (...) { } // nothing is left to report it to + } catch (...) {} // nothing is left to report it to } }; @@ -382,7 +383,8 @@ class Commands { return owner->list(); })); registered(app.template cppFunction( - "webfront.commands.start", [owner = registry](UI ui, std::uint32_t id, const std::string& name, const std::string& arguments) { + "webfront.commands.start", + [owner = registry](UI ui, std::uint32_t id, const std::string& name, const std::string& arguments) { owner->start(std::move(ui), id, name, arguments); })); registered(app.template cppFunction("webfront.commands.cancel", [owner = registry](UI ui, std::uint32_t id) { diff --git a/include/webfront/DeferredCalls.hpp b/include/webfront/DeferredCalls.hpp index b45c22e0..5ef9a396 100644 --- a/include/webfront/DeferredCalls.hpp +++ b/include/webfront/DeferredCalls.hpp @@ -7,8 +7,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -104,11 +104,11 @@ class DeferredCalls { } private: - mutable std::mutex mutex; - std::set inFlightIds; + mutable std::mutex mutex; + std::set inFlightIds; std::map> tasks; - std::uint64_t lastKey = 0; - bool closed = false; + std::uint64_t lastKey = 0; + bool closed = false; }; } // namespace webfront::detail diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index f2ce65fa..47db8f09 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -66,11 +66,10 @@ inline constexpr std::string_view defaultRegistry{"https://registry.npmjs.org/"} /// The configuration the environment reads. "registry" always names a usable registry, for environments /// that predate "registryExplicit"; the latter tells whether the application chose it. inline std::string bootstrapConfig(const DeveloperBootstrapOptions& options) { - return "{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) - + ",\"registry\":" + json::quote(options.registry.value_or(std::string(defaultRegistry))) - + ",\"registryExplicit\":" + (options.registry ? "true" : "false") - + (options.manifestDirectory.empty() ? std::string{} : ",\"manifestDirectory\":" + json::quote(options.manifestDirectory)) - + ",\"supported\":{\"protocol\":[" + std::to_string(protocolVersion) + "],\"api\":[" + std::to_string(apiVersion) + "]}}"; + return "{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) + ",\"registry\":" + + json::quote(options.registry.value_or(std::string(defaultRegistry))) + ",\"registryExplicit\":" + (options.registry ? "true" : "false") + + (options.manifestDirectory.empty() ? std::string{} : ",\"manifestDirectory\":" + json::quote(options.manifestDirectory)) + + ",\"supported\":{\"protocol\":[" + std::to_string(protocolVersion) + "],\"api\":[" + std::to_string(apiVersion) + "]}}"; } } // namespace developer @@ -82,7 +81,7 @@ class DeveloperAppWithNetwork : public BasicWF #include #include +#include #include #include #include #include -#include - namespace webfront { namespace detail { struct IgnoreJsResult {}; -} +} // namespace detail -template +template class JsFunction { public: JsFunction(std::string_view functionName, WebFront& wf, WebLinkId linkId, WebLinkGeneration connectionGeneration) @@ -58,10 +57,10 @@ class JsFunction { } private: - std::string name; - WebFront& webFront; - WebLinkId webLinkId; + std::string name; + WebFront& webFront; + WebLinkId webLinkId; WebLinkGeneration generation; }; -} // namespace webfront +} // namespace webfront diff --git a/include/webfront/JsFunctionSender.hpp b/include/webfront/JsFunctionSender.hpp index a7ffcf68..bf26acc5 100644 --- a/include/webfront/JsFunctionSender.hpp +++ b/include/webfront/JsFunctionSender.hpp @@ -64,7 +64,7 @@ class BrowserCallSender { std::optional> stopCallback; State(Receiver r, std::weak_ptr calls, std::weak_ptr ws, std::vector data) - : receiver(std::move(r)), pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) { } + : receiver(std::move(r)), pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) {} void start() noexcept { // Completion is deferred until callback construction and dispatch are finished: @@ -97,11 +97,11 @@ class BrowserCallSender { id = calls->add({.complete = [self](const msg::FunctionReturn& result) { self->complete(result); - }, + }, .reject = [self](std::exception_ptr e) { self->finish(Outcome::error, std::move(e)); - }, + }, .owner = this}); } @@ -198,12 +198,12 @@ class BrowserCallSender { public: using operation_state_concept = ex::operation_state_tag; - explicit Operation(std::shared_ptr> value) : state(std::move(value)) { } - Operation(const Operation&) = delete; - Operation(Operation&&) = delete; - Operation& operator=(const Operation&) = delete; - Operation& operator=(Operation&&) = delete; - void start() noexcept { + explicit Operation(std::shared_ptr> value) : state(std::move(value)) {} + Operation(const Operation&) = delete; + Operation(Operation&&) = delete; + Operation& operator=(const Operation&) = delete; + Operation& operator=(Operation&&) = delete; + void start() noexcept { auto keepAlive = state; // receiver completion may destroy this operation inline keepAlive->start(); } @@ -214,7 +214,7 @@ class BrowserCallSender { using completion_signatures = typename CallCompletions::type; BrowserCallSender(std::weak_ptr calls, std::weak_ptr ws, std::vector data) - : pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) { } + : pending(std::move(calls)), socket(std::move(ws)), payload(std::move(data)) {} template auto connect(Receiver receiver) && { @@ -249,7 +249,7 @@ class JsFunctionSender { auto operator()(auto&&... arguments) const { msg::FunctionCall command; const auto frame = detail::encodeCall(command, name, std::forward(arguments)...); - std::vector payload; + std::vector payload; payload.reserve(frame.size()); auto buffers = frame.toBuffers(); for (std::size_t i = 1; i < buffers.size(); ++i) { diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index 600873f4..e469ff3e 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -15,9 +15,9 @@ /// connection reads only if the application declared its deployment (RemoteFileTransport). #pragma once -#include "ViewAssociation.hpp" #include "automation/Credentials.hpp" #include "http/HTTPServer.hpp" +#include "ViewAssociation.hpp" #include #include @@ -42,9 +42,11 @@ namespace webfront { /// How the application declares that a connection which is not the view of an embedded frontend (the system browser, a /// remote browser) reaches it (ADR-020). WebFront decides on neither the address nor `Forwarded`/`X-Forwarded-*`. enum class RemoteFileTransport { - refused, ///< Default: such a connection reads no file. - loopbackAttested, ///< The server listens on the loopback only (checked at configuration); the integrator attests no proxy or tunnel exposes it and the machine is not shared with untrusted users. - encryptedByDeployment, ///< The deployment encrypts below HTTP (VPN, SSH or other tunnel) while the browser still uses http://: unverified. The cookie is not `Secure`, which a browser would refuse over http://. + refused, ///< Default: such a connection reads no file. + loopbackAttested, ///< The server listens on the loopback only (checked at configuration); the integrator attests no proxy or tunnel exposes it and the + ///< machine is not shared with untrusted users. + encryptedByDeployment, ///< The deployment encrypts below HTTP (VPN, SSH or other tunnel) while the browser still uses http://: unverified. The cookie is + ///< not `Secure`, which a browser would refuse over http://. httpsByDeployment, ///< The browser reaches the application by https:// (TLS reverse proxy): unverified. The binding cookie is `Secure`. plaintextAccepted ///< An isolated trusted network: unverified. }; @@ -77,7 +79,9 @@ namespace detail { [[nodiscard]] inline std::string lowerAscii(std::string_view text) { std::string result(text); - std::ranges::transform(result, result.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(result, result.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); return result; } @@ -121,24 +125,31 @@ struct ReadPresentation { /// The closed list of passive types shown inline (raster images, audio, video, text/plain); every other type is a download. /// HTML, XML, JavaScript and WebAssembly are announced as application/octet-stream; SVG keeps its type, for ``. [[nodiscard]] inline ReadPresentation presentRead(std::string_view contentType) { - const auto announced = std::string(trimBlanks(contentType)); - const auto semicolon = announced.find(';'); - const auto essence = lowerAscii(trimBlanks(std::string_view{announced}.substr(0, semicolon))); + const auto announced = std::string(trimBlanks(contentType)); + const auto semicolon = announced.find(';'); + const auto essence = lowerAscii(trimBlanks(std::string_view{announced}.substr(0, semicolon))); if (essence.empty()) return {"application/octet-stream", false}; - static constexpr std::string_view active[] = {"text/html", "application/xhtml+xml", "text/xml", "application/xml", - "text/javascript", "application/javascript", "application/x-javascript", - "text/ecmascript", "application/ecmascript", "application/wasm"}; + static constexpr std::string_view active[] = {"text/html", + "application/xhtml+xml", + "text/xml", + "application/xml", + "text/javascript", + "application/javascript", + "application/x-javascript", + "text/ecmascript", + "application/ecmascript", + "application/wasm"}; // Every spelling a browser runs as a script (text/javascript1.5, application/x-ecmascript, text/jscript, ...), and // stylesheets, are announced as opaque bytes. - const bool scripting = essence.contains("javascript") || essence.contains("ecmascript") || essence.contains("jscript") - || essence.contains("livescript") || essence.contains("vbscript") || essence == "text/css"; - const bool isActive = scripting || std::ranges::find(active, essence) != std::end(active) - || (essence.ends_with("+xml") && essence != "image/svg+xml") || essence.ends_with("+wasm"); + const bool scripting = essence.contains("javascript") || essence.contains("ecmascript") || essence.contains("jscript") || essence.contains("livescript") + || essence.contains("vbscript") || essence == "text/css"; + const bool isActive = scripting || std::ranges::find(active, essence) != std::end(active) || (essence.ends_with("+xml") && essence != "image/svg+xml") + || essence.ends_with("+wasm"); if (isActive) return {"application/octet-stream", false}; - static constexpr std::string_view raster[] = {"image/png", "image/jpeg", "image/gif", "image/webp", - "image/avif", "image/bmp", "image/apng", "image/x-icon", "image/vnd.microsoft.icon"}; + static constexpr std::string_view raster[] = + {"image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp", "image/apng", "image/x-icon", "image/vnd.microsoft.icon"}; const bool passive = std::ranges::find(raster, essence) != std::end(raster) || essence.starts_with("audio/") || essence.starts_with("video/") || essence == "text/plain"; return {announced, passive}; @@ -150,16 +161,16 @@ struct ReadPresentation { std::string name(slash == std::string_view::npos ? rest : rest.substr(slash + 1)); std::string ascii, encoded; for (const char raw : name) { - const auto c = static_cast(raw); + const auto c = static_cast(raw); const bool plain = c >= 0x20 && c < 0x7f && c != '"' && c != '\\' && c != ';' && c != '%' && c != '/'; - ascii += plain ? static_cast(c) : '_'; + ascii += plain ? static_cast(c) : '_'; if (asciiAlnum(c) || std::string_view{"!#$&+-.^_`|~"}.contains(static_cast(c))) { encoded += static_cast(c); } else { constexpr std::string_view digits = "0123456789ABCDEF"; - encoded += '%'; - encoded += digits[c >> 4]; - encoded += digits[c & 15]; + encoded += '%'; + encoded += digits[c >> 4]; + encoded += digits[c & 15]; } } if (ascii.empty()) @@ -168,7 +179,9 @@ struct ReadPresentation { } inline void setHeader(http::RouteReply& reply, std::string_view name, std::string value) { - std::erase_if(reply.headers, [&](const auto& header) { return lowerAscii(header.first) == lowerAscii(name); }); + std::erase_if(reply.headers, [&](const auto& header) { + return lowerAscii(header.first) == lowerAscii(name); + }); reply.headers.emplace_back(std::string(name), std::move(value)); } @@ -181,7 +194,9 @@ inline void hardenRead(http::RouteReply& reply, std::string_view rest) { const auto presentation = presentRead(contentType); setHeader(reply, "Content-Type", presentation.contentType); // A handler cannot choose a presentation of its own: the disposition is derived from the announced type. - std::erase_if(reply.headers, [](const auto& header) { return lowerAscii(header.first) == "content-disposition"; }); + std::erase_if(reply.headers, [](const auto& header) { + return lowerAscii(header.first) == "content-disposition"; + }); if (!presentation.inlineOk) reply.headers.emplace_back("Content-Disposition", attachmentName(rest)); setHeader(reply, "Cache-Control", "no-store"); @@ -209,14 +224,26 @@ class ReadBinding { struct Options { RemoteFileTransport remote = RemoteFileTransport::refused; - bool secure = false; + bool secure = false; }; - explicit ReadBinding(RemoteFileTransport declared = RemoteFileTransport::refused, Clock clock = [] { return std::chrono::steady_clock::now(); }) + explicit ReadBinding( + RemoteFileTransport declared = RemoteFileTransport::refused, + Clock clock = + [] { + return std::chrono::steady_clock::now(); + }) : ReadBinding(Options{.remote = declared}, std::move(clock)) {} - explicit ReadBinding(std::same_as auto options, Clock clock = [] { return std::chrono::steady_clock::now(); }) - : transport(options.remote), secureTransport(options.secure), now(std::move(clock)), + explicit ReadBinding( + std::same_as auto options, + Clock clock = + [] { + return std::chrono::steady_clock::now(); + }) + : transport(options.remote), + secureTransport(options.secure), + now(std::move(clock)), ownPrefix(std::string(cookiePrefix) + automation::channel::nonce().substr(0, 8) + "-") {} /// Names the cookies after `name` (the port the server listens on) instead of a random word, so that a restart on the @@ -228,12 +255,16 @@ class ReadBinding { /// The cookie name prefix of this application: cookies are shared across ports of a host, so each binding names (and /// erases) only its own, `wf-client--`. - [[nodiscard]] const std::string& clientCookiePrefix() const noexcept { return ownPrefix; } + [[nodiscard]] const std::string& clientCookiePrefix() const noexcept { + return ownPrefix; + } ReadBinding(const ReadBinding&) = delete; ReadBinding& operator=(const ReadBinding&) = delete; - [[nodiscard]] RemoteFileTransport declaredTransport() const noexcept { return transport; } + [[nodiscard]] RemoteFileTransport declaredTransport() const noexcept { + return transport; + } /// A connection starts. `local` is true only for the view of an embedded frontend. Returns the one-time secret /// that the page exchanges for its cookie. @@ -242,10 +273,10 @@ class ReadBinding { Released released; std::scoped_lock lock{mutex}; if (stopped) - return secret; // nothing is registered: the exchange of this secret finds no connection + return secret; // nothing is registered: the exchange of this secret finds no connection if (connections.contains(key)) // a key opened twice starts over: the old secret, client link and grants die dropConnection(key, released); - connections[key] = Connection{.local = local, .client = {}, .exchange = secret}; + connections[key] = Connection{.local = local, .client = {}, .exchange = secret}; exchanges[secret] = key; return secret; } @@ -279,7 +310,9 @@ class ReadBinding { if (options.transferable && (options.lifetime.count() <= 0 || options.lifetime > maxTransferableLifetime)) throw ReadRefused("A transferable read needs a lifetime of at most 15 minutes"); // The server refuses a target holding ".." or a control character before any route sees it: such a URL would never work. - if (rest.contains("..") || std::ranges::any_of(rest, [](char c) { return static_cast(c) < 32 || c == 127; })) + if (rest.contains("..") || std::ranges::any_of(rest, [](char c) { + return static_cast(c) < 32 || c == 127; + })) throw ReadRefused("The path of a read cannot contain \"..\" or control characters"); if (http::routing::collapseSegments("/" + std::string(rest)) != "/" + std::string(rest)) throw ReadRefused("The path of a read cannot hold empty or dot segments"); @@ -287,12 +320,18 @@ class ReadBinding { Released released; std::scoped_lock lock{mutex}; reapExpired(released); - const auto connection = connections.find(key); + const auto connection = connections.find(key); if (stopped || connection == connections.end()) throw ReadRefused("The connection is closed"); if (!connection->second.local && transport == RemoteFileTransport::refused) throw ReadRefused("This connection is not the view of an embedded frontend: declare WebFrontConfig::remoteFileTransport to read files"); - Grant record{.owner = key, .route = std::string(routeId), .secret = secret, .path = std::string(rest), .transferable = options.transferable, .expiry = {}, .context = std::make_shared(std::move(options.context))}; + Grant record{.owner = key, + .route = std::string(routeId), + .secret = secret, + .path = std::string(rest), + .transferable = options.transferable, + .expiry = {}, + .context = std::make_shared(std::move(options.context))}; if (options.lifetime.count() > 0) { // now() + lifetime must not overflow the clock's representation (seconds::max() converts to ticks that do not fit). const auto current = now(); @@ -337,7 +376,7 @@ class ReadBinding { auto reply = plain(http::Response::ok); detail::setHeader(reply, "Cache-Control", "no-store"); detail::setHeader(reply, "Referrer-Policy", "no-referrer"); - const auto what = request.path.substr(bindPath.size()); + const auto what = request.path.substr(bindPath.size()); const auto cookies = detail::requestCookies(request.request); if (what.starts_with("check/")) { // the client the exchange assigned to this page, which must be the one whose cookie came back std::scoped_lock lock{mutex}; @@ -355,10 +394,10 @@ class ReadBinding { /// The prefix this is registered under must be `prefix`, which ends with '/'. [[nodiscard]] http::RouteHandler readHandler(std::string routeId, std::string prefix, ReadHandler handler) { return [this, routeId = std::move(routeId), prefix = std::move(prefix), handler = std::move(handler)](const http::RouteRequest& request) { - const auto after = request.path.substr(std::min(prefix.size(), request.path.size())); - const auto slash = after.find('/'); - const auto token = after.substr(0, slash); - const auto rest = slash == std::string_view::npos ? std::string_view{} : after.substr(slash + 1); + const auto after = request.path.substr(std::min(prefix.size(), request.path.size())); + const auto slash = after.find('/'); + const auto token = after.substr(0, slash); + const auto rest = slash == std::string_view::npos ? std::string_view{} : after.substr(slash + 1); auto context = authorize(routeId, token, rest, detail::requestCookies(request.request)); if (!context) { auto denied = plain(http::Response::forbidden); @@ -372,7 +411,8 @@ class ReadBinding { } /// True when `token` is accepted for a request that presents `cookies`: used by the route, exposed for tests. - [[nodiscard]] bool accepts(std::string_view routeId, std::string_view token, std::string_view rest, const std::vector>& cookies) { + [[nodiscard]] bool + accepts(std::string_view routeId, std::string_view token, std::string_view rest, const std::vector>& cookies) { return authorize(routeId, token, rest, cookies).has_value(); } @@ -385,14 +425,14 @@ class ReadBinding { std::string exchange; // the one-time secret, until used }; struct Client { - std::string secret; + std::string secret; std::set connections; }; struct Grant { ConnectionKey owner = 0; std::string route; // the registration that issued it std::string secret; - std::string path; // the path it was issued for + std::string path; // the path it was issued for bool transferable = false; std::optional expiry; std::shared_ptr context; @@ -413,9 +453,9 @@ class ReadBinding { encoded += static_cast(c); } else { constexpr std::string_view digits = "0123456789ABCDEF"; - encoded += '%'; - encoded += digits[c >> 4]; - encoded += digits[c & 15]; + encoded += '%'; + encoded += digits[c >> 4]; + encoded += digits[c & 15]; } } return encoded; @@ -433,13 +473,21 @@ class ReadBinding { clients.erase(client); } connections.erase(found); - detach([key](const auto& grant) { return grant.second.owner == key; }, released); + detach( + [key](const auto& grant) { + return grant.second.owner == key; + }, + released); } /// Drops the expired grants and their contexts, whether or not their tokens are ever presented again. Caller holds the lock. void reapExpired(Released& released) { const auto instant = now(); - detach([instant](const auto& grant) { return grant.second.expiry && instant >= *grant.second.expiry; }, released); + detach( + [instant](const auto& grant) { + return grant.second.expiry && instant >= *grant.second.expiry; + }, + released); } /// Removes the grants matching `selected`, handing their contexts to `released` so that the caller destroys them once @@ -496,11 +544,13 @@ class ReadBinding { // Cookies named after a client the server forgot are erased; the ones of a known client are left alone. for (const auto& [name, value] : cookies) if (name.starts_with(ownPrefix) && !clients.contains(name.substr(ownPrefix.size()))) - reply.headers.emplace_back("Set-Cookie", name + "=; Max-Age=0; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict" + (secureCookies() ? "; Secure" : "")); + reply.headers.emplace_back("Set-Cookie", + name + "=; Max-Age=0; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict" + + (secureCookies() ? "; Secure" : "")); auto id = cookieClient(cookies); if (id.empty()) { id = automation::channel::nonce().substr(0, 16); - Client created{.secret = automation::channel::nonce(), .connections = {}}; + Client created{.secret = automation::channel::nonce(), .connections = {}}; std::string cookie = ownPrefix + id + "=" + created.secret + "; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict"; if (secureCookies()) cookie += "; Secure"; @@ -514,18 +564,19 @@ class ReadBinding { } /// The context of the grant, when `token` and the cookies are acceptable. Every refusal looks alike. - std::optional> authorize(std::string_view routeId, std::string_view token, std::string_view rest, const std::vector>& cookies) { + std::optional> + authorize(std::string_view routeId, std::string_view token, std::string_view rest, const std::vector>& cookies) { const auto dot = token.find('.'); if (dot == std::string_view::npos) return std::nullopt; Released released; std::scoped_lock lock{mutex}; reapExpired(released); - const auto found = grants.find(std::string(token.substr(0, dot))); + const auto found = grants.find(std::string(token.substr(0, dot))); if (found == grants.end() || !detail::viewSecretMatches(found->second.secret, token.substr(dot + 1))) return std::nullopt; const auto& grant = found->second; - if (grant.path != rest) // a token opens the path it was issued for, nothing else under the route + if (grant.path != rest) // a token opens the path it was issued for, nothing else under the route return std::nullopt; if (grant.route != routeId) // a grant is valid for the registration that issued it, not for a later route on the prefix return std::nullopt; @@ -547,27 +598,35 @@ class ReadBinding { return grant.context; } - bool secureCookies() const { return secureTransport || transport == RemoteFileTransport::httpsByDeployment; } + bool secureCookies() const { + return secureTransport || transport == RemoteFileTransport::httpsByDeployment; + } - RemoteFileTransport transport; - bool secureTransport = false; - Clock now; - std::string ownPrefix; - std::mutex mutex; - std::map connections; + RemoteFileTransport transport; + bool secureTransport = false; + Clock now; + std::string ownPrefix; + std::mutex mutex; + std::map connections; std::map exchanges; - std::map clients; - std::map grants; - bool stopped = false; + std::map clients; + std::map grants; + bool stopped = false; }; /// A registered read route (BasicWF::addReadRoute): the route lasts as long as this object. Move-only. class ReadRoute { public: ReadRoute() = default; - [[nodiscard]] const std::string& prefix() const noexcept { return prefixValue; } - [[nodiscard]] const std::string& id() const noexcept { return idValue; } - [[nodiscard]] explicit operator bool() const noexcept { return static_cast(registration); } + [[nodiscard]] const std::string& prefix() const noexcept { + return prefixValue; + } + [[nodiscard]] const std::string& id() const noexcept { + return idValue; + } + [[nodiscard]] explicit operator bool() const noexcept { + return static_cast(registration); + } ReadRoute(std::string id, std::string prefix, std::shared_ptr owner, http::RouteTable::Registration route) : idValue(std::move(id)), prefixValue(std::move(prefix)), bound(std::move(owner)), registration(std::move(route)) {} diff --git a/include/webfront/Task.hpp b/include/webfront/Task.hpp index 7b3db523..c6f8c174 100644 --- a/include/webfront/Task.hpp +++ b/include/webfront/Task.hpp @@ -41,7 +41,7 @@ struct StopTask { struct TaskRegistration { TaskHandle handle; networking::ex::stop_callback_for_t stop; - TaskRegistration(TaskHandle value, networking::ex::inplace_stop_token parent) : handle(std::move(value)), stop(parent, StopTask{handle}) { } + TaskRegistration(TaskHandle value, networking::ex::inplace_stop_token parent) : handle(std::move(value)), stop(parent, StopTask{handle}) {} }; inline Task ownedTask(Task task, std::unique_ptr registration) { diff --git a/include/webfront/UIThread.hpp b/include/webfront/UIThread.hpp index b1a000e5..83b54594 100644 --- a/include/webfront/UIThread.hpp +++ b/include/webfront/UIThread.hpp @@ -24,7 +24,7 @@ namespace webfront { /// @brief UIThread::stop() gave up: the window did not close in the time allowed, and its thread still runs show(). class UIThreadStalled : public std::runtime_error { public: - UIThreadStalled() : std::runtime_error("webfront::UIThread::stop(): the interface did not close when asked; its thread is still running") { } + UIThreadStalled() : std::runtime_error("webfront::UIThread::stop(): the interface did not close when asked; its thread is still running") {} }; /** @@ -92,7 +92,9 @@ class UIThread { std::exception_ptr error; { std::unique_lock lock(mutex); - changed.wait(lock, [&] { return started; }); + changed.wait(lock, [&] { + return started; + }); if (!application) // set before `started`: construction or setup failed error = std::exchange(failed, nullptr); } @@ -111,7 +113,7 @@ class UIThread { ~UIThread() { try { stop(std::chrono::milliseconds::max()); - } catch (...) { // observed through failure() or an explicit stop(), or not at all + } catch (...) { // observed through failure() or an explicit stop(), or not at all } if (worker.joinable()) // never leave a joinable thread to std::thread's destructor, whatever stop() threw worker.join(); @@ -132,7 +134,9 @@ class UIThread { template bool waitFor(std::chrono::duration timeout) const { std::unique_lock lock(mutex); - return changed.wait_for(lock, timeout, [&] { return finished; }); + return changed.wait_for(lock, timeout, [&] { + return finished; + }); } /// What show() threw, once it has ended; null while it runs and after a normal end. stop() rethrows it. @@ -165,7 +169,9 @@ class UIThread { } catch (...) { // a request that failed is repeated at the next period, like one that reached nothing } lock.lock(); - if (changed.wait_for(lock, closeRetry, [&] { return finished; })) + if (changed.wait_for(lock, closeRetry, [&] { + return finished; + })) break; // Elapsed time is converted down to the patience's unit: converting milliseconds::max() up would overflow. if (std::chrono::duration_cast(std::chrono::steady_clock::now() - start) >= patience) @@ -201,8 +207,8 @@ class UIThread { changed.notify_all(); } - std::optional application; // written by the interface thread before `started`, then by stop() - mutable std::mutex mutex; // guards started, finished and failed + std::optional application; // written by the interface thread before `started`, then by stop() + mutable std::mutex mutex; // guards started, finished and failed mutable std::condition_variable changed; bool started = false; // construction and setup are over, successfully or not bool finished = false; // show() returned or threw diff --git a/include/webfront/ViewAssociation.hpp b/include/webfront/ViewAssociation.hpp index 4261ffcd..ccb8f13d 100644 --- a/include/webfront/ViewAssociation.hpp +++ b/include/webfront/ViewAssociation.hpp @@ -44,7 +44,7 @@ inline std::string newViewSecret() { std::size_t mismatch = launchSecret.size() ^ presented.size(); for (std::size_t index = 0; index < launchSecret.size(); ++index) { const unsigned char given = index < presented.size() ? static_cast(presented[index]) : 0; - mismatch |= static_cast(static_cast(launchSecret[index]) ^ given); + mismatch |= static_cast(static_cast(launchSecret[index]) ^ given); } return mismatch == 0; } @@ -53,7 +53,9 @@ inline std::string newViewSecret() { /// browser's URL parser finish serialization, including compression of IPv6 and its embedded IPv4 notation. [[nodiscard]] inline std::string browserOrigin(std::string_view address, std::string_view port, bool secure = false) { auto origin = applicationOrigin(address, port, secure); - std::ranges::transform(origin, origin.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(origin, origin.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); if (port == (secure ? "443" : "80")) origin.resize(origin.size() - port.size() - 1); return origin; @@ -63,17 +65,21 @@ inline std::string newViewSecret() { /// Returns an empty script (no association) unless `secret` is lowercase hexadecimal and `origin` is made of the characters /// of a plain http origin: nothing else can be written in a string literal without escaping, and nothing is escaped here. [[nodiscard]] inline std::string viewSecretScript(std::string_view secret, std::string_view origin) { - const auto isHex = [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }; - const auto isOrigin = [](char c) { return std::isalnum(static_cast(c)) || std::string_view{":/.[]-"}.contains(c); }; + const auto isHex = [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }; + const auto isOrigin = [](char c) { + return std::isalnum(static_cast(c)) || std::string_view{":/.[]-"}.contains(c); + }; if (secret.empty() || origin.empty() || !std::ranges::all_of(secret, isHex) || !std::ranges::all_of(origin, isOrigin)) return {}; std::string script = "if (window === window.top && location.origin === new URL('"; - script += origin; - script += "').origin) Object.defineProperty(window, '"; - script += viewSecretProperty; - script += "', {value: '"; - script += secret; - script += "', configurable: true});"; + script += origin; + script += "').origin) Object.defineProperty(window, '"; + script += viewSecretProperty; + script += "', {value: '"; + script += secret; + script += "', configurable: true});"; return script; } diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 34ab45c1..2147f239 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -13,12 +13,12 @@ #include "JsFunction.hpp" #include "JsFunctionSender.hpp" #include "networking/TCPNetworkingStdnet.hpp" +#include "ReadBinding.hpp" #include "system/DefaultFS.hpp" #include "system/IndexFS.hpp" #include "system/WindowsCompat.hpp" #include "Task.hpp" #include "UISubscribers.hpp" -#include "ReadBinding.hpp" #include "ViewAssociation.hpp" #include "weblink/DomBatch.hpp" #include "weblink/Messages.hpp" @@ -28,13 +28,13 @@ #include #include #include -#include #include #include #include #include #include #include +#include #include #include #include @@ -67,8 +67,8 @@ using ConnectionError = std::runtime_error; template class BasicUI { - WebFront* webFront; ///< Never null: the only constructor takes a reference, and there is no default constructor. - WebLinkId webLinkId; + WebFront* webFront; ///< Never null: the only constructor takes a reference, and there is no default constructor. + WebLinkId webLinkId; WebLinkGeneration generation; public: @@ -107,7 +107,8 @@ class BasicUI { /// Queues one DOM command on the bridge context. Rejections arrive at wfDom.rejected(batchId, reason). void sendDomBatch(const msg::DomBatch& batch) const { const auto link = webFront->findLink(webLinkId, generation); - if (!link) throw ConnectionError("Connection with client lost"); + if (!link) + throw ConnectionError("Connection with client lost"); link->sendCommand(batch); } @@ -218,7 +219,11 @@ template [[nodiscard]] bool isLoopbackAddress(const Address& address) { if (address.is_loopback()) return true; - if constexpr (requires { address.is_v6(); address.to_v6().is_v4_mapped(); address.to_v6().to_bytes(); }) { + if constexpr (requires { + address.is_v6(); + address.to_v6().is_v4_mapped(); + address.to_v6().to_bytes(); + }) { if (address.is_v6()) { const auto v6 = address.to_v6(); return v6.is_v4_mapped() && v6.to_bytes()[12] == 127; @@ -241,11 +246,11 @@ inline int ensureFrontendInitialized() { template auto makeCppFunctionHandler(Function&& function) { using StoredFunction = std::decay_t; - auto callable = std::make_shared(std::forward(function)); + auto callable = std::make_shared(std::forward(function)); return [callable = std::move(callable)](std::span data, auto&&... caller) -> R { std::tuple parameters; - auto deserializeAndCall = [&](std::tuple& tuple, std::index_sequence) -> R { + auto deserializeAndCall = [&](std::tuple& tuple, std::index_sequence) -> R { // Arguments that cannot be decoded as the callback declared them reject with the `webfront.malformed` code. try { (msg::FunctionCall::decodeParameter(std::get(tuple), data), ...); @@ -271,14 +276,18 @@ auto makeCppFunctionHandler(Function&& function) { template auto makeDeferredHandler(Function&& function) { using StoredFunction = std::decay_t; - auto callable = std::make_shared(std::forward(function)); + auto callable = std::make_shared(std::forward(function)); return [callable = std::move(callable)](std::span data, auto&&... caller) { // The caller (the calling UI) is kept with the arguments, as a copy: a callback taking it by reference lives as long as them. using State = std::pair...>, std::tuple>; auto state = std::make_shared(std::tuple...>{caller...}, std::tuple{}); try { - std::apply([&](auto&... decoded) { (msg::FunctionCall::decodeParameter(decoded, data), ...); }, state->second); + std::apply( + [&](auto&... decoded) { + (msg::FunctionCall::decodeParameter(decoded, data), ...); + }, + state->second); if (!data.empty()) throw std::runtime_error("Function call contains trailing parameter data"); } catch (const std::exception& error) { @@ -286,10 +295,16 @@ auto makeDeferredHandler(Function&& function) { } auto sender = std::apply( [&](auto&... kept) { - return std::apply([&](auto&... decoded) { return std::invoke(*callable, kept..., decoded...); }, state->second); + return std::apply( + [&](auto&... decoded) { + return std::invoke(*callable, kept..., decoded...); + }, + state->second); }, state->first); - return networking::ex::let_value(networking::ex::just(std::move(state)), [sender = std::move(sender)](auto&) mutable { return std::move(sender); }); + return networking::ex::let_value(networking::ex::just(std::move(state)), [sender = std::move(sender)](auto&) mutable { + return std::move(sender); + }); }; } @@ -348,8 +363,7 @@ struct callable_traits : callable_traits_impl template struct has_callable_traits_impl : std::false_type {}; template -struct has_callable_traits_impl::Return, typename callable_traits::DecayedArgs>> - : std::true_type {}; +struct has_callable_traits_impl::Return, typename callable_traits::DecayedArgs>> : std::true_type {}; template concept has_callable_traits = has_callable_traits_impl::value; @@ -438,7 +452,7 @@ websocket::Frame makeVoidFrame(msg::CallId callId) { return frame; } -template +template auto makeCppFunctionResponder(Callable&& callable) { return [callable = std::forward(callable)](std::span data, auto& link, msg::CallId callId, auto&&... caller) mutable { msg::FunctionReturn result; @@ -469,9 +483,9 @@ namespace detail { /// What an application that serves a document root is told once: a document root holds development files, and the /// development path of an interface is not hand-written pages there but TypeScript/TSX in ui/ built by wf. inline constexpr std::string_view developmentPathNote = - "WebFront: serving local files from documentRoot (development only). The intended development path is a TypeScript/TSX " - "interface in ui/, built with `wf dev` in the terminal of app.bootstrap(\"developer\"); an agent can run wf through MCP " - "(docs/DEVELOPING_WITH_AGENTS.md)."; + "WebFront: serving local files from documentRoot (development only). The intended development path is a TypeScript/TSX " + "interface in ui/, built with `wf dev` in the terminal of app.bootstrap(\"developer\"); an agent can run wf through MCP " + "(docs/DEVELOPING_WITH_AGENTS.md)."; /// Set once the process has written developmentPathNote. inline std::atomic_flag developmentPathNoted; @@ -527,7 +541,9 @@ inline bool noteDevelopmentPath() { /// The port of a configuration that does not choose one: WEBFRONT_PORT when it is set, "9002" otherwise. A server created /// from such a configuration (an empty `WebFrontConfig::port`) also falls back to a free port when "9002" is taken. -[[nodiscard]] inline std::string defaultPort() { return environmentPort().value_or("9002"); } +[[nodiscard]] inline std::string defaultPort() { + return environmentPort().value_or("9002"); +} /** * @brief Configuration for the newcomer-friendly default construction of BasicWF. @@ -539,7 +555,7 @@ inline bool noteDevelopmentPath() { * root, and the embedded fallback page. */ struct WebFrontConfig { - std::string address{"127.0.0.1"}; + std::string address{"127.0.0.1"}; /// "0" requests an ephemeral port with TCPStdnet. The frontend receives the bound port. Empty (the default) takes /// defaultPort(): WEBFRONT_PORT, else 9002, and then, 9002 being taken, a free port, so that several applications start side /// by side. A port that is chosen, here or by WEBFRONT_PORT, is never replaced: when it is taken the start fails. @@ -547,18 +563,18 @@ struct WebFrontConfig { std::filesystem::path documentRoot{}; ContentPolicy contentPolicy{}; /// Initial window of the embedded frontends; the title defaults to the executable's name. - WindowOptions window{}; + WindowOptions window{}; /// Treats a connection whose peer address is the loopback as a local client (UI::isLocalClient) although it is /// not the view of an embedded frontend. This reintroduces a decision by address: it is unsafe on a shared machine /// and behind a local proxy or an SSH tunnel, which also arrive from the loopback. Off by default (ADR-020). - bool trustLoopbackClients = false; + bool trustLoopbackClients = false; /// How the application declares that a connection other than the view of an embedded frontend (the system browser /// among them) reaches it, which decides whether such a connection may read files (ADR-020 rule 3). Never deduced /// from an address or a `Forwarded` header. `loopbackAttested` is refused at construction unless `address` is a /// loopback address; the other declarations are the integrator's word, which WebFront does not verify. - RemoteFileTransport remoteFileTransport = RemoteFileTransport::refused; + RemoteFileTransport remoteFileTransport = RemoteFileTransport::refused; /// Allows the optional PtyPage component. Requires a literal loopback bind and a bridge policy limited to the application's Origin. - bool allowPtyPages = false; + bool allowPtyPages = false; /// PEM identity for the optional HTTPS provider (webfront/tls/WebFront.hpp). std::shared_ptr tlsCredentials{}; }; @@ -599,9 +615,10 @@ namespace detail { return false; unsigned value = 0; for (const char c : group) { - const unsigned digit = c >= '0' && c <= '9' ? static_cast(c - '0') + const unsigned digit = c >= '0' && c <= '9' ? static_cast(c - '0') : c >= 'a' && c <= 'f' ? static_cast(c - 'a' + 10) - : c >= 'A' && c <= 'F' ? static_cast(c - 'A' + 10) : 16u; + : c >= 'A' && c <= 'F' ? static_cast(c - 'A' + 10) + : 16u; if (digit > 15) return false; value = value * 16 + digit; @@ -626,7 +643,13 @@ namespace detail { std::vector all = head; all.insert(all.end(), 8 - head.size() - tail.size(), 0u); all.insert(all.end(), tail.begin(), tail.end()); - return all.size() == 8 && std::all_of(all.begin(), all.end() - 1, [](unsigned g) { return g == 0; }) && all.back() == 1; + return all.size() == 8 + && std::all_of(all.begin(), + all.end() - 1, + [](unsigned g) { + return g == 0; + }) + && all.back() == 1; } /// True for the literal loopback addresses a server can be configured with: 127.x.y.z and ::1 in any spelling, bracketed or not. @@ -640,17 +663,17 @@ namespace detail { return false; // Four decimal octets of 0 to 255 without leading zeros: the string must read the same to every resolver (127.256.0.1 or // 127.0.0.010 are not literal addresses, and a resolver could take them for names). - int octets = 0; - unsigned value = 0; - int digits = 0; + int octets = 0; + unsigned value = 0; + int digits = 0; bool leadingZero = false; for (const char c : address) { if (c == '.') { if (digits == 0) return false; ++octets; - value = 0; - digits = 0; + value = 0; + digits = 0; leadingZero = false; } else if (c >= '0' && c <= '9') { if (digits == 1 && leadingZero) @@ -693,8 +716,10 @@ inline std::shared_ptr makeReadBinding(const WebFrontConfig& config } } // namespace detail -template +template class BasicWF { public: using Net = NetProvider; @@ -739,12 +764,25 @@ class BasicWF { loopbackPeer = !error && detail::isLoopbackAddress(peer.address()); } } - auto link = std::make_shared>(std::move(socket), id, [this](WebLinkEvent event) { - onEvent(event); - }, httpServer.taskScope(), false); + auto link = std::make_shared>( + std::move(socket), + id, + [this](WebLinkEvent event) { + onEvent(event); + }, + httpServer.taskScope(), + false); { std::scoped_lock lock{linksMutex}; - webLinks.emplace(id, Connection{.link = link, .generation = generation, .thread = std::this_thread::get_id(), .closed = false, .stage = Connection::Stage::handshaking, .deferred = {}, .viewAssociated = false, .loopbackPeer = loopbackPeer}); + webLinks.emplace(id, + Connection{.link = link, + .generation = generation, + .thread = std::this_thread::get_id(), + .closed = false, + .stage = Connection::Stage::handshaking, + .deferred = {}, + .viewAssociated = false, + .loopbackPeer = loopbackPeer}); } link->start(); // registered first: every event it dispatches finds it }); @@ -754,7 +792,9 @@ class BasicWF { } public: - [[nodiscard]] bool allowsPtyPages() const noexcept { return ptyPagesAllowed; } + [[nodiscard]] bool allowsPtyPages() const noexcept { + return ptyPagesAllowed; + } // Preserved for source compatibility; binds all interfaces like it always has, unlike the // loopback-by-default WebFrontConfig constructor above. @@ -766,7 +806,9 @@ class BasicWF { BasicWF& operator=(const BasicWF&) = delete; /** @brief The listening port, including the OS-assigned TCPStdnet port when configured with "0". */ - std::string_view port() const noexcept { return httpPort; } + std::string_view port() const noexcept { + return httpPort; + } ~BasicWF() noexcept { stopAndJoinServer(); @@ -823,10 +865,12 @@ class BasicWF { if (!handler) throw std::invalid_argument("A read route needs a handler"); if (!prefix.starts_with(ReadBinding::servicesPath) || prefix.size() == ReadBinding::servicesPath.size() || prefix.starts_with(ReadBinding::bindPath)) - throw std::invalid_argument("A read route lives under " + std::string(ReadBinding::servicesPath) + ", not under " + std::string(ReadBinding::bindPath)); - auto id = automation::channel::nonce(); // this registration's identity: its grants work nowhere else - auto registration = httpServer.addRoute(prefix, readBinding->readHandler(id, prefix, std::move(handler)), true, - [](http::RouteReply& reply) { detail::hardenRead(reply, {}); }); + throw std::invalid_argument("A read route lives under " + std::string(ReadBinding::servicesPath) + ", not under " + + std::string(ReadBinding::bindPath)); + auto id = automation::channel::nonce(); // this registration's identity: its grants work nowhere else + auto registration = httpServer.addRoute(prefix, readBinding->readHandler(id, prefix, std::move(handler)), true, [](http::RouteReply& reply) { + detail::hardenRead(reply, {}); + }); return ReadRoute{std::move(id), prefix, readBinding, std::move(registration)}; } @@ -862,7 +906,9 @@ class BasicWF { /// The interface thread of the frontend: available while an embedded frontend's loop runs (or the system browser's /// optional loop mode), never for a frontend without one. See frontend/UIExecutor.hpp for the completion rules. [[nodiscard]] frontend::UIExecutor uiExecutor() const { - if constexpr (requires { { Frontend::uiExecutor() } -> std::same_as; }) + if constexpr (requires { + { Frontend::uiExecutor() } -> std::same_as; + }) return Frontend::uiExecutor(); else return {}; @@ -872,7 +918,9 @@ class BasicWF { /// frontend without one. It names the window, not a connection: UI::nativeWindow() also checks that the caller's view /// is that window. [[nodiscard]] frontend::NativeWindow nativeWindow() const { - if constexpr (requires { { Frontend::nativeWindow() } -> std::same_as; }) + if constexpr (requires { + { Frontend::nativeWindow() } -> std::same_as; + }) return Frontend::nativeWindow(); else return {}; @@ -908,7 +956,7 @@ class BasicWF { template friend struct testing::ConnectionIds; // lets a test start the identifiers near their wrap template - friend struct testing::LaunchSecret; // lets a test present the secret an embedded view would + friend struct testing::LaunchSecret; // lets a test present the secret an embedded view would /// Sends `call` to each browser not reported closed whose onUIStarted handlers have returned: at once, on the /// calling thread and outside every lock. For a browser whose handlers are running, `call` is kept, within its @@ -1131,7 +1179,7 @@ class BasicWF { ~Showing() { if (owns) { ++self.showEpoch; // even: a reader that saw the odd value and sees this one reads nothing - self.showThread = std::thread::id{}; + self.showThread = std::thread::id{}; detail::FrontendSessionOwner::owner = nullptr; } } @@ -1148,7 +1196,12 @@ class BasicWF { if constexpr (networking::secureTransport) static_assert(acceptsViewLaunch, "An HTTPS frontend must accept ViewLaunch in open()"); if constexpr (acceptsViewLaunch) - Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); + Frontend::open(httpAddress, + httpPort, + htmlFilename, + contentPolicy, + windowOptions, + ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); }) Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy); }) @@ -1226,10 +1279,9 @@ class BasicWF { * which show() does not give them either (ADR-020). */ void start(std::string_view page = "index.html") { - constexpr bool secure = networking::secureTransport; - constexpr bool canLaunch = secure - ? requires { Frontend::launchHttps(std::string_view{}, std::string_view{}, std::string_view{}); } - : requires { Frontend::launch(std::string_view{}, std::string_view{}, std::string_view{}); }; + constexpr bool secure = networking::secureTransport; + constexpr bool canLaunch = secure ? requires { Frontend::launchHttps(std::string_view{}, std::string_view{}, std::string_view{}); } + : requires { Frontend::launch(std::string_view{}, std::string_view{}, std::string_view{}); }; if constexpr (secure) static_assert(canLaunch, "webfront::BasicWF::start(): an HTTPS frontend must provide launchHttps(address, port, page)"); else @@ -1274,9 +1326,13 @@ class BasicWF { const auto epoch = showEpoch.load(); if (epoch % 2 == 0) return false; - if constexpr (requires { { Frontend::uiExecutor() } -> std::same_as; }) { + if constexpr (requires { + { Frontend::uiExecutor() } -> std::same_as; + }) { bool publishesSessions = true; // false: the frontend in use has no executor (an empty handle), so no session to name - if constexpr (requires { { Frontend::publishesUIExecutor() } -> std::same_as; }) + if constexpr (requires { + { Frontend::publishesUIExecutor() } -> std::same_as; + }) publishesSessions = Frontend::publishesUIExecutor(); if (publishesSessions) { const auto shows = showThread.load(); @@ -1287,13 +1343,17 @@ class BasicWF { return false; // Another application may open a window between this check and the toolkit call: a frontend that // takes the session checks it again where the request runs, so that it never closes a later one. - if constexpr (requires { { Frontend::requestClose(session) } -> std::same_as; }) + if constexpr (requires { + { Frontend::requestClose(session) } -> std::same_as; + }) return Frontend::requestClose(session); } } if (showEpoch.load() != epoch) return false; - if constexpr (requires { { Frontend::requestClose() } -> std::same_as; }) + if constexpr (requires { + { Frontend::requestClose() } -> std::same_as; + }) return Frontend::requestClose(); else return Frontend::requestClose(std::nullopt); // only the form that takes a session, and none is published @@ -1317,7 +1377,9 @@ class BasicWF { [[nodiscard]] static bool canShowSecondaryWindow() { if constexpr (!supportsSecondaryWindow) return false; - else if constexpr (requires { { Frontend::secondaryWindowsAvailable() } -> std::convertible_to; }) + else if constexpr (requires { + { Frontend::secondaryWindowsAvailable() } -> std::convertible_to; + }) return Frontend::secondaryWindowsAvailable(); else return true; @@ -1354,7 +1416,7 @@ class BasicWF { if (epoch % 2 == 0) throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): this application is not showing a window; call show() first"); const auto executor = Frontend::uiExecutor(); - const auto session = executor.session(); + const auto session = executor.session(); if (!session || session->thread != showThread.load() || showEpoch.load() != epoch) throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): this application has no active interface session"); if (options.background.empty()) @@ -1365,7 +1427,11 @@ class BasicWF { frontend::invokeOnUIThreadWhenReady(executor, [&] { if (showEpoch.load() != epoch || executor.session() != session) throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): the interface session has ended"); - Frontend::openSecondaryWindow(httpAddress, httpPort, page, contentPolicy, options, + Frontend::openSecondaryWindow(httpAddress, + httpPort, + page, + contentPolicy, + options, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); }); } catch (const frontend::UIExecutorUnavailable&) { @@ -1382,12 +1448,14 @@ class BasicWF { * `cppFunction` callback, run it on the interface thread instead. */ bool requestClose(std::string_view page) { - if constexpr (supportsSecondaryWindow && requires { { Frontend::closeSecondaryWindow(page) } -> std::same_as; }) { + if constexpr (supportsSecondaryWindow && requires { + { Frontend::closeSecondaryWindow(page) } -> std::same_as; + }) { const auto epoch = showEpoch.load(); if (epoch % 2 == 0) return false; const auto executor = Frontend::uiExecutor(); - const auto session = executor.session(); + const auto session = executor.session(); if (!session || session->thread != showThread.load() || showEpoch.load() != epoch) return false; bool closed = false; @@ -1459,8 +1527,8 @@ class BasicWF { for (auto& [id, document] : domDocuments) document->close(); domDocuments.clear(); - std::map released; - std::scoped_lock lock{linksMutex}; + std::map released; + std::scoped_lock lock{linksMutex}; released.swap(webLinks); } @@ -1471,7 +1539,7 @@ class BasicWF { bool registerDeferred(std::string functionName, auto&& function) { // Naming the value type checks the contract at registration: one value at most, one kind of value completion. using DeferredValue [[maybe_unused]] = detail::deferred_value_t; - const auto start = [this](auto invoke, WebLink& link, msg::CallId callId, UI caller) { + const auto start = [this](auto invoke, WebLink& link, msg::CallId callId, UI caller) { this->startDeferred(std::move(invoke), link, callId, caller); }; if constexpr (detail::takes_caller::value) { @@ -1479,7 +1547,13 @@ class BasicWF { return cppFunctions .try_emplace(std::move(functionName), [start, handler](std::span data, WebLink& link, msg::CallId callId, UI caller) mutable { - start([&] { return handler(data, caller); }, link, callId, caller); + start( + [&] { + return handler(data, caller); + }, + link, + callId, + caller); }) .second; } else { @@ -1487,7 +1561,13 @@ class BasicWF { return cppFunctions .try_emplace(std::move(functionName), [start, handler](std::span data, WebLink& link, msg::CallId callId, UI caller) mutable { - start([&] { return handler(data); }, link, callId, caller); + start( + [&] { + return handler(data); + }, + link, + callId, + caller); }) .second; } @@ -1503,7 +1583,7 @@ class BasicWF { template void startDeferred(Invoke invoke, WebLink& link, msg::CallId callId, UI caller) { const auto [calls, generation] = deferredCallsOf(caller); - const auto key = calls ? calls->reserve(callId) : 0; + const auto key = calls ? calls->reserve(callId) : 0; if (key == 0) { // The connection closed (nobody is left to answer), or a call with this identifier is still running: the common // reception drops such a call before it gets here, and this claim is the last guard. @@ -1556,18 +1636,22 @@ class BasicWF { /// completed stopped by something other than this call's own stop request. When that request was made (the /// connection closed, the application is stopping) nothing is sent: nobody is left to read it. template - Task respondLater(UI caller, WebLinkGeneration generation, std::shared_ptr calls, msg::CallId callId, std::uint64_t key, Sender sender) { + Task + respondLater(UI caller, WebLinkGeneration generation, std::shared_ptr calls, msg::CallId callId, std::uint64_t key, Sender sender) { struct Finish { detail::DeferredCalls& calls; msg::CallId callId; std::uint64_t key; - ~Finish() { calls.finish(callId, key); } + ~Finish() { + calls.finish(callId, key); + } } finish{*calls, callId, key}; - const auto token = co_await networking::ex::read_env(networking::ex::get_stop_token); + const auto token = co_await networking::ex::read_env(networking::ex::get_stop_token); std::optional> answer; try { auto stoppable = networking::ex::stopped_as_error( - std::move(sender), std::make_exception_ptr(detail::makeBridgeError(bridge_code::cancelled, "The C++ callback was cancelled"))); + std::move(sender), + std::make_exception_ptr(detail::makeBridgeError(bridge_code::cancelled, "The C++ callback was cancelled"))); // One answer frame whether the sender completes with a value or without: the message is built where it completes. auto framed = networking::ex::then(std::move(stoppable), [callId](auto&&... values) -> websocket::Frame { if constexpr (sizeof...(values) == 0) @@ -1601,47 +1685,47 @@ class BasicWF { } // Before the server: the routes' handlers use it, and the server drains them before it is destroyed. - std::shared_ptr readBinding; - http::Server httpServer; - http::RouteTable::Registration bindRoute; - std::string httpAddress; - std::string httpPort; - std::filesystem::path httpDocRoot; - ContentPolicy contentPolicy; - WindowOptions windowOptions; - const std::string viewSecret = detail::newViewSecret(); // this launch's proof of an embedded view - const bool trustLoopbackClients; - const bool ptyPagesAllowed; - bool developerEnvironment = false; - std::atomic launched{false}; // start() was called - std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any - std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit - std::atomic showRunning{false}; // a show() of this application is in progress - std::atomic shown{false}; // show() was called, whether or not its server still runs - mutable std::mutex linksMutex; // guards webLinks, read from any thread + std::shared_ptr readBinding; + http::Server httpServer; + http::RouteTable::Registration bindRoute; + std::string httpAddress; + std::string httpPort; + std::filesystem::path httpDocRoot; + ContentPolicy contentPolicy; + WindowOptions windowOptions; + const std::string viewSecret = detail::newViewSecret(); // this launch's proof of an embedded view + const bool trustLoopbackClients; + const bool ptyPagesAllowed; + bool developerEnvironment = false; + std::atomic launched{false}; // start() was called + std::atomic showThread{}; // the thread inside this application's Frontend::open(), if any + std::atomic showEpoch{0}; // odd while show() runs its frontend, changes at each entry and exit + std::atomic showRunning{false}; // a show() of this application is in progress + std::atomic shown{false}; // show() was called, whether or not its server still runs + mutable std::mutex linksMutex; // guards webLinks, read from any thread struct Connection { std::shared_ptr> link; WebLinkGeneration generation; std::thread::id thread; bool closed; enum class Stage { handshaking, starting, started }; - Stage stage = Stage::handshaking; // starting while its onUIStarted handlers run + Stage stage = Stage::handshaking; // starting while its onUIStarted handlers run std::vector> deferred; // sendToStartedLinks() calls while starting - bool viewAssociated = false; // presented the launch secret of an embedded view - bool loopbackPeer = false; // peer address was the loopback (read only with trustLoopbackClients) - std::shared_ptr deferredCalls = std::make_shared(); // calls a callback answers later + bool viewAssociated = false; // presented the launch secret of an embedded view + bool loopbackPeer = false; // peer address was the loopback (read only with trustLoopbackClients) + std::shared_ptr deferredCalls = std::make_shared(); // calls a callback answers later }; - std::map webLinks; - WebLinkId idsCounter{0}; - WebLinkGeneration generationCounter{0}; // guarded by linksMutex; the first connection is 1 - std::function uiStartedHandler; - std::shared_ptr> uiSubscribers = std::make_shared>(); - std::shared_ptr> uiClosedSubscribers = std::make_shared>(); + std::map webLinks; + WebLinkId idsCounter{0}; + WebLinkGeneration generationCounter{0}; // guarded by linksMutex; the first connection is 1 + std::function uiStartedHandler; + std::shared_ptr> uiSubscribers = std::make_shared>(); + std::shared_ptr> uiClosedSubscribers = std::make_shared>(); std::map, WebLink&, msg::CallId, UI)>, std::less<>> cppFunctions; // Keyed by identifier alone: a document is closed and erased on its connection's closed event, before the link is // released and its identifier can be reused, so two connections never share an entry. - std::map> domDocuments; - std::thread serverThread; // Background thread running the HTTP server + std::map> domDocuments; + std::thread serverThread; // Background thread running the HTTP server private: static Task flushDomAfter(UI ui, std::shared_ptr state) { @@ -1745,7 +1829,7 @@ class BasicWF { { std::scoped_lock lock{linksMutex}; if (auto found = webLinks.find(event.webLinkId); found != webLinks.end()) { - found->second.stage = Connection::Stage::starting; + found->second.stage = Connection::Stage::starting; // Raised once, never lowered: the secret is judged at the single handshake WebLink dispatches. found->second.viewAssociated = found->second.viewAssociated || detail::viewSecretMatches(viewSecret, event.text); bindKey = found->second.generation; @@ -1778,7 +1862,7 @@ class BasicWF { // Shutdown cancels the connections' writes, which then fail and report a closure: not a disconnection. if (httpServer.taskScope().stopRequested()) break; - std::optional closedGeneration; + std::optional closedGeneration; std::shared_ptr stoppedCalls; { std::scoped_lock lock{linksMutex}; @@ -1841,7 +1925,7 @@ using BasicWFWithFrontend = BasicWF; using WebFront = BasicWF; template using WebFrontWithFrontend = BasicWF; -using UI = WebFront::UI; +using UI = WebFront::UI; #ifdef WEBFRONT_EMBED_CEF inline constexpr bool cefAvailable = true; diff --git a/include/webfront/automation/Binding.hpp b/include/webfront/automation/Binding.hpp index 0e68bde8..b494f887 100644 --- a/include/webfront/automation/Binding.hpp +++ b/include/webfront/automation/Binding.hpp @@ -75,7 +75,8 @@ void (async () => { })(); )JS"; -inline std::string connectionScript(std::string_view capability, const std::vector>& versioned = {}, std::string_view notice = {}) { +inline std::string +connectionScript(std::string_view capability, const std::vector>& versioned = {}, std::string_view notice = {}) { std::string script{connectionScriptTemplate}; std::string list = "["; for (const auto& [operation, since] : versioned) @@ -98,7 +99,7 @@ class Binding { authentication::PageAuthentication pageAuthentication; std::string launchToken = channel::nonce(); std::string notice; // what the human sees in the terminal: grants and how to attach - bool closing = false; + bool closing = false; void authorize(const AppUI& ui, std::string_view sequence, std::string_view mac, std::string_view method, std::initializer_list args) { if (!browser || *browser != ui) @@ -125,7 +126,8 @@ class Binding { throw std::runtime_error("Automation window claim rejected"); owned->browser = ui; owned->launchToken.clear(); // one successful claim; later connections cannot replace the selected browser - ui.addScript(owned->closing ? std::string{"window.close()"} : connectionScript(owned->pageAuthentication.secret(), owned->session->versionedOperations(), owned->notice)); + ui.addScript(owned->closing ? std::string{"window.close()"} + : connectionScript(owned->pageAuthentication.secret(), owned->session->versionedOperations(), owned->notice)); return std::string{"null"}; }); app.cppFunction("webfront.automation.poll", [owned](AppUI ui, std::string sequence, std::string mac, std::string output) { diff --git a/include/webfront/automation/Channel.hpp b/include/webfront/automation/Channel.hpp index 63aa6652..8609be83 100644 --- a/include/webfront/automation/Channel.hpp +++ b/include/webfront/automation/Channel.hpp @@ -61,7 +61,7 @@ inline constexpr Handle invalid = -1; inline void close(Handle socket) { ::close(socket); } -struct Runtime { }; +struct Runtime {}; inline bool wait(Handle socket, short events, int milliseconds) { pollfd item{socket, events, 0}; return ::poll(&item, 1, milliseconds) > 0; @@ -158,7 +158,7 @@ inline std::filesystem::path outsideProject(const Session& controller, const std inline bool transientRemovalFailure([[maybe_unused]] const std::error_code& error) noexcept { #ifdef _WIN32 return error.category() == std::system_category() - && (error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_LOCK_VIOLATION || error.value() == ERROR_ACCESS_DENIED); + && (error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_LOCK_VIOLATION || error.value() == ERROR_ACCESS_DENIED); #else return false; #endif @@ -243,7 +243,7 @@ struct Descriptor { ::close(value); } Descriptor(const Descriptor&) = delete; - explicit Descriptor(int descriptor) : value(descriptor) { } + explicit Descriptor(int descriptor) : value(descriptor) {} }; inline std::string readEndpointFile(int directory, const char* name = "endpoint.json") { Descriptor file{::openat(directory, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)}; @@ -279,12 +279,12 @@ inline std::string readEndpoint(const std::filesystem::path& directory, const ch }; // Deny directory rename/deletion while resolving and reading its endpoint. FileHandle parent{CreateFileW(directory.c_str(), - FILE_READ_ATTRIBUTES, - FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, - OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, - nullptr)}; + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + nullptr)}; BY_HANDLE_FILE_INFORMATION parentInfo{}; if (parent.value == INVALID_HANDLE_VALUE || !GetFileInformationByHandle(parent.value, &parentInfo) || !(parentInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (parentInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) diff --git a/include/webfront/automation/Contract.hpp b/include/webfront/automation/Contract.hpp index aac7aa8b..8cf15a16 100644 --- a/include/webfront/automation/Contract.hpp +++ b/include/webfront/automation/Contract.hpp @@ -65,7 +65,7 @@ inline std::vector contractStrings(std::string_view value) { } class OperationError : public std::runtime_error { public: - OperationError(std::string category, std::string message) : std::runtime_error(std::move(message)), code(std::move(category)) { } + OperationError(std::string category, std::string message) : std::runtime_error(std::move(message)), code(std::move(category)) {} const std::string code; }; /// The channel to the native owner failed: the outcome of the request in flight is unknown. @@ -93,9 +93,12 @@ inline const auto& operationDefinitions() { const Object schemas{contractObject().raw("x-webfront-operations")}; for (const auto& [name, raw] : schemas.members()) { const Object schema{raw}; - values.emplace( - name, - OperationDefinition{schema, schema.string("permission"), contractStrings(schema.raw("arguments")), contractStrings(schema.raw("required")), schema.string("since")}); + values.emplace(name, + OperationDefinition{schema, + schema.string("permission"), + contractStrings(schema.raw("arguments")), + contractStrings(schema.raw("required")), + schema.string("since")}); } return values; }(); diff --git a/include/webfront/automation/Discovery.hpp b/include/webfront/automation/Discovery.hpp index ea4e3cec..11ebf15e 100644 --- a/include/webfront/automation/Discovery.hpp +++ b/include/webfront/automation/Discovery.hpp @@ -6,10 +6,9 @@ /// only that private configuration file contains: reading a record does not allow operating the session. Records are /// removed on closure; one whose process is gone is dropped by the next listing, with the private directory named after it. #pragma once -#include "Platform.hpp" - #include "Channel.hpp" #include "Json.hpp" +#include "Platform.hpp" #include #include @@ -22,7 +21,7 @@ #include #include #ifndef _WIN32 -#include + #include #endif #include #include @@ -67,8 +66,8 @@ inline std::filesystem::path defaultDirectory() { /// A session identifier names the record file: only plain alphanumeric names are ever opened. inline bool validIdentifier(std::string_view id) { return !id.empty() && id.size() <= 64 && std::ranges::all_of(id, [](char c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); - }); + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + }); } /// One shared session as its owner published it. `allow` is the JSON array of its grants. @@ -83,14 +82,14 @@ struct Entry { /// The record as it is written. std::string json() const { std::map members{ - {"version", "1"}, - {"session", webfront::json::quote(session)}, - {"pid", std::to_string(pid)}, - {"project", webfront::json::quote(project)}, - {"allow", allow}, - {"callbacks", callbacks}, - {"endpoint", webfront::json::quote(endpoint)}, - {"state", webfront::json::quote("running")}, + { "version", "1"}, + { "session", webfront::json::quote(session)}, + { "pid", std::to_string(pid)}, + { "project", webfront::json::quote(project)}, + { "allow", allow}, + {"callbacks", callbacks}, + { "endpoint", webfront::json::quote(endpoint)}, + { "state", webfront::json::quote("running")}, }; if (!mcp.empty()) { members.emplace("mcp", webfront::json::quote(mcp)); @@ -140,7 +139,9 @@ inline void preparePrivateDirectory(const std::filesystem::path& directory) { throw std::runtime_error("The automation discovery directory must be a real directory"); struct Closer { int fd; - ~Closer() { ::close(fd); } + ~Closer() { + ::close(fd); + } } closer{descriptor}; struct stat info{}; if (::fstat(descriptor, &info) != 0 || !S_ISDIR(info.st_mode) || info.st_uid != ::geteuid()) @@ -215,15 +216,15 @@ inline std::optional readRecord(const std::filesystem::path& path) { try { const Object record{text, recordLimit}; Entry entry; - entry.session = record.string("session"); - entry.project = record.string("project"); - entry.endpoint = record.string("endpoint"); - entry.allow = record.raw("allow", "[]"); - entry.callbacks = record.raw("callbacks", "[]"); + entry.session = record.string("session"); + entry.project = record.string("project"); + entry.endpoint = record.string("endpoint"); + entry.allow = record.raw("allow", "[]"); + entry.callbacks = record.raw("callbacks", "[]"); entry.mcp = record.string("mcp"); entry.configuration = record.string("configuration"); - const auto pid = record.raw("pid", "0"); - entry.pid = std::stol(pid); + const auto pid = record.raw("pid", "0"); + entry.pid = std::stol(pid); if (record.raw("version") != "1" || !validIdentifier(entry.session) || path.stem().string() != entry.session || entry.project.empty() || entry.endpoint.empty() || !entry.allow.starts_with('[') || !entry.callbacks.starts_with('[') || entry.pid <= 0) return std::nullopt; @@ -263,7 +264,7 @@ inline std::vector list(const std::filesystem::path& directory, bool prun // the resolved path (channel::outsideProject), so the discovery directory is resolved the same way, and // the session's directory must be a real child of it, not a link put in its place. std::error_code unresolved; - const auto own = std::filesystem::weakly_canonical(std::filesystem::absolute(directory), unresolved) / entry->session; + const auto own = std::filesystem::weakly_canonical(std::filesystem::absolute(directory), unresolved) / entry->session; const auto kind = std::filesystem::symlink_status(own, unresolved); if (!unresolved && std::filesystem::is_directory(kind) && std::filesystem::path(entry->endpoint).lexically_normal().generic_string() == own.lexically_normal().generic_string()) { diff --git a/include/webfront/automation/Enable.hpp b/include/webfront/automation/Enable.hpp index a62e154d..532b6e5c 100644 --- a/include/webfront/automation/Enable.hpp +++ b/include/webfront/automation/Enable.hpp @@ -64,7 +64,7 @@ template /// The end of the startup window, saturated (see `deadlineAfter`). [[nodiscard]] constexpr std::chrono::steady_clock::time_point startupDeadline(std::chrono::steady_clock::time_point launched, - std::chrono::seconds startup) noexcept { + std::chrono::seconds startup) noexcept { return deadlineAfter(launched, startup); } @@ -201,7 +201,7 @@ class Automation { for (const auto& callback : callbackNames) names += (names.empty() ? "" : ", ") + callback; const auto granted = std::string{authenticationDisabled ? "WARNING: MCP authentication disabled; local processes can use granted operations; " : ""} - + "grants: " + (list.empty() ? std::string{"none"} : list) + (names.empty() ? "" : "; callbacks: " + names); + + "grants: " + (list.empty() ? std::string{"none"} : list) + (names.empty() ? "" : "; callbacks: " + names); return "WebFront MCP (" + granted + "): " + mcp.url() + " - client configuration: " + mcp.configuration().generic_string(); } /// `base` marked as shared with an agent, for a window title: automation must be visible to the person using it. @@ -239,11 +239,13 @@ class Automation { throw std::invalid_argument("Automation startupTimeout must be positive"); if (options.closeGrace < std::chrono::milliseconds::zero()) throw std::invalid_argument("Automation closeGrace must not be negative"); - return std::make_shared(SessionOptions{.project = app.projectDirectory(), .allow = options.grants, .timeout = options.timeout, .callbacks = options.callbacks}); + return std::make_shared( + SessionOptions{.project = app.projectDirectory(), .allow = options.grants, .timeout = options.timeout, .callbacks = options.callbacks}); } // `directory`, or a new directory named after the session in the (private) discovery directory. The records of the // instances that ended without closing (a forced end) are removed first, with the private directories named after them. - static std::filesystem::path privateDirectoryFor(const AutomationOptions& options, const std::filesystem::path& directoryOfRecords, const Session& session) { + static std::filesystem::path + privateDirectoryFor(const AutomationOptions& options, const std::filesystem::path& directoryOfRecords, const Session& session) { discovery::preparePrivateDirectory(directoryOfRecords); (void)discovery::list(directoryOfRecords); if (!options.directory.empty()) @@ -262,22 +264,22 @@ class Automation { .configuration = mcp.configuration().generic_string()}; } - std::shared_ptr session; - std::filesystem::path discoveryDirectory; - channel::PrivateDirectory privateDirectory; - mcphttp::Server mcp; - discovery::Registration registration; - std::vector grants; - std::vector callbackNames; - bool authenticationDisabled; - std::chrono::milliseconds grace; - std::function unresponsive; - std::mutex revocation; - bool revoked = false; + std::shared_ptr session; + std::filesystem::path discoveryDirectory; + channel::PrivateDirectory privateDirectory; + mcphttp::Server mcp; + discovery::Registration registration; + std::vector grants; + std::vector callbackNames; + bool authenticationDisabled; + std::chrono::milliseconds grace; + std::function unresponsive; + std::mutex revocation; + bool revoked = false; std::chrono::steady_clock::time_point launched; - std::chrono::seconds startup; - Binding binding; - std::jthread supervisor; + std::chrono::seconds startup; + Binding binding; + std::jthread supervisor; }; /// Enables automation on an application; keep the result alive until after `show()` and call `close()` before diff --git a/include/webfront/automation/Mcp.hpp b/include/webfront/automation/Mcp.hpp index cfa66af1..2402c60c 100644 --- a/include/webfront/automation/Mcp.hpp +++ b/include/webfront/automation/Mcp.hpp @@ -8,7 +8,7 @@ namespace webfront::automation { template class Mcp { public: - explicit Mcp(Backend& controller) : session(controller) { } + explicit Mcp(Backend& controller) : session(controller) {} std::optional receive(std::string_view line) { std::string id = "null"; @@ -51,9 +51,10 @@ class Mcp { initialized = true; // Lifecycle version negotiation: offer our supported version when the requested one differs. // A client that does not support it should disconnect, rather than use a mismatched profile. - return success(id, - R"({"protocolVersion":"2025-11-25","capabilities":{"tools":{}},"serverInfo":{"name":"webfront-developer","version":"1.0.0"},"instructions":)" - + json::quote(mcpInstructions) + "}"); + return success( + id, + R"({"protocolVersion":"2025-11-25","capabilities":{"tools":{}},"serverInfo":{"name":"webfront-developer","version":"1.0.0"},"instructions":)" + + json::quote(mcpInstructions) + "}"); } if (!ready) return error(id, -32600, "Initialize the MCP connection first"); diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 3ceded13..2175f514 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -46,24 +46,42 @@ struct Answer { static std::string_view reason(int status) { switch (status) { - case 100: return "Continue"; - case 200: return "OK"; - case 202: return "Accepted"; - case 204: return "No Content"; - case 400: return "Bad Request"; - case 401: return "Unauthorized"; - case 403: return "Forbidden"; - case 404: return "Not Found"; - case 405: return "Method Not Allowed"; - case 406: return "Not Acceptable"; - case 411: return "Length Required"; - case 413: return "Content Too Large"; - case 415: return "Unsupported Media Type"; - case 421: return "Misdirected Request"; - case 431: return "Request Header Fields Too Large"; - case 501: return "Not Implemented"; - case 503: return "Service Unavailable"; - default: return "Internal Server Error"; + case 100: + return "Continue"; + case 200: + return "OK"; + case 202: + return "Accepted"; + case 204: + return "No Content"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 411: + return "Length Required"; + case 413: + return "Content Too Large"; + case 415: + return "Unsupported Media Type"; + case 421: + return "Misdirected Request"; + case 431: + return "Request Header Fields Too Large"; + case 501: + return "Not Implemented"; + case 503: + return "Service Unavailable"; + default: + return "Internal Server Error"; } } std::string serialize() const { @@ -94,7 +112,9 @@ inline std::string trimmed(std::string_view text) { return std::string(text); } inline std::string lower(std::string text) { - std::ranges::transform(text, text.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(text, text.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); return text; } /// The single value of a header; empty when it is missing, nullopt when it is repeated. @@ -217,7 +237,7 @@ inline Screening screen(const http::Request& request, unsigned short port, std:: template class Endpoint { public: - explicit Endpoint(Backend& controller) : backend(controller) { } + explicit Endpoint(Backend& controller) : backend(controller) {} /// Handles a request that `screen` accepted, with its whole body. Answer handle(const http::Request& request, std::string_view body) { @@ -226,9 +246,9 @@ class Endpoint { return refusal(400, "Mcp-Session-Id is repeated"); // Every message of an initialized session, its termination included, names a supported revision (or none, which // MCP lets the server read as its default); a rejected one has no effect on the session. - const auto negotiated = detail::single(request, "MCP-Protocol-Version"); + const auto negotiated = detail::single(request, "MCP-Protocol-Version"); const bool supportedVersion = negotiated && (negotiated->empty() || *negotiated == protocolVersion); - const auto unsupported = [] { + const auto unsupported = [] { return rpcError(400, -32600, "Unsupported MCP-Protocol-Version; this server supports " + std::string(protocolVersion)); }; if (request.method == http::Request::Method::Delete) { @@ -250,7 +270,7 @@ class Endpoint { bool isRequest = false; try { const Object message{body}; - method = message.has("method") ? message.string("method") : std::string{}; + method = message.has("method") ? message.string("method") : std::string{}; isRequest = message.has("id") && message.has("method"); if (!message.has("method")) { // A response of the client: this server sends no request, so there is nothing to route it to. It is @@ -280,7 +300,9 @@ class Endpoint { answer.headers.emplace_back("Mcp-Session-Id", created); const std::scoped_lock lock{mutex}; if (conversations.size() >= maxSessions) { - const auto oldest = std::ranges::min_element(conversations, {}, [](const auto& item) { return item.second->used; }); + const auto oldest = std::ranges::min_element(conversations, {}, [](const auto& item) { + return item.second->used; + }); conversations.erase(oldest); } conversations.emplace(created, std::move(conversation)); @@ -317,7 +339,7 @@ class Endpoint { private: struct Conversation { - explicit Conversation(Backend& backend) : mcp(backend) { } + explicit Conversation(Backend& backend) : mcp(backend) {} std::mutex mutex; Mcp mcp; std::chrono::steady_clock::time_point used = std::chrono::steady_clock::now(); @@ -341,7 +363,10 @@ class Endpoint { inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront", bool authentication = true) { std::string server = "{\"type\":" + json::quote("http") + ",\"url\":" + json::quote(url); if (authentication) - server += ",\"headers\":" + objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}}); + server += ",\"headers\":" + + objectJson({ + {"Authorization", json::quote("Bearer " + std::string(token))} + }); server += "}"; return "{\n \"mcpServers\": {\n " + json::quote(name) + ": " + server + "\n }\n}\n"; } @@ -351,15 +376,16 @@ inline std::string clientConfiguration(std::string_view url, std::string_view to inline void validateTokenOptions(const std::optional& fixed, bool authentication) { if (!authentication && fixed) throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); - if (fixed && (fixed->size() < 32 || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; }))) + if (fixed && (fixed->size() < 32 || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { + return c >= 0x21 && c <= 0x7e; + }))) throw std::invalid_argument("MCP token must contain 32 to 1024 visible ASCII characters without spaces"); } /// A failure to bind or listen on the requested MCP port; retains the native error code. class BindError : public std::system_error { public: - BindError(std::error_code cause, unsigned short port) - : std::system_error(cause, "WebFront cannot listen for MCP on 127.0.0.1:" + std::to_string(port)) { } + BindError(std::error_code cause, unsigned short port) : std::system_error(cause, "WebFront cannot listen for MCP on 127.0.0.1:" + std::to_string(port)) {} /// Whether the native error reports that the requested port is already in use. [[nodiscard]] bool addressInUse() const noexcept { #ifdef _WIN32 @@ -377,15 +403,19 @@ class Server { public: /// @param port 0 (the default) lets the OS choose; a chosen port is never replaced: when it is taken the constructor throws /// @throws std::system_error naming the address, the port and the cause when the listener cannot be bound - Server(std::shared_ptr controller, const std::filesystem::path& directory, unsigned short port = 0, - std::optional fixedToken = std::nullopt, bool authentication = true) + Server(std::shared_ptr controller, + const std::filesystem::path& directory, + unsigned short port = 0, + std::optional fixedToken = std::nullopt, + bool authentication = true) : backend(std::move(controller)), endpoint(*backend), token(selectToken(fixedToken, authentication)), listener(channel::createSocket()), boundPort(bind(listener, port)), address("http://127.0.0.1:" + std::to_string(boundPort) + "/mcp"), - file(directory / configurationFile), authenticate(authentication) { + file(directory / configurationFile), + authenticate(authentication) { channel::nonblocking(listener.value); channel::writeEndpoint(file, clientConfiguration(address, token, "webfront", authenticate)); worker = std::jthread([this](std::stop_token stop) { @@ -449,7 +479,7 @@ class Server { std::size_t headerBytes = 0; std::optional screening{}; std::string body{}; - bool refused = false; + bool refused = false; std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; explicit Pending(channel::Handle handle) : socket(handle) { channel::nonblocking(handle); @@ -544,7 +574,9 @@ class Server { } } revoke{*this}; while (!stop.stop_requested() && !backend->isClosed()) { - std::erase_if(connections, [](const Connection& connection) { return connection.finished.load(); }); + std::erase_if(connections, [](const Connection& connection) { + return connection.finished.load(); + }); #ifdef _WIN32 std::vector items; #else @@ -599,12 +631,11 @@ class Server { auto& connection = connections.emplace_back(); channel::Socket transfer{std::exchange(peer.socket.value, channel::invalid)}; try { - connection.thread = std::jthread( - [this, handle = transfer.value, request = std::move(peer.request), body = std::move(peer.body), &connection] { - respond(handle, request, body); - connection.finished.store(true); - }); - transfer.value = channel::invalid; + connection.thread = std::jthread([this, handle = transfer.value, request = std::move(peer.request), body = std::move(peer.body), &connection] { + respond(handle, request, body); + connection.finished.store(true); + }); + transfer.value = channel::invalid; } catch (...) { connection.finished.store(true); throw; @@ -631,8 +662,7 @@ class Server { if (count == 0 || (count < 0 && !channel::retryableSocketError(channel::socketError()))) break; } - } catch (const std::exception&) { - } + } catch (const std::exception&) {} } }; } // namespace webfront::automation::mcphttp diff --git a/include/webfront/automation/PageAuthentication.hpp b/include/webfront/automation/PageAuthentication.hpp index 19f3c1ae..d39cb1a7 100644 --- a/include/webfront/automation/PageAuthentication.hpp +++ b/include/webfront/automation/PageAuthentication.hpp @@ -1,7 +1,7 @@ /// @brief Authenticate page callbacks without putting a reusable secret on their wire messages. #pragma once -#include "Channel.hpp" #include "../utils/Sha256.hpp" +#include "Channel.hpp" #include #include diff --git a/include/webfront/automation/Session.hpp b/include/webfront/automation/Session.hpp index fd86c91d..5357b23b 100644 --- a/include/webfront/automation/Session.hpp +++ b/include/webfront/automation/Session.hpp @@ -58,7 +58,8 @@ class Session { + json::quote(closed ? "closed" : ready ? "ready" : "starting") - + ",\"allow\":" + stringArray(options.allow) + ",\"callbacks\":" + stringArray(options.callbacks) + ",\"failure\":" + json::quote(failure) + ",\"audit\":" + auditJson() + "}"; + + ",\"allow\":" + stringArray(options.allow) + ",\"callbacks\":" + stringArray(options.callbacks) + ",\"failure\":" + json::quote(failure) + + ",\"audit\":" + auditJson() + "}"; } std::string start(const Object& request, Clock::time_point now = Clock::now()) { @@ -253,8 +254,8 @@ class Session { /// A name an application registered, never an internal `webfront.*` one: letters, digits, `.`, `_`, `-`, at most 128. static bool callbackName(std::string_view name) { return !name.empty() && name.size() <= 128 && !name.starts_with("webfront.") && std::ranges::all_of(name, [](char c) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-'; - }); + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-'; + }); } static bool knownPermission(std::string_view name) { for (const auto& [operation, definition] : operationDefinitions()) @@ -267,14 +268,14 @@ class Session { const auto operation = request.string("operation"); if (!operation.empty() && operation.size() <= 64) return operation; - } catch (const std::exception&) { } + } catch (const std::exception&) {} return ""; } void authorize(const Object& request) const { std::string claimed; try { claimed = request.string("session"); - } catch (const std::exception&) { } + } catch (const std::exception&) {} if (!channel::sameToken(claimed, identity)) throw OperationError("wrong_session", "Wrong automation session"); } diff --git a/include/webfront/components/forms/Form.hpp b/include/webfront/components/forms/Form.hpp index 6a521cb9..346fd2e1 100644 --- a/include/webfront/components/forms/Form.hpp +++ b/include/webfront/components/forms/Form.hpp @@ -84,7 +84,7 @@ inline void discard(const dom::Node& root) noexcept { try { if (root.valid()) root.remove(); - } catch (...) { } + } catch (...) {} } } // namespace detail @@ -106,7 +106,7 @@ class Form { public: /// Built by forms::form(). - Form(std::shared_ptr> s, dom::Node r) : state(std::move(s)), root(r) { } + Form(std::shared_ptr> s, dom::Node r) : state(std::move(s)), root(r) {} /// The `form` element, to remove or move the whole form. dom::Node node() const { return root; @@ -145,7 +145,7 @@ Form form(const dom::Document& doc, dom::Node parent, std::shared_ptr try { root.attribute("class", "wf-form"); // Enter in a text input submits the form: the page must not navigate. - root.listen("submit", [](std::string) { }, {.preventDefault = true, .stopPropagation = false}); + root.listen("submit", [](std::string) {}, {.preventDefault = true, .stopPropagation = false}); for (std::size_t i = 0; i < state->description.fields.size(); ++i) { const auto& field = state->description.fields[i]; auto row = doc.element("label"); @@ -202,7 +202,7 @@ class Inspector { public: /// Built by forms::inspector(). - Inspector(std::shared_ptr> s, dom::Node r) : state(std::move(s)), root(r) { } + Inspector(std::shared_ptr> s, dom::Node r) : state(std::move(s)), root(r) {} /// The `table` element. dom::Node node() const { return root; diff --git a/include/webfront/components/forms/Reflection.hpp b/include/webfront/components/forms/Reflection.hpp index a3c1b84d..3a0abef7 100644 --- a/include/webfront/components/forms/Reflection.hpp +++ b/include/webfront/components/forms/Reflection.hpp @@ -22,7 +22,7 @@ namespace webfront::forms { /// The label of a member. A string literal is not a structural value: the text is copied into static storage. struct Label { const char* text; - consteval Label(const char* value) : text(std::define_static_string(std::string_view(value))) { } + consteval Label(const char* value) : text(std::define_static_string(std::string_view(value))) {} }; /// The inclusive bounds of a numeric member. diff --git a/include/webfront/components/react/Store.hpp b/include/webfront/components/react/Store.hpp index 000698a1..a635d82a 100644 --- a/include/webfront/components/react/Store.hpp +++ b/include/webfront/components/react/Store.hpp @@ -87,7 +87,7 @@ class Store { return state && state->valid(); } void set(T value) const { - auto& current = checked(); + auto& current = checked(); current.pending = std::move(value); if (!current.scheduled) { current.scheduled = true; @@ -107,7 +107,7 @@ class Store { checked().onError = std::move(callback); } void close() const { - auto& current = checked(); + auto& current = checked(); current.closed = true; current.pending.reset(); current.onError = nullptr; diff --git a/include/webfront/details/C++20Support.hpp b/include/webfront/details/C++20Support.hpp index 6775ad5b..25a180cd 100644 --- a/include/webfront/details/C++20Support.hpp +++ b/include/webfront/details/C++20Support.hpp @@ -5,112 +5,126 @@ #include #ifndef __cpp_concepts -#pragma message("Concepts minimal implementation added") -#include -#include + #pragma message("Concepts minimal implementation added") + #include + #include namespace std { -template +template concept constructible_from = destructible && is_constructible_v; -template -concept convertible_to = is_convertible_v && requires(add_rvalue_reference_t (&t)()) { - static_cast(t()); -}; +template +concept convertible_to = is_convertible_v && requires(add_rvalue_reference_t (&t)()) { static_cast(t()); }; -template -concept swappable = requires(T& t, T& t2) { - swap(t, t2); -}; +template +concept swappable = requires(T& t, T& t2) { swap(t, t2); }; -template +template concept move_constructible = std::constructible_from && std::convertible_to; -template +template concept movable = std::is_object_v && std::move_constructible && std::swappable; -} // namespace std +} // namespace std #endif #ifdef __cpp_lib_format -#include + #include #else -#pragma message("std::format minimal implementation added") -#include -#include -#include -#include -#include + #pragma message("std::format minimal implementation added") + #include + #include + #include + #include + #include namespace webfront { -template +template std::ostream& operator<<(std::ostream& os, std::chrono::time_point t) { using namespace std::chrono; auto tp = t.time_since_epoch(); - auto d = duration_cast(tp); - tp -= d; - auto h = duration_cast(tp); - tp -= h; - auto m = duration_cast(tp); - tp -= m; - auto s = duration_cast(tp); - tp -= s; + auto d = duration_cast(tp); + tp -= d; + auto h = duration_cast(tp); + tp -= h; + auto m = duration_cast(tp); + tp -= m; + auto s = duration_cast(tp); + tp -= s; auto us = duration_cast(tp); os << std::setfill('0') << std::setw(2) << h.count() << ':'; os << std::setfill('0') << std::setw(2) << m.count() << ':'; os << std::setfill('0') << std::setw(2) << s.count() << '.' << std::setw(6) << us.count(); return os; } -} // namespace webfront +} // namespace webfront namespace std { string format(std::string_view fmt, auto&&... ts) { - if (sizeof...(ts) == 0) return std::string(fmt); + if (sizeof...(ts) == 0) + return std::string(fmt); std::array fragments{}; - if (sizeof...(ts) > fragments.size()) throw std::length_error("format parameters count limit exceeded"); + if (sizeof...(ts) > fragments.size()) + throw std::length_error("format parameters count limit exceeded"); size_t index = 0; - auto start = fmt.cbegin(), parser = start; + auto start = fmt.cbegin(), parser = start; while (parser != fmt.cend()) { if (*parser == '{') { if (start == fmt.cbegin()) - fragments[index++] = std::string_view(start, static_cast(parser - start)); /// string_view constructor with iterators is missing in Apple Clang 13 + fragments[index++] = std::string_view( + start, + static_cast(parser - start)); /// string_view constructor with iterators is missing in Apple Clang 13 else if (start != parser && index < fragments.size()) - fragments[index++] = std::string_view(start + 1, static_cast(parser - (start + 1)));/// string_view constructor with iterators is missing in Apple Clang 13 - } - else if (*parser == '}') + fragments[index++] = std::string_view( + start + 1, + static_cast(parser - (start + 1))); /// string_view constructor with iterators is missing in Apple Clang 13 + } else if (*parser == '}') start = parser; ++parser; } - if (start + 1 != fmt.cend()) fragments[index++] = std::string_view(start + 1, static_cast(fmt.cend() - (start + 1)));/// string_view constructor with iterators is missing in Apple Clang 13 + if (start + 1 != fmt.cend()) + fragments[index++] = std::string_view( + start + 1, + static_cast(fmt.cend() - (start + 1))); /// string_view constructor with iterators is missing in Apple Clang 13 - auto frag = fragments.cbegin(); + auto frag = fragments.cbegin(); stringstream ss; using webfront::operator<<; ((ss << *frag++ << std::forward(ts)), ...); - while (frag != fragments.cend()) ss << *frag++; + while (frag != fragments.cend()) + ss << *frag++; return ss.str(); } - -} // namespace std +} // namespace std #endif #ifdef __cpp_lib_source_location -#include + #include #else -#pragma message("std::source_location minimal implementation added") + #pragma message("std::source_location minimal implementation added") namespace std { struct source_location { - static source_location current() noexcept { return {}; } + static source_location current() noexcept { + return {}; + } constexpr source_location() noexcept {} - constexpr uint_least32_t line() const noexcept { return l; }; - constexpr uint_least32_t column() const noexcept { return c; }; - constexpr const char* file_name() const noexcept { return "file"; } - constexpr const char* function_name() const noexcept { return "function"; } + constexpr uint_least32_t line() const noexcept { + return l; + }; + constexpr uint_least32_t column() const noexcept { + return c; + }; + constexpr const char* file_name() const noexcept { + return "file"; + } + constexpr const char* function_name() const noexcept { + return "function"; + } private: uint_least32_t l = 0; uint_least32_t c = 0; }; -} // namespace std +} // namespace std #endif diff --git a/include/webfront/details/C++23Support.hpp b/include/webfront/details/C++23Support.hpp index 3cb3636a..ee061dbc 100644 --- a/include/webfront/details/C++23Support.hpp +++ b/include/webfront/details/C++23Support.hpp @@ -9,17 +9,29 @@ namespace std { /// template constexpr T byteswap( T n ) noexcept; -/// Reverses the bytes in the given integer value n. +/// Reverses the bytes in the given integer value n. #ifndef __cpp_lib_byteswap #if defined(_MSC_VER) -inline auto byteswap(uint64_t v) noexcept { return _byteswap_uint64(v); } -inline auto byteswap(uint32_t v) noexcept { return _byteswap_ulong(v); } -inline auto byteswap(uint16_t v) noexcept { return _byteswap_ushort(v); } +inline auto byteswap(uint64_t v) noexcept { + return _byteswap_uint64(v); +} +inline auto byteswap(uint32_t v) noexcept { + return _byteswap_ulong(v); +} +inline auto byteswap(uint16_t v) noexcept { + return _byteswap_ushort(v); +} #else -constexpr auto byteswap(uint64_t v) noexcept { return __builtin_bswap64(v); } -constexpr auto byteswap(uint32_t v) noexcept { return __builtin_bswap32(v); } -constexpr auto byteswap(uint16_t v) noexcept { return __builtin_bswap16(v); } +constexpr auto byteswap(uint64_t v) noexcept { + return __builtin_bswap64(v); +} +constexpr auto byteswap(uint32_t v) noexcept { + return __builtin_bswap32(v); +} +constexpr auto byteswap(uint16_t v) noexcept { + return __builtin_bswap16(v); +} #endif #endif -} // namespace std +} // namespace std diff --git a/include/webfront/dom/Document.hpp b/include/webfront/dom/Document.hpp index 5095e7b1..667cdec1 100644 --- a/include/webfront/dom/Document.hpp +++ b/include/webfront/dom/Document.hpp @@ -396,7 +396,7 @@ class EventOperationState : public EventWaiter, public std::enable_shared_from_t { std::lock_guard lock(mutex); nameIndex = index; - ended = outcome != Outcome::pending; + ended = outcome != Outcome::pending; } if (ended) state->drop({node, index}, this->weak_from_this()); // stopped from another thread while subscribing @@ -404,7 +404,7 @@ class EventOperationState : public EventWaiter, public std::enable_shared_from_t public: EventOperationState(Receiver r, std::weak_ptr document, std::uint32_t id, std::string name, EventOptions flags) - : receiver(std::move(r)), owner(std::move(document)), node(id), event(std::move(name)), options(flags) { } + : receiver(std::move(r)), owner(std::move(document)), node(id), event(std::move(name)), options(flags) {} void start() noexcept { // Completion is deferred until subscription is finished: registering a stopped token invokes OnStop inline. try { @@ -456,7 +456,7 @@ class EventSender { public: using operation_state_concept = networking::ex::operation_state_tag; - explicit Operation(std::shared_ptr> value) : state(std::move(value)) { } + explicit Operation(std::shared_ptr> value) : state(std::move(value)) {} Operation(const Operation&) = delete; Operation(Operation&&) = delete; Operation& operator=(const Operation&) = delete; @@ -469,10 +469,10 @@ class EventSender { public: using sender_concept = networking::ex::sender_tag; - using completion_signatures = networking::ex::completion_signatures; + using completion_signatures = networking::ex:: + completion_signatures; EventSender(std::weak_ptr document, std::uint32_t id, std::string name, EventOptions flags) - : owner(std::move(document)), node(id), event(std::move(name)), options(flags) { } + : owner(std::move(document)), node(id), event(std::move(name)), options(flags) {} template auto connect(Receiver receiver) const { // Not make_shared: an obsolete weak entry must not keep the receiver's storage allocated. @@ -488,7 +488,7 @@ class Node { std::uint32_t identifier{}; template friend class Document; - Node(std::shared_ptr state, std::uint32_t id) : owner(std::move(state)), identifier(id) { } + Node(std::shared_ptr state, std::uint32_t id) : owner(std::move(state)), identifier(id) {} std::shared_ptr state() const { auto shared = owner.lock(); if (!shared) @@ -624,7 +624,7 @@ class Document { std::shared_ptr state; public: - explicit Document(UI browser) : ui(browser), state(browser.domState()) { } + explicit Document(UI browser) : ui(browser), state(browser.domState()) {} /// Whether this document is live and usable on the calling thread. bool valid() const noexcept { return state && state->validOnCurrentThread(); diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index 03635c06..191665da 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -2,29 +2,29 @@ #include "../ContentPolicy.hpp" #include "../system/WindowsCompat.hpp" -#include "../ViewAssociation.hpp" #include "../tooling/Logger.hpp" -#include "CEFPaths.hpp" -#include "ProfileLease.hpp" +#include "../ViewAssociation.hpp" #include "Capture.hpp" +#include "CEFPaths.hpp" #include "DefaultBrowser.hpp" #include "Downloads.hpp" -#include "ScriptDialogs.hpp" #include "NativeWindow.hpp" +#include "ProfileLease.hpp" +#include "ScriptDialogs.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" #include #include +#include #include #include #include #include #include -#include -#include #include +#include #include #include #include @@ -50,14 +50,14 @@ namespace webfront::cef { // Exception types for CEF initialization class CEFInitializationError : public std::runtime_error { public: - explicit CEFInitializationError(const std::string& message) : std::runtime_error("CEF initialization failed: " + message) { } + explicit CEFInitializationError(const std::string& message) : std::runtime_error("CEF initialization failed: " + message) {} }; class CEFSubprocessExit : public std::exception { int exit_code_; public: - explicit CEFSubprocessExit(int exit_code) : exit_code_(exit_code) { } + explicit CEFSubprocessExit(int exit_code) : exit_code_(exit_code) {} [[nodiscard]] const char* what() const noexcept override { return "CEF subprocess should exit"; @@ -92,8 +92,8 @@ class CEFSubprocessExit : public std::exception { #include "cef_id_mappers.h" #include "cef_load_handler.h" #include "cef_parser.h" - #include "cef_task.h" #include "cef_request_handler.h" + #include "cef_task.h" #include "views/cef_browser_view.h" #include "views/cef_window.h" #include "views/cef_window_delegate.h" @@ -107,11 +107,11 @@ static constexpr bool webfrontEmbedCEF{true}; // Constants namespace { -constexpr const char* kCEFCacheDir = "cef_cache"; -constexpr const char* kCEFLogFile = "cef_debug.log"; -constexpr const char* kICUDataFile = "icudtl.dat"; -constexpr const char* kLocalesDir = "locales"; -constexpr const char* kResourcesDir = "Resources"; +constexpr const char* kCEFCacheDir = "cef_cache"; +constexpr const char* kCEFLogFile = "cef_debug.log"; +constexpr const char* kICUDataFile = "icudtl.dat"; +constexpr const char* kLocalesDir = "locales"; +constexpr const char* kResourcesDir = "Resources"; } // namespace // Helper function to set keychain-related environment variables @@ -148,7 +148,7 @@ inline void configurePlatformPaths(CefSettings& settings [[maybe_unused]]) { std::filesystem::path framework_path = detail::macOSFrameworkPath(exe_path); std::filesystem::path resources_path = framework_path / kResourcesDir; // One live process per profile: Chromium would hand a second instance over to the first (ProfileLease.hpp). - std::filesystem::path cache_path = frontend::leaseProfileDirectory(exe_dir / kCEFCacheDir / exe_path.filename()); + std::filesystem::path cache_path = frontend::leaseProfileDirectory(exe_dir / kCEFCacheDir / exe_path.filename()); // Convert to absolute paths framework_path = std::filesystem::absolute(framework_path); @@ -175,7 +175,7 @@ inline void configurePlatformPaths(CefSettings& settings [[maybe_unused]]) { std::filesystem::path locales_path = resources_path / kLocalesDir; std::filesystem::path exe_path = current_exe; // One live process per profile: Chromium would hand a second instance over to the first (ProfileLease.hpp). - std::filesystem::path cache_path = frontend::leaseProfileDirectory(exe_dir / kCEFCacheDir / exe_path.filename()); + std::filesystem::path cache_path = frontend::leaseProfileDirectory(exe_dir / kCEFCacheDir / exe_path.filename()); // Convert to absolute paths resources_path = std::filesystem::absolute(resources_path); @@ -306,8 +306,8 @@ class ViewSecretRenderApp : public CefApp, public CefRenderProcessHandler { } private: - std::mutex mutex; - std::map launches; + std::mutex mutex; + std::map launches; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wextra-semi" @@ -376,7 +376,9 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { return; } CefRefPtr self(this); - setReveal([self, window] { self->present(window); }); + setReveal([self, window] { + self->present(window); + }); CefPostDelayedTask(TID_UI, new PresentTask(self, window), presentDelayMilliseconds); } @@ -426,7 +428,9 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { class PresentTask : public CefTask { public: PresentTask(CefRefPtr owner, CefRefPtr target) : delegate(std::move(owner)), window(std::move(target)) {} - void Execute() override { delegate->present(window); } + void Execute() override { + delegate->present(window); + } private: CefRefPtr delegate; @@ -434,10 +438,10 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { IMPLEMENT_REFCOUNTING(PresentTask); }; - CefRefPtr browserView; + CefRefPtr browserView; std::function)> setReveal; - WindowOptions windowOptions; - bool presented = false; + WindowOptions windowOptions; + bool presented = false; #ifdef __clang__ #pragma clang diagnostic push @@ -466,15 +470,15 @@ class DevToolsWindowClient : public CefClient { using frontend::CaptureProvider; using frontend::CaptureRegistration; -using frontend::PendingCaptures; using frontend::CaptureResult; +using frontend::PendingCaptures; namespace detail { /// The browser as seen by capture requests: read and cleared only on the UI thread, so a request that outlives the /// window finds it null. struct CaptureJob; struct CaptureTarget { - CefRefPtr browser; + CefRefPtr browser; PendingCaptures pending; // Requests nobody has answered yet, queued or in flight. }; @@ -486,7 +490,7 @@ struct CaptureJob { inline void answer(CaptureJob& job, CaptureResult result) noexcept { try { job.done.set_value(std::move(result)); - } catch (...) { } + } catch (...) {} } /// The window is going away: no pending request waits for an answer that will never come. @@ -514,7 +518,7 @@ inline CaptureResult pngOf(const void* json, std::size_t size) { // registration then; the job outlives a waiter that timed out. class CaptureObserver : public CefDevToolsMessageObserver { public: - explicit CaptureObserver(std::shared_ptr request) : job(std::move(request)) { } + explicit CaptureObserver(std::shared_ptr request) : job(std::move(request)) {} void start(CefRefPtr host) { registration = host->AddDevToolsMessageObserver(this); @@ -558,7 +562,7 @@ class CaptureObserver : public CefDevToolsMessageObserver { class CaptureTask : public CefTask { public: - explicit CaptureTask(std::shared_ptr request) : job(std::move(request)) { } + explicit CaptureTask(std::shared_ptr request) : job(std::move(request)) {} void Execute() override { try { if (!job->target->browser) { @@ -570,7 +574,7 @@ class CaptureTask : public CefTask { } catch (...) { try { job->done.set_exception(std::current_exception()); - } catch (...) { } + } catch (...) {} } } @@ -618,7 +622,7 @@ class SimpleCEFClient : public CefClient, public CefJSDialogHandler { public: explicit SimpleCEFClient(webfront::detail::BoundContentPolicy policy = webfront::detail::BoundContentPolicy{}, browser::Launcher launch = browser::launch) - : contentPolicy(std::move(policy)), popupLauncher(launch) { } + : contentPolicy(std::move(policy)), popupLauncher(launch) {} void setContentPolicy(webfront::detail::BoundContentPolicy policy) { contentPolicy = std::move(policy); @@ -638,10 +642,10 @@ class SimpleCEFClient : public CefClient, /// Test injection: answers without a dialog (an empty list cancels). Unset keeps the engine's dialog. std::function()> chooseFiles; /// Test injection: a non-empty folder receives downloads without a "save as" dialog. - std::filesystem::path downloadDirectory; - frontend::detail::DownloadReservations downloadReservations; - std::mutex reservedMutex; - std::map reservedByDownload; // CefDownloadItem id -> destination + std::filesystem::path downloadDirectory; + frontend::detail::DownloadReservations downloadReservations; + std::mutex reservedMutex; + std::map reservedByDownload; // CefDownloadItem id -> destination /// Test injection: called with the full path of each completed download. std::function downloadFinished; @@ -831,7 +835,7 @@ class SimpleCEFClient : public CefClient, return this; } - virtual void OnTitleChange(CefRefPtr /*browser*/, const CefString& /*title*/) override { } + virtual void OnTitleChange(CefRefPtr /*browser*/, const CefString& /*title*/) override {} virtual void OnAfterCreated(CefRefPtr browser) override { // The application's window is the first browser; popups are cancelled and DevTools has its own client. if (!captureTarget->browser) { @@ -869,10 +873,10 @@ class SimpleCEFClient : public CefClient, return true; } - webfront::detail::BoundContentPolicy contentPolicy; - browser::Launcher popupLauncher; - bool loadingInitialPage = true; - std::shared_ptr captureTarget = std::make_shared(); + webfront::detail::BoundContentPolicy contentPolicy; + browser::Launcher popupLauncher; + bool loadingInitialPage = true; + std::shared_ptr captureTarget = std::make_shared(); CaptureRegistration captureRegistration; void dispatchPopup(const std::string& url, bool userGesture) noexcept { @@ -967,9 +971,13 @@ class DrainTask : public CefTask { #endif }; -inline void openWindow(std::string url, webfront::detail::BoundContentPolicy contentPolicy, - CefRefPtr client = nullptr, const std::filesystem::path& profile = {}, - WindowOptions windowSettings = {}, bool preserveSignalHandlers = false, const ViewLaunch& launch = {}) { +inline void openWindow(std::string url, + webfront::detail::BoundContentPolicy contentPolicy, + CefRefPtr client = nullptr, + const std::filesystem::path& profile = {}, + WindowOptions windowSettings = {}, + bool preserveSignalHandlers = false, + const ViewLaunch& launch = {}) { // One window per process. Refuse a second open() first, before CefInitialize (which succeeds again when the context // exists) and before any view: its browser would reach OnAfterCreated and replace the published window of the running // one, before host.attach() could refuse it, and the first connection's dialogs would be parented to the new window. @@ -1017,7 +1025,8 @@ inline void openWindow(std::string url, webfront::detail::BoundContentPolicy con // Chrome's browser startup can install handlers independently of ContentMain's setting. // Restore the embedder's exact actions once all browser initialization has finished. if (preserveSignalHandlers && (::sigaction(SIGINT, &previousInt, nullptr) || ::sigaction(SIGTERM, &previousTerm, nullptr))) { - if (initialized) CefShutdown(); + if (initialized) + CefShutdown(); throw std::runtime_error("Cannot restore native signal handlers"); } #endif @@ -1049,7 +1058,9 @@ inline void openWindow(std::string url, webfront::detail::BoundContentPolicy con // Create a window delegate for controlling the window appearance CefRefPtr window_delegate(new SimpleCEFWindowDelegate(frontend::detail::resolveWindow(std::move(windowSettings)))); window_delegate->SetBrowserView(browser_view); - window_delegate->SetRevealHook([client](std::function reveal) { client->onInitialLoad = std::move(reveal); }); + window_delegate->SetRevealHook([client](std::function reveal) { + client->onInitialLoad = std::move(reveal); + }); // Create a top-level window with no browser chrome CefRefPtr window = CefWindow::CreateTopLevelWindow(window_delegate); @@ -1057,7 +1068,9 @@ inline void openWindow(std::string url, webfront::detail::BoundContentPolicy con // Run the CEF message loop; CefPostTask is thread-safe and the task runs on this (UI) thread. A failed post (the loop is // ending) is dropped: closing the host completes what is pending stopped. auto& host = frontend::uiExecutorHostOf(); - host.attach([] { CefPostTask(TID_UI, new DrainTask); }); + host.attach([] { + CefPostTask(TID_UI, new DrainTask); + }); { struct Closing { frontend::UIExecutorHost& host; @@ -1083,8 +1096,12 @@ inline void closeBrowser(void* browser) { static_cast(browser)->GetHost()->CloseBrowser(true); } -inline void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy = {}, - const WindowOptions& window = {}, const ViewLaunch& launch = {}) { +inline void open(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy = {}, + const WindowOptions& window = {}, + const ViewLaunch& launch = {}) { detail::openWindow(frontend::detail::applicationUrl(address, port, file, launch.origin), webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", launch.origin), policy}, nullptr, @@ -1109,8 +1126,12 @@ inline void initialize() { "WEBFRONT_EMBED_CEF=OFF. Reconfigure with -DWEBFRONT_EMBED_CEF=ON to use the embedded CEF frontend."); } -inline void open(std::string_view /*address*/, std::string_view /*port*/, std::string_view /*file*/, const ContentPolicy& = {}, const WindowOptions& = {}, - const ViewLaunch& = {}) { +inline void open(std::string_view /*address*/, + std::string_view /*port*/, + std::string_view /*file*/, + const ContentPolicy& = {}, + const WindowOptions& = {}, + const ViewLaunch& = {}) { throw std::runtime_error("webfront::frontend::CEFFrontend requires CEF support, but this build was configured with " "WEBFRONT_EMBED_CEF=OFF. Reconfigure with -DWEBFRONT_EMBED_CEF=ON to use the embedded CEF frontend."); } diff --git a/include/webfront/frontend/Capture.hpp b/include/webfront/frontend/Capture.hpp index 81d85c2e..58f42d6d 100644 --- a/include/webfront/frontend/Capture.hpp +++ b/include/webfront/frontend/Capture.hpp @@ -87,7 +87,7 @@ class CaptureRegistration { } CaptureRegistration(const CaptureRegistration&) = delete; CaptureRegistration& operator=(const CaptureRegistration&) = delete; - CaptureRegistration(CaptureRegistration&& other) noexcept : owned(std::exchange(other.owned, nullptr)) { } + CaptureRegistration(CaptureRegistration&& other) noexcept : owned(std::exchange(other.owned, nullptr)) {} CaptureRegistration& operator=(CaptureRegistration&& other) noexcept { if (this != &other) { reset(); diff --git a/include/webfront/frontend/CloseRequest.hpp b/include/webfront/frontend/CloseRequest.hpp index f99d1fa8..afe3d6b0 100644 --- a/include/webfront/frontend/CloseRequest.hpp +++ b/include/webfront/frontend/CloseRequest.hpp @@ -20,7 +20,9 @@ namespace webfront::frontend { /// `static constexpr bool requiresMainThread` says; a frontend that does not declare it is taken to run on any thread. template inline constexpr bool requiresMainThread = [] { - if constexpr (requires { { Frontend::requiresMainThread } -> std::convertible_to; }) + if constexpr (requires { + { Frontend::requiresMainThread } -> std::convertible_to; + }) return static_cast(Frontend::requiresMainThread); else return false; @@ -43,7 +45,9 @@ template inline constexpr bool endsOnRequest = [] { if constexpr (!CanRequestClose) return false; - else if constexpr (requires { { Frontend::endsOnRequest } -> std::convertible_to; }) + else if constexpr (requires { + { Frontend::endsOnRequest } -> std::convertible_to; + }) return static_cast(Frontend::endsOnRequest); else return true; @@ -80,15 +84,14 @@ struct WindowCloseRequest { } }; - UIExecutor executor; - NativeWindow window; - Close close; - std::optional session; + UIExecutor executor; + NativeWindow window; + Close close; + std::optional session; ex::connect_result_t().schedule()), Receiver> operation; WindowCloseRequest(const UIExecutor& loop, NativeWindow target, Close function, std::optional owner) - : executor(loop), window(std::move(target)), close(std::move(function)), session(owner), - operation(ex::connect(loop.schedule(), Receiver{this})) { } + : executor(loop), window(std::move(target)), close(std::move(function)), session(owner), operation(ex::connect(loop.schedule(), Receiver{this})) {} }; /// Runs `close(const NativeWindowHandle&)` on the interface thread with the published window. Returns false, having diff --git a/include/webfront/frontend/DefaultBrowser.hpp b/include/webfront/frontend/DefaultBrowser.hpp index 358c168f..43d92636 100644 --- a/include/webfront/frontend/DefaultBrowser.hpp +++ b/include/webfront/frontend/DefaultBrowser.hpp @@ -14,14 +14,14 @@ #ifdef _WIN32 #include #else - #include - #include - #include - #include #include #include #include + + #include + #include + #include extern char** environ; #endif diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index ca306d5d..68e19a39 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -25,7 +25,7 @@ class DownloadStaging { explicit DownloadStaging(const std::filesystem::path& parent) { sweepStale(parent); #ifdef __APPLE__ - auto pattern = (parent / ".webfront-download-XXXXXX").string(); + auto pattern = (parent / ".webfront-download-XXXXXX").string(); std::vector buffer(pattern.begin(), pattern.end()); buffer.push_back('\0'); if (!::mkdtemp(buffer.data())) @@ -34,7 +34,7 @@ class DownloadStaging { #else std::random_device random; for (int attempt = 0; attempt < 100; ++attempt) { - auto candidate = parent / (".webfront-download-" + std::to_string(random()) + "-" + std::to_string(random())); + auto candidate = parent / (".webfront-download-" + std::to_string(random()) + "-" + std::to_string(random())); std::error_code error; if (std::filesystem::create_directory(candidate, error)) { directory = std::move(candidate); @@ -51,13 +51,15 @@ class DownloadStaging { throw std::filesystem::filesystem_error("Cannot allocate download staging", parent, std::make_error_code(std::errc::file_exists)); #endif } - DownloadStaging(const DownloadStaging&) = delete; + DownloadStaging(const DownloadStaging&) = delete; DownloadStaging& operator=(const DownloadStaging&) = delete; ~DownloadStaging() { std::error_code ignored; std::filesystem::remove_all(directory, ignored); } - [[nodiscard]] std::filesystem::path path() const { return directory / "download"; } + [[nodiscard]] std::filesystem::path path() const { + return directory / "download"; + } /** * @brief Installs the staged file. A new target never replaces a file that appeared meanwhile. * @@ -103,8 +105,7 @@ class DownloadStaging { } error.clear(); } - } catch (...) { - } + } catch (...) {} } private: @@ -177,7 +178,7 @@ class DownloadReservations { } private: - mutable std::mutex mutex; + mutable std::mutex mutex; std::set reserved; }; diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index b7885256..787d0808 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -28,7 +28,8 @@ namespace detail { /// otherwise wrap around when it becomes the unsigned argument of the timer. [[nodiscard]] inline unsigned timerMilliseconds(std::chrono::milliseconds timeout, std::string_view frontend) { if (timeout.count() < 1 || timeout.count() > std::numeric_limits::max()) - throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be positive and at most " + std::to_string(std::numeric_limits::max()) + " milliseconds"); + throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be positive and at most " + std::to_string(std::numeric_limits::max()) + + " milliseconds"); return static_cast(timeout.count()); } } // namespace detail @@ -40,8 +41,8 @@ struct ViewOptions { /// depends on the engine: WKWebView, the end of the load; WebKitGTK, the commit of the navigation (resources still /// loading are not waited for); WebView2, the creation of its browser, before the navigation starts. std::chrono::milliseconds startupTimeout{30000}; - ContentPolicy contentPolicy{}; - WindowOptions window{}; + ContentPolicy contentPolicy{}; + WindowOptions window{}; /// WKWebView and WebView2: keep the native window hidden and avoid activating the application. bool visible{true}; /// Test injections (WKWebView, WebKitGTK): answers `` without a dialog (an empty list cancels). @@ -82,7 +83,8 @@ struct ViewOptions { * - `using Options`: the frontend's options (`contentPolicy`, `window` and `launch` at least; ViewOptions has them), and an * optional `static Options defaultOptions()` for the ones a call starts from; * - `static void openNative(address, port, file, const Options&)` and `closeNative(const NativeWindowHandle&)` (on the - * interface thread: the toolkit's own close request), and an optional `initializeNative()` (a frontend without one throws from initialize() when it is not compiled); + * interface thread: the toolkit's own close request), and an optional `initializeNative()` (a frontend without one throws from initialize() when it is not + * compiled); * - `static constexpr bool secondaryWindows`, and when true `openSecondaryNative(address, port, page, const Options&)` and * `closeSecondaryNative(page) -> bool`, which run on the interface thread; `waitsForFirstWindow` (optional) tells that * the call may come before the first window is ready (invokeOnUIThreadWhenReady). @@ -112,17 +114,25 @@ struct EmbeddedFrontend { /// Asks the window to close, from any thread; false when no window is open (see CloseRequest.hpp). static bool requestClose([[maybe_unused]] std::optional session = std::nullopt) noexcept { if constexpr (Derived::compiled) - return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { - Derived::closeNative(window); - }, session); + return detail::requestWindowClose( + uiExecutor(), + nativeWindow(), + [](const NativeWindowHandle& window) { + Derived::closeNative(window); + }, + session); else return false; } /// Opens `page` in a second window beside the one open() runs, or brings the window already showing it to the front /// (#616). Callable from any thread while open() runs; throws std::logic_error when no window is open. - static void openSecondaryWindow(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, - const WindowOptions& window, const ViewLaunch& launch) + static void openSecondaryWindow(std::string_view address, + std::string_view port, + std::string_view page, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch) requires(Derived::secondaryWindows) { if constexpr (!Derived::compiled) { @@ -176,8 +186,12 @@ struct EmbeddedFrontend { static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { open(address, port, file, optionsOf(policy, &window)); } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { + static void open(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch) { open(address, port, file, optionsOf(policy, &window, &launch)); } diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index c8f01b00..853e2e7b 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -3,7 +3,6 @@ #include "../ContentPolicy.hpp" #include "../ViewAssociation.hpp" #include "Action.hpp" -#include "Window.hpp" #include "CEF.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" @@ -12,9 +11,10 @@ #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "UILoop.hpp" +#include "WebKitGTK.hpp" #include "WebView2.hpp" +#include "Window.hpp" #include "WKWebView.hpp" -#include "WebKitGTK.hpp" #include #include @@ -82,7 +82,7 @@ struct DefaultBrowserFrontend { static constexpr Action action{Action::keepServerRunning}; static constexpr bool requiresMainThread = false; - static void initialize() { } + static void initialize() {} /// Opens the page in the system browser and returns at once, without the console wait of open() and without waiting /// for the opener command to end (BasicWF::start()). @@ -94,8 +94,8 @@ struct DefaultBrowserFrontend { browser::launchWithoutWaiting(detail::applicationUrl(address, port, file, webfront::detail::applicationOrigin(address, port, true))); } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, - const ViewLaunch& launch) { + static void + open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, const ViewLaunch& launch) { browser::openUrl(detail::applicationUrl(address, port, file, launch.origin)); } @@ -137,7 +137,7 @@ struct BrowserWithUILoopFrontend { static constexpr bool requiresMainThread = false; #endif - static void initialize() { } + static void initialize() {} /// Ends the loop of a running open(), as the user closing the window would end the others; the browser's window is /// not ours to close, the loop is. False, and nothing remembered, when no loop runs: unlike requestStop(), a request @@ -172,8 +172,8 @@ struct BrowserWithUILoopFrontend { static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&) { open(address, port, file); } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, - const ViewLaunch& launch) { + static void + open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, const ViewLaunch& launch) { loop(address, port, file, browser::launchWithoutWaiting, launch.origin); } /// The loop with another launcher: the unit tests start no browser. @@ -199,8 +199,8 @@ struct CEFFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = false; // (#616) static constexpr bool compiled = true; // without CEF the functions of cef:: throw their own diagnostic static constexpr std::string_view name = "CEFFrontend"; - using Host = CEFFrontend; - using Options = ViewOptions; + using Host = CEFFrontend; + using Options = ViewOptions; static void initialize() { try { @@ -239,8 +239,12 @@ struct PlatformNativeFrontend { // Calls the richest open() the frontend offers, as BasicWF does. template -void openWith(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch = {}) { +void openWith(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch = {}) { if constexpr (requires { Frontend::open(address, port, file, policy, window, launch); }) Frontend::open(address, port, file, policy, window, launch); else if constexpr (requires { Frontend::open(address, port, file, policy, window); }) @@ -273,7 +277,7 @@ struct NativeOrBrowserFrontendFor { static constexpr Action action{Native::action}; static constexpr bool requiresMainThread = frontend::requiresMainThread || frontend::requiresMainThread; /// Whichever is used at run time must be closable on request: the plain system browser, which waits for Enter, is not. - static constexpr bool endsOnRequest = frontend::endsOnRequest && frontend::endsOnRequest; + static constexpr bool endsOnRequest = frontend::endsOnRequest && frontend::endsOnRequest; /// Asks the one in use to end its session; false when it has nothing to close (the plain system browser never has). /// Callable from any thread: the decision of initialize() is read atomically. @@ -302,19 +306,27 @@ struct NativeOrBrowserFrontendFor { /// owner of a session is told apart by it only then. [[nodiscard]] static bool publishesUIExecutor() { if (usesNativeWindow()) - return requires { { Native::uiExecutor() } -> std::same_as; }; - return requires { { Browser::uiExecutor() } -> std::same_as; }; + return requires { + { Native::uiExecutor() } -> std::same_as; + }; + return requires { + { Browser::uiExecutor() } -> std::same_as; + }; } /// The interface thread of the window in use; the browser path has one only with its loop mode. [[nodiscard]] static UIExecutor uiExecutor() { if (usesNativeWindow()) { - if constexpr (requires { { Native::uiExecutor() } -> std::same_as; }) + if constexpr (requires { + { Native::uiExecutor() } -> std::same_as; + }) return Native::uiExecutor(); else return {}; } else { - if constexpr (requires { { Browser::uiExecutor() } -> std::same_as; }) + if constexpr (requires { + { Browser::uiExecutor() } -> std::same_as; + }) return Browser::uiExecutor(); else return {}; @@ -324,7 +336,9 @@ struct NativeOrBrowserFrontendFor { /// The window of the one in use; the system browser has none. [[nodiscard]] static NativeWindow nativeWindow() { if (usesNativeWindow()) { - if constexpr (requires { { Native::nativeWindow() } -> std::same_as; }) + if constexpr (requires { + { Native::nativeWindow() } -> std::same_as; + }) return Native::nativeWindow(); } return {}; @@ -350,8 +364,12 @@ struct NativeOrBrowserFrontendFor { /// A second window beside the first (#616): the native window's, or a refusal when the system browser was chosen. The /// system browser is never asked to open one: it would be an external browser, without the proof of an embedded view. /// Offered only when the native frontend offers it; secondaryWindowsAvailable() tells which way initialize() decided. - static void openSecondaryWindow(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, - const WindowOptions& window, const ViewLaunch& launch) + static void openSecondaryWindow(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch) requires requires { Native::openSecondaryWindow(address, port, file, policy, window, launch); } { if (!usesNativeWindow()) @@ -359,7 +377,9 @@ struct NativeOrBrowserFrontendFor { Native::openSecondaryWindow(address, port, file, policy, window, launch); } [[nodiscard]] static bool closeSecondaryWindow(std::string_view file) - requires requires { { Native::closeSecondaryWindow(file) } -> std::same_as; } + requires requires { + { Native::closeSecondaryWindow(file) } -> std::same_as; + } { return usesNativeWindow() && Native::closeSecondaryWindow(file); } @@ -379,8 +399,12 @@ struct NativeOrBrowserFrontendFor { Browser::open(port, file); } /// The launch proof goes to the native window only: the system browser is never given a secret (ADR-020). - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy = {}, const WindowOptions& window = {}, - const ViewLaunch& launch = {}) { + static void open(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy = {}, + const WindowOptions& window = {}, + const ViewLaunch& launch = {}) { if (usesNativeWindow()) detail::openWith(address, port, file, policy, window, launch); else @@ -390,9 +414,13 @@ struct NativeOrBrowserFrontendFor { private: template static bool closeWith(std::optional session) { - if constexpr (requires { { Used::requestClose(session) } -> std::same_as; }) + if constexpr (requires { + { Used::requestClose(session) } -> std::same_as; + }) return Used::requestClose(session); - else if constexpr (requires { { Used::requestClose() } -> std::same_as; }) + else if constexpr (requires { + { Used::requestClose() } -> std::same_as; + }) return Used::requestClose(); else return false; diff --git a/include/webfront/frontend/NativeWebView.hpp b/include/webfront/frontend/NativeWebView.hpp index 3598937a..f0c6a8fc 100644 --- a/include/webfront/frontend/NativeWebView.hpp +++ b/include/webfront/frontend/NativeWebView.hpp @@ -18,7 +18,7 @@ namespace webfront::frontend { * It says nothing about the session: a native window can still fail at run time, for instance without a display. * NativeOrBrowserFrontend handles that case. */ -#if (defined(_WIN32) && defined(WEBFRONT_EMBED_WEBVIEW2)) || (defined(__APPLE__) && defined(WEBFRONT_EMBED_WKWEBVIEW)) \ +#if (defined(_WIN32) && defined(WEBFRONT_EMBED_WEBVIEW2)) || (defined(__APPLE__) && defined(WEBFRONT_EMBED_WKWEBVIEW)) \ || (defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK)) inline constexpr bool nativeWebViewAvailable = true; #else diff --git a/include/webfront/frontend/NativeWindow.hpp b/include/webfront/frontend/NativeWindow.hpp index 7d9736e6..d145baff 100644 --- a/include/webfront/frontend/NativeWindow.hpp +++ b/include/webfront/frontend/NativeWindow.hpp @@ -113,7 +113,7 @@ class NativeWindow { public: NativeWindow() = default; - NativeWindow(std::weak_ptr value, UIExecutor uiExecutor) : shared(std::move(value)), executor(std::move(uiExecutor)) { } + NativeWindow(std::weak_ptr value, UIExecutor uiExecutor) : shared(std::move(value)), executor(std::move(uiExecutor)) {} /// The window, or why it is not given (see the file comment). Never blocks and never throws. [[nodiscard]] NativeWindowResult get() const { @@ -130,7 +130,7 @@ class NativeWindowHost { UIExecutor executor; public: - explicit NativeWindowHost(UIExecutor uiExecutor) : executor(std::move(uiExecutor)) { } + explicit NativeWindowHost(UIExecutor uiExecutor) : executor(std::move(uiExecutor)) {} [[nodiscard]] NativeWindow window() const { return NativeWindow{shared, executor}; diff --git a/include/webfront/frontend/ProfileLease.hpp b/include/webfront/frontend/ProfileLease.hpp index e311e5ea..91aa672c 100644 --- a/include/webfront/frontend/ProfileLease.hpp +++ b/include/webfront/frontend/ProfileLease.hpp @@ -15,8 +15,8 @@ #include #include #include -#include #include +#include #include #ifndef _WIN32 @@ -33,7 +33,7 @@ namespace detail { /// An exclusive flock on a file: held until destruction (or the death of the process, which the system releases). class FileLock { public: - FileLock() = default; + FileLock() = default; FileLock(const FileLock&) = delete; FileLock& operator=(const FileLock&) = delete; FileLock(FileLock&& other) noexcept : fd(std::exchange(other.fd, -1)) {} @@ -44,10 +44,14 @@ class FileLock { /// Takes the lock of `file`, creating it. Returns nullopt when another process holds it (contention, the only expected /// refusal) and throws std::system_error for any other failure (no descriptor left, a file that cannot be created...). - [[nodiscard]] static std::optional tryLock(const std::filesystem::path& file) { return lock(file, LOCK_EX | LOCK_NB); } + [[nodiscard]] static std::optional tryLock(const std::filesystem::path& file) { + return lock(file, LOCK_EX | LOCK_NB); + } /// Waits for the lock of `file`; used for the short critical section that coordinates the leases of a directory. - [[nodiscard]] static FileLock wait(const std::filesystem::path& file) { return std::move(*lock(file, LOCK_EX)); } + [[nodiscard]] static FileLock wait(const std::filesystem::path& file) { + return std::move(*lock(file, LOCK_EX)); + } private: static std::optional lock(const std::filesystem::path& file, int operation) { @@ -89,11 +93,10 @@ struct LeaseHolder { continue; // Under the registry lock, like the scan of another process: the directory does not vanish while it is visited. try { - const auto registry = FileLock::wait(lease.remove.parent_path() / registryFile); + const auto registry = FileLock::wait(lease.remove.parent_path() / registryFile); std::error_code ignored; std::filesystem::remove_all(lease.remove, ignored); - } catch (...) { - } + } catch (...) {} } } }; diff --git a/include/webfront/frontend/StartupTrace.hpp b/include/webfront/frontend/StartupTrace.hpp index 91ce449e..1f0c252b 100644 --- a/include/webfront/frontend/StartupTrace.hpp +++ b/include/webfront/frontend/StartupTrace.hpp @@ -11,17 +11,18 @@ #if defined(_WIN32) #include "../system/WindowsCompat.hpp" + #include #elif defined(__APPLE__) #include #include #include #elif defined(__linux__) - #include - #include #include #include + + #include #endif namespace webfront::frontend::detail { @@ -35,9 +36,9 @@ namespace webfront::frontend::detail { return -1; GetSystemTimeAsFileTime(&now); ULARGE_INTEGER start{}, current{}; - start.LowPart = creation.dwLowDateTime; - start.HighPart = creation.dwHighDateTime; - current.LowPart = now.dwLowDateTime; + start.LowPart = creation.dwLowDateTime; + start.HighPart = creation.dwHighDateTime; + current.LowPart = now.dwLowDateTime; current.HighPart = now.dwHighDateTime; return static_cast((current.QuadPart - start.QuadPart) / 10000); #elif defined(__APPLE__) @@ -67,8 +68,7 @@ namespace webfront::frontend::detail { uptime >> seconds; return static_cast((seconds - std::stod(field) / static_cast(sysconf(_SC_CLK_TCK))) * 1000.0); } - } catch (...) { - } + } catch (...) {} return -1; #else return -1; @@ -96,7 +96,10 @@ class StartupTrace { public: void operator()(const char* milestone) const noexcept { if (enabled()) - std::fprintf(stderr, "WebFront startup: %s at %lld ms (session %lld ms)\n", milestone, millisecondsSinceProcessStart(), + std::fprintf(stderr, + "WebFront startup: %s at %lld ms (session %lld ms)\n", + milestone, + millisecondsSinceProcessStart(), static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - created).count())); } }; diff --git a/include/webfront/frontend/UIExecutor.hpp b/include/webfront/frontend/UIExecutor.hpp index d2c579cd..25483a83 100644 --- a/include/webfront/frontend/UIExecutor.hpp +++ b/include/webfront/frontend/UIExecutor.hpp @@ -46,16 +46,16 @@ namespace ex = networking::ex; /// @brief No interface-thread loop is attached: the frontend has none, it has not started or it has closed. class UIExecutorUnavailable : public std::runtime_error { public: - UIExecutorUnavailable() : std::runtime_error("no interface thread is available: the frontend has no running loop") { } + UIExecutorUnavailable() : std::runtime_error("no interface thread is available: the frontend has no running loop") {} }; namespace detail { /// One pending operation. The first of run / stop / close / failure to claim it completes the receiver, once. struct UIJob { - virtual ~UIJob() = default; - virtual void run() noexcept = 0; // on the interface thread - virtual void abandon() noexcept = 0; // loop closed or stop requested: completes stopped + virtual ~UIJob() = default; + virtual void run() noexcept = 0; // on the interface thread + virtual void abandon() noexcept = 0; // loop closed or stop requested: completes stopped virtual void fail(std::exception_ptr) noexcept = 0; }; @@ -160,7 +160,7 @@ class UIExecutorShared { { std::lock_guard lock(mutex); if (queue.empty() || phase != Phase::running || wakePending) - return; // nothing left, or a job queued meanwhile already asked for the next pass + return; // nothing left, or a job queued meanwhile already asked for the next pass wake = wakeFunction; // may throw: nothing has changed yet wakePending = true; ++wakesInFlight; @@ -180,7 +180,9 @@ class UIExecutorShared { phase = Phase::closed; pending.swap(queue); // No new wake starts (phase is closed): wait for those in flight on other threads, which only signal the loop. - wakesDone.wait(lock, [&] { return wakesInFlight == 0; }); + wakesDone.wait(lock, [&] { + return wakesInFlight == 0; + }); wakeFunction = nullptr; // may hold the session that is ending } for (auto& job : pending) @@ -235,7 +237,7 @@ class UIScheduleSender { std::exception_ptr failure; std::optional> stopCallback; - State(Receiver r, std::weak_ptr o) : receiver(std::move(r)), owner(std::move(o)) { } + State(Receiver r, std::weak_ptr o) : receiver(std::move(r)), owner(std::move(o)) {} // The first completion wins. Delivery is deferred while start() registers the stop callback: a token already // stopped invokes it inline, and the callback is not yet constructed. @@ -314,7 +316,7 @@ class UIScheduleSender { public: using operation_state_concept = ex::operation_state_tag; - explicit Operation(std::shared_ptr> value) : state(std::move(value)) { } + explicit Operation(std::shared_ptr> value) : state(std::move(value)) {} Operation(const Operation&) = delete; Operation(Operation&&) = delete; Operation& operator=(const Operation&) = delete; @@ -329,7 +331,7 @@ class UIScheduleSender { using sender_concept = ex::sender_tag; using completion_signatures = ex::completion_signatures; - explicit UIScheduleSender(std::weak_ptr value) : target(std::move(value)) { } + explicit UIScheduleSender(std::weak_ptr value) : target(std::move(value)) {} template auto connect(Receiver receiver) const { @@ -345,7 +347,7 @@ class UIExecutor { public: UIExecutor() = default; - explicit UIExecutor(std::weak_ptr value) : shared(std::move(value)) { } + explicit UIExecutor(std::weak_ptr value) : shared(std::move(value)) {} /// True while the frontend's loop runs. A later call to schedule() can still find it closed. [[nodiscard]] bool available() const { @@ -407,7 +409,7 @@ template /// thread; on the interface thread it reaches the caller, as the std::logic_error it is. class WindowNotReady : public std::logic_error { public: - explicit WindowNotReady(const std::string& message) : std::logic_error(message) { } + explicit WindowNotReady(const std::string& message) : std::logic_error(message) {} }; namespace detail { @@ -439,10 +441,10 @@ struct UIInvocation { finish(std::make_exception_ptr(UIExecutorUnavailable{})); } }; - Function function; - std::promise done; + Function function; + std::promise done; ex::connect_result_t().schedule()), Receiver> operation; - UIInvocation(const UIExecutor& loop, Function work) : function(std::move(work)), operation(ex::connect(loop.schedule(), Receiver{this})) { } + UIInvocation(const UIExecutor& loop, Function work) : function(std::move(work)), operation(ex::connect(loop.schedule(), Receiver{this})) {} }; } // namespace detail diff --git a/include/webfront/frontend/UILoop.hpp b/include/webfront/frontend/UILoop.hpp index cd8cb320..3425fdb4 100644 --- a/include/webfront/frontend/UILoop.hpp +++ b/include/webfront/frontend/UILoop.hpp @@ -21,12 +21,14 @@ #if defined(_WIN32) #include "../system/WindowsCompat.hpp" + #include #elif defined(__APPLE__) #include #include #elif defined(__linux__) #include + #include #include #include @@ -66,7 +68,9 @@ class UILoopStop { void disarm() { std::unique_lock lock(mutex); quit = nullptr; // no later request() copies it - callsDone.wait(lock, [&] { return calls == 0; }); + callsDone.wait(lock, [&] { + return calls == 0; + }); requested = false; } @@ -102,8 +106,8 @@ class UILoopStop { mutable std::mutex mutex; std::condition_variable callsDone; unsigned calls{0}; - bool requested{false}; - std::function quit; + bool requested{false}; + std::function quit; }; namespace detail::uiloop { @@ -128,7 +132,7 @@ struct CloseGuard { inline constexpr UINT drainMessage = WM_APP + 0x4C2; struct LoopWindow { - UIExecutorHost* host{}; + UIExecutorHost* host{}; static LRESULT CALLBACK procedure(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) noexcept { if (message == drainMessage) { if (auto* self = reinterpret_cast(GetWindowLongPtrW(handle, GWLP_USERDATA))) @@ -177,7 +181,9 @@ inline void run(UIExecutorHost& host, UILoopStop& stop, const Launch& launch = { throw std::runtime_error("UI loop: cannot wake the interface thread (the message queue is full)"); }); CloseGuard guard{host, stop}; - if (stop.arm([event = stopEvent.handle] { SetEvent(event); })) + if (stop.arm([event = stopEvent.handle] { + SetEvent(event); + })) return; for (;;) { if (stop.requestedStop()) @@ -216,16 +222,16 @@ class CoreFoundation { void (*perform)(void*); }; - Ref (*current)() = nullptr; - Ref (*sourceCreate)(void*, long, SourceContext*) = nullptr; - void (*addSource)(Ref, Ref, Ref) = nullptr; - void (*removeSource)(Ref, Ref, Ref) = nullptr; - void (*signal)(Ref) = nullptr; - void (*wakeUp)(Ref) = nullptr; - int (*runInMode)(Ref, double, unsigned char) = nullptr; - void (*release)(Ref) = nullptr; - Ref commonModes = nullptr; - Ref defaultMode = nullptr; + Ref (*current)() = nullptr; + Ref (*sourceCreate)(void*, long, SourceContext*) = nullptr; + void (*addSource)(Ref, Ref, Ref) = nullptr; + void (*removeSource)(Ref, Ref, Ref) = nullptr; + void (*signal)(Ref) = nullptr; + void (*wakeUp)(Ref) = nullptr; + int (*runInMode)(Ref, double, unsigned char) = nullptr; + void (*release)(Ref) = nullptr; + Ref commonModes = nullptr; + Ref defaultMode = nullptr; static const CoreFoundation& get() { static const CoreFoundation instance; @@ -286,7 +292,7 @@ class AppKitPump { const auto mode = reinterpret_cast(dlsym(RTLD_DEFAULT, "NSDefaultRunLoopMode")); if (!getClass || !selector || !send || !poolPush || !poolPop || !mode) return; - defaultMode = *mode; + defaultMode = *mode; const auto appClass = getClass("NSApplication"); eventClass = getClass("NSEvent"); dateClass = getClass("NSDate"); @@ -304,8 +310,17 @@ class AppKitPump { /// Thread-safe: makes next() return, so that the loop reads its flags again. void wake() const { const auto pool = poolPush(); - const auto event = call(eventClass, "otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:", - 15UL /* NSEventTypeApplicationDefined */, Point{0, 0}, 0UL, 0.0, 0L, Id{}, short{0}, 0L, 0L); + const auto event = call(eventClass, + "otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:", + 15UL /* NSEventTypeApplicationDefined */, + Point{0, 0}, + 0UL, + 0.0, + 0L, + Id{}, + short{0}, + 0L, + 0L); if (event) call(application, "postEvent:atStart:", event, static_cast(1)); poolPop(pool); @@ -315,8 +330,7 @@ class AppKitPump { void next() const { const auto pool = poolPush(); const auto until = call(dateClass, "distantFuture"); - const auto event = call(application, "nextEventMatchingMask:untilDate:inMode:dequeue:", ~0UL, until, defaultMode, - static_cast(1)); + const auto event = call(application, "nextEventMatchingMask:untilDate:inMode:dequeue:", ~0UL, until, defaultMode, static_cast(1)); if (event) call(application, "sendEvent:", event); poolPop(pool); @@ -329,24 +343,26 @@ class AppKitPump { } Selector (*selector)(const char*) = nullptr; - void* send{}; - Id (*poolPush)() = nullptr; - void (*poolPop)(Id) = nullptr; - Id application{}; - Id eventClass{}; - Id dateClass{}; - Id defaultMode{}; + void* send{}; + Id (*poolPush)() = nullptr; + void (*poolPop)(Id) = nullptr; + Id application{}; + Id eventClass{}; + Id dateClass{}; + Id defaultMode{}; }; inline void run(UIExecutorHost& host, UILoopStop& stop, const Launch& launch = {}) { // AppKit belongs to the main thread: fail before initializing it or attaching the executor. if (!pthread_main_np()) throw std::runtime_error("UI loop: the system browser's interface loop must run on the main thread on macOS"); - const auto& cf = CoreFoundation::get(); - const AppKitPump pump; + const auto& cf = CoreFoundation::get(); + const AppKitPump pump; CoreFoundation::SourceContext context{}; context.info = &host; - context.perform = +[](void* info) { static_cast(info)->drain(); }; + context.perform = +[](void* info) { + static_cast(info)->drain(); + }; const auto source = cf.sourceCreate(nullptr, 0, &context); if (!source) throw std::runtime_error("UI loop: cannot create the run loop source"); @@ -405,11 +421,11 @@ class WakeEvent { } void signal() const noexcept { const std::uint64_t one = 1; - while (::write(descriptor, &one, sizeof(one)) < 0 && errno == EINTR) { } + while (::write(descriptor, &one, sizeof(one)) < 0 && errno == EINTR) {} } std::uint64_t consume() const noexcept { std::uint64_t count = 0; - while (::read(descriptor, &count, sizeof(count)) < 0 && errno == EINTR) { } + while (::read(descriptor, &count, sizeof(count)) < 0 && errno == EINTR) {} return count; } }; @@ -463,8 +479,7 @@ inline void run(UIExecutorHost& host, UILoopStop& stop, const Launch& launch = { // can then dispatch it, and the callback below always runs on the interface thread. A host that iterates this context // on another thread (even briefly, when this call arrives) is refused here instead of running our callback there. if (!glib.contextAcquire(context)) - throw std::runtime_error( - "UI loop: the default GLib context is owned by another thread; run the loop on the thread that iterates it"); + throw std::runtime_error("UI loop: the default GLib context is owned by another thread; run the loop on the thread that iterates it"); struct Release { const GLib& glib; GLib::Object context; @@ -476,7 +491,7 @@ inline void run(UIExecutorHost& host, UILoopStop& stop, const Launch& launch = { if (!loop) throw std::runtime_error("UI loop: cannot create the GLib main loop"); struct Unref { - const GLib& glib; + const GLib& glib; GLib::Object loop; ~Unref() { glib.loopUnref(loop); diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 5d781b5a..7fe685fa 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -1,15 +1,15 @@ #pragma once #include "../ContentPolicy.hpp" +#include "../ViewAssociation.hpp" #include "Action.hpp" #include "Capture.hpp" #include "CloseRequest.hpp" #include "Downloads.hpp" #include "EmbeddedFrontend.hpp" -#include "../ViewAssociation.hpp" +#include "NativeWindow.hpp" #include "ScriptDialogs.hpp" #include "StartupTrace.hpp" -#include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" @@ -22,12 +22,12 @@ #include #include #include -#include #include +#include #include #include -#include #include +#include namespace webfront::frontend { @@ -48,7 +48,7 @@ using WKWebViewOptions = ViewOptions; #include #include #include -#include + #include #include #include #include @@ -79,7 +79,7 @@ inline id type(const char* name) { class Object { public: - explicit Object(id value = nullptr) : value(value) { } + explicit Object(id value = nullptr) : value(value) {} Object(const Object&) = delete; Object& operator=(const Object&) = delete; ~Object() { @@ -118,7 +118,7 @@ inline void initialize() { } inline long applicationActivationPolicy() { - Object agentKey(text("LSUIElement")); + Object agentKey(text("LSUIElement")); const auto agent = send(send(type("NSBundle"), "mainBundle"), "objectForInfoDictionaryKey:", agentKey.get()); return send(agent, "boolValue") ? 1L : 0L; // Accessory for agent bundles, Regular otherwise. } @@ -185,7 +185,7 @@ inline bool successfulHttpStatus(long status) { /// window finds it null. struct CaptureJob; struct CaptureTarget { - id view = nullptr; + id view = nullptr; PendingCaptures pending; // Requests nobody has answered yet, queued or in flight. }; @@ -197,7 +197,7 @@ struct CaptureJob { inline void answer(CaptureJob& job, CaptureResult result) noexcept { try { job.done.set_value(std::move(result)); - } catch (...) { } // Already answered: a closing window may have answered before the engine did. + } catch (...) {} // Already answered: a closing window may have answered before the engine did. } /// The window is going away: no pending request waits for an answer that will never come. @@ -245,7 +245,7 @@ inline void startCapture(void* data) noexcept { } catch (...) { try { job->done.set_exception(std::current_exception()); - } catch (...) { } + } catch (...) {} } }; // A nil configuration snapshots the visible bounds of the view. @@ -262,7 +262,7 @@ inline void startCapture(void* data) noexcept { } catch (...) { try { job->done.set_exception(std::current_exception()); - } catch (...) { } + } catch (...) {} } } @@ -284,8 +284,7 @@ inline CaptureProvider captureProvider(std::shared_ptr target) { struct Session { explicit Session(std::string url, WKWebViewOptions options = {}) - : url(std::move(url)), options(std::move(options)), contentPolicy(this->url, this->options.contentPolicy) { - } + : url(std::move(url)), options(std::move(options)), contentPolicy(this->url, this->options.contentPolicy) {} std::string url; WKWebViewOptions options; @@ -293,35 +292,35 @@ struct Session { std::function navigationCancelled; struct PendingDownload { std::unique_ptr staging; - std::filesystem::path target; - bool reserved; - bool replace; + std::filesystem::path target; + bool reserved; + bool replace; }; frontend::detail::DownloadReservations reservations; - std::map downloadDestinations; // WKDownload -> its paths, until it ends. + std::map downloadDestinations; // WKDownload -> its paths, until it ends. /// What the answers of a system panel hold instead of `this`: AppKit may deliver one after the session is gone. - std::shared_ptr alive = std::make_shared(this); - id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; + std::shared_ptr alive = std::make_shared(this); + id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; /// The window is shown nearly transparent and made opaque at the page's first frame, or when this timer expires. - id presentTimer = nullptr; + id presentTimer = nullptr; /// Test hook: false does not show the window when the document finishes loading, so only the delay can. - bool revealOnLoad = true; + bool revealOnLoad = true; /// Seconds before the window is shown even if the document has not loaded. A test lengthens it so that a slow /// first launch of the web content process cannot make the delay win against the load it observes. - double presentDelay = 1.0; + double presentDelay = 1.0; /// Test hook: called on the main thread when the window has been made opaque. - frontend::detail::Presentation presentation; - frontend::detail::StartupTrace trace; - id previousDelegate = nullptr, previousMenu = nullptr; - long previousActivationPolicy = 0; - bool installed = false, running = false, closed = false, loaded = false; - bool secondary = false; - id sharedDataStore = nullptr; - std::function closedHook; - bool receivedResponse = false, committed = false; - std::exception_ptr failure; - std::shared_ptr captureTarget = std::make_shared(); - CaptureRegistration captureRegistration; + frontend::detail::Presentation presentation; + frontend::detail::StartupTrace trace; + id previousDelegate = nullptr, previousMenu = nullptr; + long previousActivationPolicy = 0; + bool installed = false, running = false, closed = false, loaded = false; + bool secondary = false; + id sharedDataStore = nullptr; + std::function closedHook; + bool receivedResponse = false, committed = false; + std::exception_ptr failure; + std::shared_ptr captureTarget = std::make_shared(); + CaptureRegistration captureRegistration; ~Session() { *alive = nullptr; @@ -516,22 +515,23 @@ struct Session { // so asynchronous bridge/Worker work and close requests keep progressing without a visible native window. if (!options.visible) { const auto preferences = send(configuration.get(), "preferences"); - const auto selector = sel_registerName("setInactiveSchedulingPolicy:"); + const auto selector = sel_registerName("setInactiveSchedulingPolicy:"); if (!send(preferences, "respondsToSelector:", selector)) throw std::runtime_error("WKWebView: hidden sessions require macOS 14 or later (inactiveSchedulingPolicy)"); - send(preferences, "setInactiveSchedulingPolicy:", 2L); // WKInactiveSchedulingPolicyNone + send(preferences, "setInactiveSchedulingPolicy:", 2L); // WKInactiveSchedulingPolicyNone } if (!options.launch.secret.empty()) { // At the start of every document, in the main frame only: the script itself checks the origin. Object source(text(::webfront::detail::viewSecretScript(options.launch.secret, options.launch.origin))); - Object script(send(send(type("WKUserScript"), "alloc"), "initWithSource:injectionTime:forMainFrameOnly:", source.get(), 0L, static_cast(true))); + Object script( + send(send(type("WKUserScript"), "alloc"), "initWithSource:injectionTime:forMainFrameOnly:", source.get(), 0L, static_cast(true))); send(send(configuration.get(), "userContentController"), "addUserScript:", script.get()); } // Deliver script-created popup attempts to the delegates, which always cancel unmanaged views. send(send(configuration.get(), "preferences"), "setJavaScriptCanOpenWindowsAutomatically:", static_cast(true)); const auto windowOptions = frontend::detail::resolveWindow(options.window); const CGRect bounds{ - { 0, 0}, + { 0, 0}, {static_cast(windowOptions.width), static_cast(windowOptions.height)} }; view = send(send(reinterpret_cast(viewClass()), "alloc"), "initWithFrame:configuration:", bounds, configuration.get()); @@ -551,8 +551,12 @@ struct Session { throw std::runtime_error("WKWebView: cannot create window (a WindowServer session is required)"); send(window, "setReleasedWhenClosed:", static_cast(false)); if (const auto color = frontend::detail::parseBackground(windowOptions.background)) { - const auto native = send(type("NSColor"), "colorWithSRGBRed:green:blue:alpha:", static_cast((*color)[0]), static_cast((*color)[1]), - static_cast((*color)[2]), static_cast((*color)[3])); + const auto native = send(type("NSColor"), + "colorWithSRGBRed:green:blue:alpha:", + static_cast((*color)[0]), + static_cast((*color)[1]), + static_cast((*color)[2]), + static_cast((*color)[3])); send(window, "setBackgroundColor:", native); // A translucent colour is only seen through if the window is not opaque: without this AppKit fills the window as // if the alpha were 1. Opaque colours keep the default opaque window, which is cheaper to composite. @@ -691,7 +695,7 @@ struct Session { bool retained = false; try { send(panel, "retain"); - retained = true; + retained = true; void (^finished)(long) = ^(long response) { handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK send(panel, "release"); @@ -740,14 +744,19 @@ struct Session { send(alert, "addButtonWithTitle:", cancel.get()); } if (dialog.kind == ScriptDialog::Kind::prompt) { - field = send(send(type("NSTextField"), "alloc"), "initWithFrame:", CGRect{{0, 0}, {300, 24}}); + field = send(send(type("NSTextField"), "alloc"), + "initWithFrame:", + CGRect{ + { 0, 0}, + {300, 24} + }); Object value(text(dialog.defaultText)); send(field, "setStringValue:", value.get()); send(alert, "setAccessoryView:", field); send(alert, "layout"); send(send(alert, "window"), "setInitialFirstResponder:", field); } - auto shared = std::make_shared>(std::move(answer)); + auto shared = std::make_shared>(std::move(answer)); void (^finished)(long) = ^(long response) { ScriptDialogAnswer reply; reply.accepted = response == 1000; // endSheet: at window close reports NSModalResponseCancel. @@ -801,7 +810,7 @@ struct Session { reservations.release(destination); throw; } - const auto temporary = staging->path(); + const auto temporary = staging->path(); downloadDestinations[download] = {std::move(staging), destination, true, false}; Object path(text(temporary.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); @@ -816,11 +825,11 @@ struct Session { const id key = download; // By value: the panel answers after this lambda and its references are gone. try { send(panel, "retain"); - retained = true; + retained = true; void (^finished)(long) = ^(long response) { id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK if (chosen && !*token) - chosen = nullptr; // The session is gone: nobody could move the file afterwards. + chosen = nullptr; // The session is gone: nobody could move the file afterwards. try { if (chosen) { const std::filesystem::path target = utf8(send(chosen, "path")); @@ -830,13 +839,14 @@ struct Session { throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); auto& sessionReservations = (*token)->reservations; if (!sessionReservations.reserveExact(target)) - throw std::filesystem::filesystem_error("Another download is writing this target", target, + throw std::filesystem::filesystem_error("Another download is writing this target", + target, std::make_error_code(std::errc::file_exists)); try { auto staging = std::make_unique(target.parent_path()); const auto temporary = staging->path(); Object path(text(temporary.string())); - chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); (*token)->downloadDestinations[key] = {std::move(staging), target, true, replace}; } catch (...) { sessionReservations.release(target); @@ -1150,9 +1160,13 @@ struct WindowHooks { template void scheduleReap(Registry&) { dispatch_async_f( - dispatch_get_main_queue(), nullptr, +[](void*) { reapSecondaryWindows(); }); + dispatch_get_main_queue(), + nullptr, + +[](void*) { + reapSecondaryWindows(); + }); } - void cancelReap() { } // nothing is pending that clear() must withdraw: a late reap() finds the registry empty + void cancelReap() {} // nothing is pending that clear() must withdraw: a late reap() finds the registry empty void present(Session& session) { // A hidden window stays hidden: ordering it to the front would show it. if (session.options.visible) @@ -1216,17 +1230,20 @@ inline void open(std::string_view address, std::string_view port, std::string_vi // The AppKit loop drains the main queue: a wake is a block on it. Closing completes pending operations stopped, // also when run() throws or returns at once because the window already closed. The window is published once the // loop is attached (this is the interface thread) and withdrawn before the session releases it. - auto& host = uiExecutorHostOf(); - frontend::detail::InterfaceSession interfaceSession( - host, - nativeWindowHostOf(), - Windows::instance(), - window, - [&host] { - dispatch_async_f( - dispatch_get_main_queue(), &host, +[](void* context) { static_cast(context)->drain(); }); - }, - {.kind = NativeWindowKind::cocoa, .pointer = window.window, .portalParent = {}}); + auto& host = uiExecutorHostOf(); + frontend::detail::InterfaceSession interfaceSession(host, + nativeWindowHostOf(), + Windows::instance(), + window, + [&host] { + dispatch_async_f( + dispatch_get_main_queue(), + &host, + +[](void* context) { + static_cast(context)->drain(); + }); + }, + {.kind = NativeWindowKind::cocoa, .pointer = window.window, .portalParent = {}}); window.run(); } @@ -1247,11 +1264,11 @@ struct WKWebViewFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = true; static constexpr std::string_view name = "WKWebViewFrontend"; static constexpr std::string_view enable = "Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON"; - using Host = WKWebViewFrontend; - using Options = WKWebViewOptions; + using Host = WKWebViewFrontend; + using Options = WKWebViewOptions; #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) static constexpr bool compiled = true; - static void initializeNative() { + static void initializeNative() { detail::wkwebview::initialize(); } static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 57a17a76..56d858cc 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -2,6 +2,7 @@ #include "../ContentPolicy.hpp" #include "../tooling/Logger.hpp" +#include "../ViewAssociation.hpp" #include "Action.hpp" #include "Capture.hpp" #include "CloseRequest.hpp" @@ -14,10 +15,9 @@ #include "StartupTrace.hpp" #include "UIExecutor.hpp" #include "Url.hpp" +#include "WebKitGTKPolicy.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" -#include "../ViewAssociation.hpp" -#include "WebKitGTKPolicy.hpp" #include #include @@ -27,8 +27,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -131,37 +131,39 @@ class Api { void (*bytesUnref)(Object) = symbol("g_bytes_unref"); void (*errorFree)(Error*) = symbol("g_error_free"); // GLib resolves the folder from user-dirs.dirs (a user may have moved it), not only from the environment. - const char* (*homeDirectory)() = symbol("g_get_home_dir"); - const char* (*userDirectory)(int) = symbol("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2 - void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); - void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); - const char* (*downloadGetDestination)(Object) = symbol("webkit_download_get_destination"); - void (*chooserSelect)(Object, const char* const*) = symbol("webkit_file_chooser_request_select_files"); - void (*chooserCancel)(Object) = symbol("webkit_file_chooser_request_cancel"); + const char* (*homeDirectory)() = symbol("g_get_home_dir"); + const char* (*userDirectory)(int) = symbol("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2 + void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); + void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); + const char* (*downloadGetDestination)(Object) = symbol("webkit_download_get_destination"); + void (*chooserSelect)(Object, const char* const*) = symbol("webkit_file_chooser_request_select_files"); + void (*chooserCancel)(Object) = symbol("webkit_file_chooser_request_cancel"); // WEBKIT_SCRIPT_DIALOG_ALERT = 0, CONFIRM = 1, PROMPT = 2, BEFORE_UNLOAD_CONFIRM = 3. - int (*dialogType)(Object) = symbol("webkit_script_dialog_get_dialog_type"); - const char* (*dialogMessage)(Object) = symbol("webkit_script_dialog_get_message"); - void (*dialogConfirm)(Object, int) = symbol("webkit_script_dialog_confirm_set_confirmed"); - const char* (*dialogDefault)(Object) = symbol("webkit_script_dialog_prompt_get_default_text"); - void (*dialogPromptText)(Object, const char*) = symbol("webkit_script_dialog_prompt_set_text"); + int (*dialogType)(Object) = symbol("webkit_script_dialog_get_dialog_type"); + const char* (*dialogMessage)(Object) = symbol("webkit_script_dialog_get_message"); + void (*dialogConfirm)(Object, int) = symbol("webkit_script_dialog_confirm_set_confirmed"); + const char* (*dialogDefault)(Object) = symbol("webkit_script_dialog_prompt_get_default_text"); + void (*dialogPromptText)(Object, const char*) = symbol("webkit_script_dialog_prompt_set_text"); // User scripts: WebKitUserContentInjectedFrames TOP_FRAME = 1 and WebKitUserScriptInjectionTime START = 0. - Object (*contextNew)() = symbol("webkit_web_context_new"); - Object (*contentManager)(Object) = symbol("webkit_web_view_get_user_content_manager"); + Object (*contextNew)() = symbol("webkit_web_context_new"); + Object (*contentManager)(Object) = symbol("webkit_web_view_get_user_content_manager"); Object (*scriptNew)(const char*, int, int, const char* const*, const char* const*) = symbol("webkit_user_script_new"); - void (*scriptAdd)(Object, Object) = symbol("webkit_user_content_manager_add_script"); - void (*scriptUnref)(Object) = symbol("webkit_user_script_unref"); + void (*scriptAdd)(Object, Object) = symbol("webkit_user_content_manager_add_script"); + void (*scriptUnref)(Object) = symbol("webkit_user_script_unref"); // Script messages (WebKitGTK 2.40 added the world name; an extra null argument is harmless to older callers' ABI). - int (*registerMessage)(Object, const char*, const char*) = symbol("webkit_user_content_manager_register_script_message_handler"); - void (*viewBackground)(Object, const float*) = symbol("webkit_web_view_set_background_color"); + int (*registerMessage)(Object, const char*, const char*) = symbol("webkit_user_content_manager_register_script_message_handler"); + void (*viewBackground)(Object, const float*) = symbol("webkit_web_view_set_background_color"); // Portal identifier of the window (ADR-020): the backend's own symbols exist only when GTK was built with it, so each is // optional and a missing one leaves the identifier empty. - Object (*nativeSurface)(Object) = optionalSymbol("gtk_native_get_surface"); - int (*instanceIsA)(Object, std::uintptr_t) = optionalSymbol("g_type_check_instance_is_a"); - std::uintptr_t (*x11SurfaceType)() = optionalSymbol("gdk_x11_surface_get_type"); - unsigned long (*x11Xid)(Object) = optionalSymbol("gdk_x11_surface_get_xid"); - std::uintptr_t (*waylandToplevelType)() = optionalSymbol("gdk_wayland_toplevel_get_type"); - int (*waylandExport)(Object, void (*)(Object, const char*, void*), void*, void (*)(void*)) = - optionalSymbol("gdk_wayland_toplevel_export_handle"); + Object (*nativeSurface)(Object) = optionalSymbol("gtk_native_get_surface"); + int (*instanceIsA)(Object, std::uintptr_t) = optionalSymbol("g_type_check_instance_is_a"); + std::uintptr_t (*x11SurfaceType)() = optionalSymbol("gdk_x11_surface_get_type"); + unsigned long (*x11Xid)(Object) = optionalSymbol("gdk_x11_surface_get_xid"); + std::uintptr_t (*waylandToplevelType)() = optionalSymbol("gdk_wayland_toplevel_get_type"); + int (*waylandExport)(Object, + void (*)(Object, const char*, void*), + void*, + void (*)(void*)) = optionalSymbol("gdk_wayland_toplevel_export_handle"); }; inline Api& api() { @@ -229,7 +231,7 @@ inline std::filesystem::path profileDirectory(const char* variable, const char* /// outlives the window finds it null. struct CaptureJob; struct CaptureTarget { - Api::Object view = nullptr; + Api::Object view = nullptr; PendingCaptures pending; // Requests nobody has answered yet, queued or in flight. }; @@ -242,7 +244,7 @@ struct CaptureJob { inline void answer(CaptureJob& job, CaptureResult result) noexcept { try { job.done.set_value(std::move(result)); - } catch (...) { } // Already answered: a closing window may have answered before the engine did. + } catch (...) {} // Already answered: a closing window may have answered before the engine did. } /// The window is going away: no pending request waits for an answer that will never come. @@ -282,7 +284,7 @@ inline void finishCapture(Api::Object view, Api::Object result, void* owner) noe } catch (...) { try { (*job)->done.set_exception(std::current_exception()); - } catch (...) { } + } catch (...) {} } } @@ -341,7 +343,7 @@ struct Session : FailureState { WindowOptions windowOptions; std::function navigationCancelled; /// Per-launch proof of this view (ADR-020), given at the start of the top-level documents of the application's origin. - ViewLaunch launch; + ViewLaunch launch; std::chrono::milliseconds startupTimeout{30000}; // the initial document must load within this interval /// A window opened beside the application's own (#616): it shares the network session (cookies, storage and downloads) /// of the first one, runs no loop of its own and reports its closing to `closedHook` instead of ending the loop. @@ -365,26 +367,26 @@ struct Session : FailureState { std::vector handlers; std::filesystem::path reserved; // The destination given to this download, until it ends. }; - DownloadReservations reservations; - std::vector downloads; - unsigned long downloadStartedHandler = 0; - bool closed = false; - bool initialNavigation = true; - unsigned navigationTimer = 0; - unsigned presentTimer = 0; // presents the window anyway when the first frame is late - bool firstNotified = false; // the page's first notification of the session came, whenever it did - frontend::detail::Presentation presentation; - frontend::detail::StartupTrace trace; - unsigned portalTimer = 0; // retries the Wayland export until the toplevel can be exported - int portalAttempts = 0; - std::uint64_t portalGeneration = 0; // the publication this session's identifier belongs to - unsigned long windowHandler = 0; - std::vector viewHandlers; + DownloadReservations reservations; + std::vector downloads; + unsigned long downloadStartedHandler = 0; + bool closed = false; + bool initialNavigation = true; + unsigned navigationTimer = 0; + unsigned presentTimer = 0; // presents the window anyway when the first frame is late + bool firstNotified = false; // the page's first notification of the session came, whenever it did + frontend::detail::Presentation presentation; + frontend::detail::StartupTrace trace; + unsigned portalTimer = 0; // retries the Wayland export until the toplevel can be exported + int portalAttempts = 0; + std::uint64_t portalGeneration = 0; // the publication this session's identifier belongs to + unsigned long windowHandler = 0; + std::vector viewHandlers; /// Profile files of the GStreamer opt-out (`WindowOptions::media == false`); empty otherwise. - std::filesystem::path mediaPlugins, mediaRegistry; - unsigned long messageHandler = 0; // on the content manager, not on the view - std::shared_ptr captureTarget = std::make_shared(); - CaptureRegistration captureRegistration; + std::filesystem::path mediaPlugins, mediaRegistry; + unsigned long messageHandler = 0; // on the content manager, not on the view + std::shared_ptr captureTarget = std::make_shared(); + CaptureRegistration captureRegistration; explicit Session(webfront::detail::BoundContentPolicy rules, WindowOptions settings = {}) @@ -458,8 +460,7 @@ struct Session : FailureState { if (first && closedHook) { try { closedHook(); - } catch (...) { - } + } catch (...) {} } } void failAndClose(std::string_view message) noexcept { @@ -485,7 +486,7 @@ struct Session : FailureState { /// The environment WebKit's processes inherit when the application has no media: GStreamer finds no plugin to scan. std::optional mediaScope; // set from the first load until the page's load starts - ScopedEnvironment mediaEnvironment() const { + ScopedEnvironment mediaEnvironment() const { ScopedEnvironment environment; if (!mediaPlugins.empty()) { environment.set("GST_PLUGIN_SYSTEM_PATH_1_0", mediaPlugins.string()); @@ -547,7 +548,7 @@ struct Session : FailureState { void presentHidden() { a.widgetOpacity(window, 0.01); // GTK does not draw a widget at 0, and WebKit would wait for a frame forever a.windowPresent(window); - if (!secondary) // the portal identifier is that of the application's own window + if (!secondary) // the portal identifier is that of the application's own window startPortalExport(); } /// Shows the window once the page painted its first frame, or when the delay expired. @@ -592,7 +593,8 @@ struct Session : FailureState { a.scriptAdd(a.contentManager(view), script); a.scriptUnref(script); a.registerMessage(a.contentManager(view), name, nullptr); - messageHandler = a.connect(a.contentManager(view), "script-message-received::webfrontFirstFrame", reinterpret_cast(onFirstFrame), this, nullptr, 0); + messageHandler = + a.connect(a.contentManager(view), "script-message-received::webfrontFirstFrame", reinterpret_cast(onFirstFrame), this, nullptr, 0); } void installViewAssociation() { @@ -746,7 +748,7 @@ struct Session : FailureState { } static void onLoadChanged(Api::Object, int event, Session* self) noexcept { self->mediaScope.reset(); // the web process was launched with the opt-out - if (event == 2) // WEBKIT_LOAD_COMMITTED: slow subresources are not a startup failure. + if (event == 2) // WEBKIT_LOAD_COMMITTED: slow subresources are not a startup failure. self->guard([self] { self->navigationCommitted(); }); @@ -810,7 +812,7 @@ struct Session : FailureState { return 0; // The system dialog, attached to the window by WebKitGTK. } try { - const auto files = self->chooseFiles(); + const auto files = self->chooseFiles(); std::vector pointers; for (const auto& file : files) pointers.push_back(file.c_str()); @@ -833,10 +835,18 @@ struct Session : FailureState { auto& a = api(); ScriptDialog description; switch (a.dialogType(dialog)) { - case 1: description.kind = ScriptDialog::Kind::confirm; break; - case 2: description.kind = ScriptDialog::Kind::prompt; break; - case 3: description.kind = ScriptDialog::Kind::beforeUnload; break; - default: description.kind = ScriptDialog::Kind::alert; break; + case 1: + description.kind = ScriptDialog::Kind::confirm; + break; + case 2: + description.kind = ScriptDialog::Kind::prompt; + break; + case 3: + description.kind = ScriptDialog::Kind::beforeUnload; + break; + default: + description.kind = ScriptDialog::Kind::alert; + break; } if (const auto* message = a.dialogMessage(dialog)) description.message = message; @@ -901,7 +911,7 @@ struct Session : FailureState { self->portalTimer = 0; return 0; // done, or given up: the identifier stays empty and a dialog is simply not parented } - return 1; // not ready yet (no surface, no xdg role): try again in 100 ms + return 1; // not ready yet (no surface, no xdg role): try again in 100 ms } void startPortalExport() { // open() published this session's window just before run(): that is the generation current now. @@ -917,7 +927,7 @@ struct Session : FailureState { if (closed) return; navigationTimer = a.timeoutAdd(frontend::detail::timerMilliseconds(startupTimeout, "WebKitGTKFrontend"), onNavigationTimeout, this); - presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); + presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); trace("load started"); a.load(view, url.c_str()); @@ -962,7 +972,7 @@ inline OpenOptions openOptionsOf(const ViewOptions& view) { /// What the registry of the secondary windows (WindowRegistry.hpp) asks of GTK: reaping is an idle callback. struct WindowHooks { - static constexpr std::string_view name = "WebKitGTKFrontend"; + static constexpr std::string_view name = "WebKitGTKFrontend"; unsigned reaper = 0; template @@ -1004,9 +1014,11 @@ inline void openSecondary(const std::string& address, const std::string& port, c Windows::instance().open( file, [&](Session& primary) { - auto session = std::make_shared(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); - session->secondary = true; - session->sharedNetwork = primary.network; + auto session = std::make_shared( + webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, + options.window); + session->secondary = true; + session->sharedNetwork = primary.network; session->launch = options.launch; session->startupTimeout = primary.startupTimeout; // the first window's delay and test injections session->chooseFiles = primary.chooseFiles; @@ -1026,7 +1038,8 @@ inline bool closeSecondary(const std::string& file) { return Windows::instance().close(file); } -inline void open(std::string_view address, std::string_view port, std::string_view file, const OpenOptions& options = {}, SandboxMode mode = SandboxMode::development) { +inline void +open(std::string_view address, std::string_view port, std::string_view file, const OpenOptions& options = {}, SandboxMode mode = SandboxMode::development) { initialize(mode); // One window per process: a second open() on the main thread is refused before it creates a window. frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); @@ -1043,24 +1056,23 @@ inline void open(std::string_view address, std::string_view port, std::string_vi options.configure(session); // g_idle_add_full is thread-safe and wakes the main context the loop of run() iterates. GTK realizes the window at // present(): run() then sets the X11 identifier, and the Wayland one arrives later. - auto& host = uiExecutorHostOf(); - frontend::detail::InterfaceSession interfaceSession( - host, - nativeWindowHostOf(), - Windows::instance(), - session, - [&host] { - constexpr int defaultIdle = 200; // G_PRIORITY_DEFAULT_IDLE - api().idleAddFull( - defaultIdle, - +[](void* data) -> int { - static_cast(data)->drain(); - return 0; // G_SOURCE_REMOVE - }, - &host, - nullptr); - }, - {.kind = NativeWindowKind::gtk, .pointer = session.window, .portalParent = {}}); + auto& host = uiExecutorHostOf(); + frontend::detail::InterfaceSession interfaceSession(host, + nativeWindowHostOf(), + Windows::instance(), + session, + [&host] { + constexpr int defaultIdle = 200; // G_PRIORITY_DEFAULT_IDLE + api().idleAddFull( + defaultIdle, + +[](void* data) -> int { + static_cast(data)->drain(); + return 0; // G_SOURCE_REMOVE + }, + &host, + nullptr); + }, + {.kind = NativeWindowKind::gtk, .pointer = session.window, .portalParent = {}}); session.run(applicationUrl(address, port, file, options.launch.origin)); } @@ -1072,7 +1084,7 @@ namespace webfront::frontend { /** @brief Optional Linux WebKitGTK 6.0 window. Construct and open on the process main thread. */ template struct BasicWebKitGTKFrontend : EmbeddedFrontend> { - static constexpr detail::webkitgtk::SandboxMode sandboxMode = Mode; + static constexpr detail::webkitgtk::SandboxMode sandboxMode = Mode; static constexpr bool requiresMainThread = true; // GTK is initialized and run on the process main thread static constexpr bool secondaryWindows = true; // they share the first window's network session static constexpr std::string_view name = "WebKitGTKFrontend"; @@ -1083,7 +1095,7 @@ struct BasicWebKitGTKFrontend : EmbeddedFrontend> { static constexpr bool compiled = false; #endif using Options = ViewOptions; - using Host = WebKitGTKHost; + using Host = WebKitGTKHost; #if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) static void initializeNative() { diff --git a/include/webfront/frontend/WebKitGTKPolicy.hpp b/include/webfront/frontend/WebKitGTKPolicy.hpp index 0d6d53f3..0dc31169 100644 --- a/include/webfront/frontend/WebKitGTKPolicy.hpp +++ b/include/webfront/frontend/WebKitGTKPolicy.hpp @@ -19,9 +19,9 @@ #include #include - #include #include #include + #include #include #include #endif @@ -105,7 +105,7 @@ enum class SandboxMode { development, distribution }; // from a different runtime. Inspect names only in diagnostics; values may be private. inline bool containsSnapPath(std::string_view value, std::string_view separators = {}) { while (!value.empty()) { - const auto end = value.find_first_of(separators); + const auto end = value.find_first_of(separators); const auto part = value.substr(0, end); if (part.starts_with("/snap/") || part.starts_with("/var/lib/snapd/snap/")) return true; @@ -118,13 +118,19 @@ inline bool containsSnapPath(std::string_view value, std::string_view separators inline bool inheritedSnapToolkitPaths() { struct Variable { - const char* name; + const char* name; std::string_view separators; }; - constexpr std::array variables = {Variable{"LD_LIBRARY_PATH", ":;"}, Variable{"LD_PRELOAD", ": "}, - Variable{"GIO_MODULE_DIR", ""}, Variable{"GTK_PATH", ":"}, - Variable{"GTK_EXE_PREFIX", ""}, Variable{"GTK_IM_MODULE_FILE", ""}, - Variable{"GSETTINGS_SCHEMA_DIR", ""}, Variable{"LOCPATH", ":"}}; + constexpr std::array variables = { + Variable{ "LD_LIBRARY_PATH", ":;"}, + Variable{ "LD_PRELOAD", ": "}, + Variable{ "GIO_MODULE_DIR", ""}, + Variable{ "GTK_PATH", ":"}, + Variable{ "GTK_EXE_PREFIX", ""}, + Variable{ "GTK_IM_MODULE_FILE", ""}, + Variable{"GSETTINGS_SCHEMA_DIR", ""}, + Variable{ "LOCPATH", ":"} + }; for (const auto& [name, separators] : variables) if (const auto* value = std::getenv(name); value && containsSnapPath(value, separators)) return true; @@ -323,10 +329,10 @@ class ScopedEnvironment { std::vector entries; public: - ScopedEnvironment() = default; + ScopedEnvironment() = default; ScopedEnvironment(const ScopedEnvironment&) = delete; ScopedEnvironment& operator=(const ScopedEnvironment&) = delete; - ScopedEnvironment(ScopedEnvironment&& other) noexcept : entries(std::exchange(other.entries, {})) { } + ScopedEnvironment(ScopedEnvironment&& other) noexcept : entries(std::exchange(other.entries, {})) {} void set(const char* name, const std::string& value) { Entry entry{name, std::nullopt}; if (const auto* current = std::getenv(name)) diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 1a88ffb1..a24a0159 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -2,15 +2,15 @@ #include "../ContentPolicy.hpp" #include "../tooling/Logger.hpp" +#include "../ViewAssociation.hpp" #include "Action.hpp" #include "Capture.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" #include "EmbeddedFrontend.hpp" -#include "../ViewAssociation.hpp" +#include "NativeWindow.hpp" #include "ScriptDialogs.hpp" #include "StartupTrace.hpp" -#include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" @@ -46,7 +46,7 @@ using WebView2Options = ViewOptions; #include #include #include -#include + #include #include #include @@ -155,7 +155,7 @@ inline constexpr UINT captureMessage = WM_APP + 0x4C1; inline constexpr UINT drainMessage = WM_APP + 0x4C3; // UIExecutor: run what the interface thread was asked inline constexpr UINT reapMessage = WM_APP + 0x4C4; // secondary windows (#616): destroy those that closed -inline void reapSecondaryWindows(); // defined with the registry of the windows, after Session +inline void reapSecondaryWindows(); // defined with the registry of the windows, after Session struct CaptureJob { std::promise done; @@ -177,8 +177,8 @@ class CaptureQueue { /// Refuses further requests and returns those still waiting or started but unanswered, to be answered by the caller. std::deque> close() { std::scoped_lock lock{mutex}; - opened = false; - window = nullptr; + opened = false; + window = nullptr; auto jobs = std::exchange(pending, {}); jobs.insert(jobs.end(), inflight.begin(), inflight.end()); inflight.clear(); @@ -215,17 +215,17 @@ class CaptureQueue { } private: - std::mutex mutex; - HWND window = nullptr; - bool opened = false; - std::deque> pending; + std::mutex mutex; + HWND window = nullptr; + bool opened = false; + std::deque> pending; std::vector> inflight; }; inline void answer(CaptureJob& job, CaptureResult result) noexcept { try { job.done.set_value(std::move(result)); - } catch (...) { } + } catch (...) {} } // The PNG that CapturePreview wrote to its memory stream. @@ -281,21 +281,21 @@ class Session : public std::enable_shared_from_this { webfront::detail::BoundContentPolicy contentPolicy; ViewLaunch viewLaunch; // Internal adapter observer, used by lifecycle probes after a successful native cancellation. - std::function navigationCancelled; + std::function navigationCancelled; // Internal adapter observer: the browser exists and nothing is loaded yet (the transport benchmark of ADR-017 registers // its message channel here). - std::function viewReady; + std::function viewReady; // Internal adapter injection (issue #452): answers alert, confirm, prompt and beforeunload without a dialog. Unset keeps // WebView2's own dialogs, which the runtime attaches to the window. - ScriptDialogHandler answerScriptDialog; - bool closed = false; - UINT_PTR startupTimer = 0; + ScriptDialogHandler answerScriptDialog; + bool closed = false; + UINT_PTR startupTimer = 0; // A window opened beside the application's own (#616): it shares the environment (profile, browser process) of the first, // runs no loop of its own and reports its closing to closedHook, once, instead of ending the session. - bool secondary = false; - std::function closedHook; - std::shared_ptr captureQueue = std::make_shared(); - CaptureRegistration captureRegistration; + bool secondary = false; + std::function closedHook; + std::shared_ptr captureQueue = std::make_shared(); + CaptureRegistration captureRegistration; ~Session() { close(); @@ -369,7 +369,7 @@ class Session : public std::enable_shared_from_this { auto hook = std::exchange(closedHook, {}); try { hook(); - } catch (...) { } + } catch (...) {} } } @@ -423,7 +423,9 @@ class Session : public std::enable_shared_from_this { windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW); windowClass.lpszClassName = className.c_str(); if (const auto color = frontend::detail::parseBackground(windowOptions.background)) { - const auto byte = [](float value) { return static_cast(value * 255.0f + 0.5f); }; + const auto byte = [](float value) { + return static_cast(value * 255.0f + 0.5f); + }; backgroundBrush = CreateSolidBrush(RGB(byte((*color)[0]), byte((*color)[1]), byte((*color)[2]))); if (!backgroundBrush) throw std::runtime_error("WebView2: cannot create background brush"); @@ -433,23 +435,24 @@ class Session : public std::enable_shared_from_this { throw std::runtime_error("WebView2: cannot register window class"); registered = true; window = CreateWindowExW(visible ? WS_EX_LAYERED : 0, - className.c_str(), - utf16(windowOptions.title).c_str(), - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, - CW_USEDEFAULT, - windowOptions.width, - windowOptions.height, - nullptr, - nullptr, - windowClass.hInstance, - this); + className.c_str(), + utf16(windowOptions.title).c_str(), + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + windowOptions.width, + windowOptions.height, + nullptr, + nullptr, + windowClass.hInstance, + this); if (!window) throw std::runtime_error("WebView2: cannot create window"); // Bounds initialization errors and an unresponsive runtime must not leave an empty window forever. // A secondary window is not pumped by a session of its own: its watchdog belongs to the window, whose procedure runs // whichever loop dispatches it. - startupTimer = secondary ? SetTimer(window, startupTimerId, startupTimeoutMilliseconds, nullptr) : SetTimer(nullptr, 0, startupTimeoutMilliseconds, nullptr); + startupTimer = secondary ? SetTimer(window, startupTimerId, startupTimeoutMilliseconds, nullptr) + : SetTimer(nullptr, 0, startupTimeoutMilliseconds, nullptr); if (!startupTimer) throw std::runtime_error("WebView2: cannot start startup timer"); if (visible) { @@ -495,18 +498,18 @@ class Session : public std::enable_shared_from_this { } private: - std::wstring className; - HBRUSH backgroundBrush = nullptr; - bool visibleWindow = false; + std::wstring className; + HBRUSH backgroundBrush = nullptr; + bool visibleWindow = false; frontend::detail::Presentation presentation; - UINT_PTR presentTimer = 0; + UINT_PTR presentTimer = 0; frontend::detail::StartupTrace trace; // Bound to the window and handled by its procedure, so that the delay also runs during the system's modal loops // (moving or resizing by the title bar), which dispatch window messages without going through dispatchNextMessage(). static constexpr UINT_PTR presentTimerId = 0x5746; static constexpr UINT_PTR startupTimerId = 0x5747; - void stopPresentTimer() noexcept { + void stopPresentTimer() noexcept { if (presentTimer && window) KillTimer(window, presentTimer); presentTimer = 0; @@ -521,9 +524,9 @@ class Session : public std::enable_shared_from_this { } } WindowOptions windowOptions; - bool registered = false; - bool initialNavigationPending = true; - UINT startupTimeoutMilliseconds = 30'000; + bool registered = false; + bool initialNavigationPending = true; + UINT startupTimeoutMilliseconds = 30'000; void requestWindowClose() noexcept { // Navigation cancelled by the page's own close request is a normal shutdown. @@ -618,7 +621,9 @@ class Session : public std::enable_shared_from_this { if (const auto color = frontend::detail::parseBackground(windowOptions.background)) { Microsoft::WRL::ComPtr controller2; check(created->QueryInterface(IID_PPV_ARGS(&controller2)), "getting background color controller"); - const auto byte = [](float value) { return static_cast(value * 255.0f + 0.5f); }; + const auto byte = [](float value) { + return static_cast(value * 255.0f + 0.5f); + }; // WebView2 supports only fully transparent or fully opaque alpha. COREWEBVIEW2_COLOR native{byte((*color)[3]) == 0 ? BYTE{0} : BYTE{255}, byte((*color)[0]), byte((*color)[1]), byte((*color)[2])}; check(controller2->put_DefaultBackgroundColor(native), "setting background color"); @@ -690,25 +695,26 @@ class Session : public std::enable_shared_from_this { check(CreateStreamOnHGlobal(nullptr, TRUE, &stream), "creating the capture stream"); captureQueue->started(job); // The handler keeps the job and the stream until the engine answers. - check(view->CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG, - stream.Get(), - Microsoft::WRL::Callback([job, stream, queue = captureQueue](HRESULT result) -> HRESULT { - queue->finished(job); - try { - answer(*job, pngBytes(result, stream.Get())); - } catch (...) { - try { - job->done.set_exception(std::current_exception()); - } catch (...) { } - } - return S_OK; - }).Get()), + check(view->CapturePreview( + COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG, + stream.Get(), + Microsoft::WRL::Callback([job, stream, queue = captureQueue](HRESULT result) -> HRESULT { + queue->finished(job); + try { + answer(*job, pngBytes(result, stream.Get())); + } catch (...) { + try { + job->done.set_exception(std::current_exception()); + } catch (...) {} + } + return S_OK; + }).Get()), "starting the capture"); } catch (...) { captureQueue->finished(job); try { job->done.set_exception(std::current_exception()); - } catch (...) { } + } catch (...) {} } } } @@ -826,7 +832,8 @@ class Session : public std::enable_shared_from_this { &token), "registering window close handler"); check(view->add_WebMessageReceived( - Microsoft::WRL::Callback([weak](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { + Microsoft::WRL::Callback([weak](ICoreWebView2*, + ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { LPWSTR raw = nullptr; if (SUCCEEDED(args->TryGetWebMessageAsString(&raw)) && raw) { const std::unique_ptr message(raw, CoTaskMemFree); @@ -881,15 +888,16 @@ class Session : public std::enable_shared_from_this { "registering popup policy"); if (answerScriptDialog) { check(settings->put_AreDefaultScriptDialogsEnabled(FALSE), "disabling the default script dialogs"); - check(view->add_ScriptDialogOpening( - Microsoft::WRL::Callback([weak](ICoreWebView2*, - ICoreWebView2ScriptDialogOpeningEventArgs* args) -> HRESULT { - if (const auto self = weak.lock()) - self->scriptDialogOpening(args); - return S_OK; - }).Get(), - &token), - "registering script dialog handler"); + check( + view->add_ScriptDialogOpening( + Microsoft::WRL::Callback([weak](ICoreWebView2*, + ICoreWebView2ScriptDialogOpeningEventArgs* args) -> HRESULT { + if (const auto self = weak.lock()) + self->scriptDialogOpening(args); + return S_OK; + }).Get(), + &token), + "registering script dialog handler"); } } @@ -901,10 +909,18 @@ class Session : public std::enable_shared_from_this { check(args->get_Kind(&kind), "reading the script dialog kind"); ScriptDialog dialog; switch (kind) { - case COREWEBVIEW2_SCRIPT_DIALOG_KIND_CONFIRM: dialog.kind = ScriptDialog::Kind::confirm; break; - case COREWEBVIEW2_SCRIPT_DIALOG_KIND_PROMPT: dialog.kind = ScriptDialog::Kind::prompt; break; - case COREWEBVIEW2_SCRIPT_DIALOG_KIND_BEFOREUNLOAD: dialog.kind = ScriptDialog::Kind::beforeUnload; break; - default: dialog.kind = ScriptDialog::Kind::alert; break; + case COREWEBVIEW2_SCRIPT_DIALOG_KIND_CONFIRM: + dialog.kind = ScriptDialog::Kind::confirm; + break; + case COREWEBVIEW2_SCRIPT_DIALOG_KIND_PROMPT: + dialog.kind = ScriptDialog::Kind::prompt; + break; + case COREWEBVIEW2_SCRIPT_DIALOG_KIND_BEFOREUNLOAD: + dialog.kind = ScriptDialog::Kind::beforeUnload; + break; + default: + dialog.kind = ScriptDialog::Kind::alert; + break; } LPWSTR message = nullptr; if (SUCCEEDED(args->get_Message(&message)) && message) { @@ -924,8 +940,7 @@ class Session : public std::enable_shared_from_this { if (dialog.kind == ScriptDialog::Kind::prompt) check(args->put_ResultText(utf16(reply.text).c_str()), "setting the prompt result"); check(args->Accept(), "accepting the script dialog"); - } catch (...) { - } + } catch (...) {} } void configure() { @@ -961,7 +976,8 @@ class Session : public std::enable_shared_from_this { } static std::string firstFrameScript() { - return "(()=>{if(window.top!==window)return;function frames(){requestAnimationFrame(()=>requestAnimationFrame(()=>{try{window.chrome.webview.postMessage('webfront:first-frame')}catch(e){}}));}" + return "(()=>{if(window.top!==window)return;function " + "frames(){requestAnimationFrame(()=>requestAnimationFrame(()=>{try{window.chrome.webview.postMessage('webfront:first-frame')}catch(e){}}));}" "if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',frames,{once:true});else frames();})();"; } @@ -973,7 +989,8 @@ class Session : public std::enable_shared_from_this { const auto script = utf16(source); check(browser->AddScriptToExecuteOnDocumentCreated( script.c_str(), - Microsoft::WRL::Callback([weak, browser](HRESULT result, LPCWSTR) -> HRESULT { + Microsoft::WRL::Callback([weak, browser](HRESULT result, + LPCWSTR) -> HRESULT { if (const auto self = weak.lock(); self && !self->closed) { try { check(result, "installing the view association script"); @@ -1001,7 +1018,7 @@ struct WindowHooks { if (windows.primary && windows.primary->window) PostMessageW(windows.primary->window, reapMessage, 0, 0); } - void cancelReap() { } // nothing is pending that clear() must withdraw: a late reap() finds the registry empty + void cancelReap() {} // nothing is pending that clear() must withdraw: a late reap() finds the registry empty void present(Session& session) { // A hidden window stays hidden and does not take the focus. if (const auto handle = session.window; handle && IsWindowVisible(handle)) { @@ -1039,11 +1056,12 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: if (!primary.environment) throw WindowNotReady("WebView2Frontend: the first window is not ready (its browser is being created); call it later"); // The first window's delay, which the application configured (WebView2FrontendWithOptions), not this call's default. - auto session = std::make_shared(primary.startupTimeout()); - session->secondary = true; - session->contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; - session->viewLaunch = options.launch; - session->url = utf16(frontend::detail::applicationUrl(address, port, page, options.launch.origin)); + auto session = std::make_shared(primary.startupTimeout()); + session->secondary = true; + session->contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), + options.contentPolicy}; + session->viewLaunch = options.launch; + session->url = utf16(frontend::detail::applicationUrl(address, port, page, options.launch.origin)); session->answerScriptDialog = primary.answerScriptDialog; session->createWindow(primary.shown(), options.window); return session; @@ -1058,12 +1076,13 @@ inline bool closeSecondary(const std::string& page) { return Windows::instance().close(page); } -inline void open(std::string_view address, - std::string_view port, - std::string_view file, - const WebView2Options& options, +inline void open(std::string_view address, + std::string_view port, + std::string_view file, + const WebView2Options& options, const std::function& prepare = {}) { - auto contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; + auto contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), + options.contentPolicy}; // One window per process: a second open() on the interface thread is refused before it creates anything. frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); Apartment apartment; @@ -1073,10 +1092,10 @@ inline void open(std::string_view address, if (FAILED(available) || !version) throw std::runtime_error("WebView2 runtime not found. Install Microsoft Edge WebView2 Evergreen Runtime: " "https://developer.microsoft.com/microsoft-edge/webview2/"); - auto session = std::make_shared(options.startupTimeout); - session->contentPolicy = std::move(contentPolicy); - session->viewLaunch = options.launch; - session->url = utf16(frontend::detail::applicationUrl(address, port, file, options.launch.origin)); + auto session = std::make_shared(options.startupTimeout); + session->contentPolicy = std::move(contentPolicy); + session->viewLaunch = options.launch; + session->url = utf16(frontend::detail::applicationUrl(address, port, file, options.launch.origin)); session->answerScriptDialog = options.answerScriptDialog; if (prepare) prepare(*session); @@ -1088,16 +1107,16 @@ inline void open(std::string_view address, // the host then fails the operations that relied on that notification instead of leaving them waiting. The session // is declared after the apartment and before run(), so the host closes on every exit, also by exception. The window // is published on the interface thread (this one) and withdrawn before the session destroys it. - frontend::detail::InterfaceSession interfaceSession( - uiExecutorHostOf(), - nativeWindowHostOf(), - Windows::instance(), - *session, - [window = session->window] { - if (!PostMessageW(window, drainMessage, 0, 0)) - throw std::runtime_error("WebView2: cannot wake the interface thread (the message queue is full)"); - }, - {.kind = NativeWindowKind::win32, .pointer = session->window, .portalParent = {}}); + frontend::detail::InterfaceSession interfaceSession(uiExecutorHostOf(), + nativeWindowHostOf(), + Windows::instance(), + *session, + [window = session->window] { + if (!PostMessageW(window, drainMessage, 0, 0)) + throw std::runtime_error( + "WebView2: cannot wake the interface thread (the message queue is full)"); + }, + {.kind = NativeWindowKind::win32, .pointer = session->window, .portalParent = {}}); session->run(); } @@ -1110,18 +1129,18 @@ struct WebView2Frontend; // names the executor's host (UIExecutor.hpp) /** @brief What WebView2Frontend and WebView2FrontendWithOptions share: the WebView2 calls the facade needs. */ struct WebView2Native { - static constexpr bool requiresMainThread = false; // open() makes its calling thread an STA and pumps its messages there - static constexpr bool secondaryWindows = true; - static constexpr bool waitsForFirstWindow = true; // just after show() started, the first environment is being created - static constexpr std::string_view name = "WebView2Frontend"; - static constexpr std::string_view enable = "Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"; + static constexpr bool requiresMainThread = false; // open() makes its calling thread an STA and pumps its messages there + static constexpr bool secondaryWindows = true; + static constexpr bool waitsForFirstWindow = true; // just after show() started, the first environment is being created + static constexpr std::string_view name = "WebView2Frontend"; + static constexpr std::string_view enable = "Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"; using Host = WebView2Frontend; // the hosts are those of WebView2Frontend whichever options provider configures it using Options = WebView2Options; /// Nothing to initialize: the COM apartment belongs to each open(), so a build without the engine fails there. - static void initializeNative() { } + static void initializeNative() {} #if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) static constexpr bool compiled = true; - static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { detail::webview2::open(address, port, file, options); } static void closeNative(const NativeWindowHandle& window) { @@ -1139,7 +1158,7 @@ struct WebView2Native { }; /** @brief Optional Windows embedded frontend. open() owns an STA and blocks until the window closes. */ -struct WebView2Frontend : WebView2Native, EmbeddedFrontend { }; +struct WebView2Frontend : WebView2Native, EmbeddedFrontend {}; /** @brief Configured WebView2 frontend. OptionsProvider::get() returns per-opening WebView2Options. */ template diff --git a/include/webfront/frontend/Window.hpp b/include/webfront/frontend/Window.hpp index 8a6859f7..68b12726 100644 --- a/include/webfront/frontend/Window.hpp +++ b/include/webfront/frontend/Window.hpp @@ -9,6 +9,7 @@ #if defined(_WIN32) #include "../system/WindowsCompat.hpp" + #include #elif defined(__APPLE__) #include @@ -20,9 +21,10 @@ namespace webfront { * @brief Initial native window of the embedded frontends (the system browser ignores it). * * An empty title selects the executable's name. Sizes are in the toolkit's logical pixels; a - * non-positive size selects the default. `background` is a CSS hexadecimal colour ("#rgb", "#rrggbb" or "#rrggbbaa") that WebKitGTK applies as the colour of the - * view under the page; WebView2 applies it to its window and WKWebView to its view, CEF to its browser and window (CEF accepts only an opaque or a fully transparent alpha: any non-zero alpha is opaque), and nothing guarantees the window's look before the first - * frame. Empty keeps the toolkit's default and an invalid value is ignored. `media` is described below. + * non-positive size selects the default. `background` is a CSS hexadecimal colour ("#rgb", "#rrggbb" or "#rrggbbaa") that WebKitGTK applies as the colour of + * the view under the page; WebView2 applies it to its window and WKWebView to its view, CEF to its browser and window (CEF accepts only an opaque or a fully + * transparent alpha: any non-zero alpha is opaque), and nothing guarantees the window's look before the first frame. Empty keeps the toolkit's default and an + * invalid value is ignored. `media` is described below. */ struct WindowOptions { std::string title{}; @@ -42,18 +44,18 @@ namespace frontend::detail { inline std::string executableName() { std::filesystem::path path; try { - #if defined(_WIN32) +#if defined(_WIN32) std::wstring buffer(32768, L'\0'); buffer.resize(GetModuleFileNameW(nullptr, buffer.data(), static_cast(buffer.size()))); path = buffer; - #elif defined(__APPLE__) +#elif defined(__APPLE__) std::string buffer(4096, '\0'); std::uint32_t size = static_cast(buffer.size()); if (_NSGetExecutablePath(buffer.data(), &size) == 0) path = buffer.c_str(); - #elif defined(__linux__) +#elif defined(__linux__) path = std::filesystem::read_symlink("/proc/self/exe"); - #endif +#endif const auto name = path.stem().u8string(); return {name.begin(), name.end()}; } catch (...) { @@ -93,7 +95,9 @@ inline std::optional> parseBackground(std::string_view text /// a browser: any non-zero alpha is therefore opaque, as in WebView2, and only "#rrggbb00" stays transparent (CEF then uses /// its default background). inline std::uint32_t cefBackground(const std::array& rgba) { - const auto byte = [](float v) { return static_cast(v * 255.0f + 0.5f); }; + const auto byte = [](float v) { + return static_cast(v * 255.0f + 0.5f); + }; return (byte(rgba[3]) > 0 ? 0xFF000000u : 0u) | (byte(rgba[0]) << 16) | (byte(rgba[1]) << 8) | byte(rgba[2]); } diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp index be526ff9..6ac27297 100644 --- a/include/webfront/frontend/WindowRegistry.hpp +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -40,7 +40,7 @@ class WindowRegistry { /// The first window, `nullptr` when none runs. Session* primary = nullptr; std::map> secondary; - std::vector> finished; // closed, destroyed by reap() + std::vector> finished; // closed, destroyed by reap() Hooks hooks; bool clearing = false; // clear() is destroying the windows @@ -55,9 +55,13 @@ class WindowRegistry { try { std::rethrow_exception(found->second->failure); } catch (const std::exception& error) { - std::fprintf(stderr, "%.*s: the secondary window of '%s' closed: %s\n", static_cast(Hooks::name.size()), Hooks::name.data(), page.c_str(), error.what()); - } catch (...) { - } + std::fprintf(stderr, + "%.*s: the secondary window of '%s' closed: %s\n", + static_cast(Hooks::name.size()), + Hooks::name.data(), + page.c_str(), + error.what()); + } catch (...) {} } finished.push_back(std::move(found->second)); secondary.erase(found); @@ -91,15 +95,19 @@ class WindowRegistry { * * `create(Session& primary)` builds the window and returns a `std::shared_ptr`; `start(Session&, Session& primary)` * starts its load and returns. Either may throw (a window whose creation or start throws is not registered, and its page - * can be opened again). A page already showing a window is brought to the front. Throws std::logic_error when a new window is needed and the first window is not open: one that closed still runs its loop - * until the pass ends, and a window built now would be destroyed with it. False, with a word on standard error, when - * the session is ending (clear() runs): the request comes from the teardown of a window, which an exception would - * turn into the end of the process, so it is refused without one. + * can be opened again). A page already showing a window is brought to the front. Throws std::logic_error when a new window is needed and the first window + * is not open: one that closed still runs its loop until the pass ends, and a window built now would be destroyed with it. False, with a word on standard + * error, when the session is ending (clear() runs): the request comes from the teardown of a window, which an exception would turn into the end of the + * process, so it is refused without one. */ template bool open(const std::string& page, Create&& create, Start&& start) { if (clearing) { - std::fprintf(stderr, "%.*s: the window of '%s' was not opened: the session is ending\n", static_cast(Hooks::name.size()), Hooks::name.data(), page.c_str()); + std::fprintf(stderr, + "%.*s: the window of '%s' was not opened: the session is ending\n", + static_cast(Hooks::name.size()), + Hooks::name.data(), + page.c_str()); return false; } if (const auto found = secondary.find(page); found != secondary.end()) { @@ -154,7 +162,12 @@ class InterfaceSession { /// Attaches `wake` (thread-safe; makes the loop call host.drain()), publishes `handle` and registers `primary` /// as the first window. Throws what attach() does (a loop is already attached) before anything is held. - InterfaceSession(UIExecutorHost& uiHost, NativeWindowHost& nativeHost, Registry& registry, typename std::remove_pointer_t& primary, std::function wake, NativeWindowHandle handle) + InterfaceSession(UIExecutorHost& uiHost, + NativeWindowHost& nativeHost, + Registry& registry, + typename std::remove_pointer_t& primary, + std::function wake, + NativeWindowHandle handle) : host(uiHost), windowHost(nativeHost), windows(registry) { host.attach(std::move(wake)); bool published = false; diff --git a/include/webfront/http/BlockingWorker.hpp b/include/webfront/http/BlockingWorker.hpp index 5cc32073..45eaa117 100644 --- a/include/webfront/http/BlockingWorker.hpp +++ b/include/webfront/http/BlockingWorker.hpp @@ -55,16 +55,17 @@ class BlockingWorker { ending.swap(threads); } for (auto& thread : ending) - if (thread.joinable()) thread.join(); + if (thread.joinable()) + thread.join(); } /// Thread-safe. True while a job runs or is queued, and counts the completions: a changed `completions` between two /// observations means a job ended in between. A job's continuation is posted before it is counted as ended, so /// that an idle worker with the same count has nothing left to post to the context. struct Activity { - bool busy = false; - std::uint64_t completions = 0; - bool operator==(const Activity&) const = default; + bool busy = false; + std::uint64_t completions = 0; + bool operator==(const Activity&) const = default; }; [[nodiscard]] Activity activity() const { std::lock_guard lock(mutex); @@ -91,7 +92,8 @@ class BlockingWorker { void start() noexcept { try { - if (worker->enqueue(this)) return; + if (worker->enqueue(this)) + return; } catch (...) { networking::ex::set_error(std::move(receiver), std::current_exception()); return; @@ -112,7 +114,9 @@ class BlockingWorker { } networking::ex::set_value(std::move(receiver)); } - void cancel() noexcept override { networking::ex::set_stopped(std::move(receiver)); } + void cancel() noexcept override { + networking::ex::set_stopped(std::move(receiver)); + } }; template @@ -122,27 +126,32 @@ class BlockingWorker { }; /// A sender running `work` on the worker thread. State it touches must outlive the await. - [[nodiscard]] Sender run(std::function work) { return {this, std::move(work)}; } + [[nodiscard]] Sender run(std::function work) { + return {this, std::move(work)}; + } private: - mutable std::mutex mutex; - std::condition_variable changed; - std::deque queue; - bool stopping = false; + mutable std::mutex mutex; + std::condition_variable changed; + std::deque queue; + bool stopping = false; std::vector threads; - std::size_t limit; - std::size_t idle = 0; - std::size_t running = 0; // jobs taken from the queue (or cancelled by a stop) and not yet ended - std::uint64_t completions = 0; + std::size_t limit; + std::size_t idle = 0; + std::size_t running = 0; // jobs taken from the queue (or cancelled by a stop) and not yet ended + std::uint64_t completions = 0; bool enqueue(Job* job) { { std::lock_guard lock(mutex); - if (stopping) return false; + if (stopping) + return false; queue.push_back(job); if (queue.size() > idle && threads.size() < limit) { try { - threads.emplace_back([this] { loop(); }); + threads.emplace_back([this] { + loop(); + }); } catch (...) { if (threads.empty()) { queue.pop_back(); @@ -157,18 +166,20 @@ class BlockingWorker { void finished(std::size_t count) noexcept { std::lock_guard lock(mutex); - running -= count; + running -= count; completions += count; } void loop() noexcept { for (;;) { - Job* job = nullptr; + Job* job = nullptr; std::deque cancelled; { std::unique_lock lock(mutex); ++idle; - changed.wait(lock, [this] { return stopping || !queue.empty(); }); + changed.wait(lock, [this] { + return stopping || !queue.empty(); + }); --idle; if (stopping) { cancelled.swap(queue); @@ -185,11 +196,12 @@ class BlockingWorker { continue; } const auto count = cancelled.size(); - for (auto* pending : cancelled) pending->cancel(); + for (auto* pending : cancelled) + pending->cancel(); finished(count); return; } } }; -} // namespace webfront::http +} // namespace webfront::http diff --git a/include/webfront/http/BuffersPolicy.hpp b/include/webfront/http/BuffersPolicy.hpp index 1fe53494..1bab68b8 100644 --- a/include/webfront/http/BuffersPolicy.hpp +++ b/include/webfront/http/BuffersPolicy.hpp @@ -16,7 +16,7 @@ class BufferOverflowException : public std::runtime_error { }; /// Concept defining requirements for a valid buffers policy -template +template concept BuffersPolicyType = requires { { T::receptionBufferSize } -> std::convertible_to; { T::emissionBufferSize } -> std::convertible_to; @@ -34,32 +34,32 @@ inline constexpr size_t defaultMaxDecodedAssetCacheSize = 8 * 1024 * 1024; /// Default buffer sizes as specified in issue #40 struct DefaultBuffersPolicy { - static constexpr size_t receptionBufferSize = 8192; - static constexpr size_t emissionBufferSize = 8192; - static constexpr size_t functionCallBufferSize = 32768; - static constexpr size_t maxMessageSize = defaultMaxMessageSize; - static constexpr size_t maxDecodedAssetSize = defaultMaxDecodedAssetSize; + static constexpr size_t receptionBufferSize = 8192; + static constexpr size_t emissionBufferSize = 8192; + static constexpr size_t functionCallBufferSize = 32768; + static constexpr size_t maxMessageSize = defaultMaxMessageSize; + static constexpr size_t maxDecodedAssetSize = defaultMaxDecodedAssetSize; static constexpr size_t maxDecodedAssetCacheSize = defaultMaxDecodedAssetCacheSize; /// Optional gzip worker limits; legacy policies use these defaults too. - static constexpr size_t maxGzipDecodeJobs = 4; - static constexpr size_t maxGzipDecodeWaiters = 16; - static constexpr size_t maxGzipDecodeBytes = 64 * 1024 * 1024; + static constexpr size_t maxGzipDecodeJobs = 4; + static constexpr size_t maxGzipDecodeWaiters = 16; + static constexpr size_t maxGzipDecodeBytes = 64 * 1024 * 1024; static constexpr size_t maxGzipEncodedAssetSize = 4 * 1024 * 1024; }; /// Custom policy template for user-defined buffer sizes -template struct CustomBuffersPolicy { - static constexpr size_t receptionBufferSize = ReceptionSize; - static constexpr size_t emissionBufferSize = EmissionSize; - static constexpr size_t functionCallBufferSize = FunctionCallSize; - static constexpr size_t maxMessageSize = MaxMessageSize; - static constexpr size_t maxDecodedAssetSize = MaxDecodedAssetSize; + static constexpr size_t receptionBufferSize = ReceptionSize; + static constexpr size_t emissionBufferSize = EmissionSize; + static constexpr size_t functionCallBufferSize = FunctionCallSize; + static constexpr size_t maxMessageSize = MaxMessageSize; + static constexpr size_t maxDecodedAssetSize = MaxDecodedAssetSize; static constexpr size_t maxDecodedAssetCacheSize = MaxDecodedAssetCacheSize; }; @@ -67,9 +67,11 @@ struct CustomBuffersPolicy { /// std::errc::message_size as soon as a frame header announces a message larger than this, in one /// frame or adding up its fragments, before buffering its payload. Control frames (close, ping, /// pong) have their own 125-byte protocol limit instead. -template +template constexpr size_t maxMessageSize() { - if constexpr (requires { { Policy::maxMessageSize } -> std::convertible_to; }) + if constexpr (requires { + { Policy::maxMessageSize } -> std::convertible_to; + }) return Policy::maxMessageSize; else return defaultMaxMessageSize; @@ -99,4 +101,4 @@ constexpr size_t maxDecodedAssetCacheSize() { static_assert(BuffersPolicyType); -} // namespace webfront::http +} // namespace webfront::http diff --git a/include/webfront/http/Encodings.hpp b/include/webfront/http/Encodings.hpp index fee09edc..441bdf44 100644 --- a/include/webfront/http/Encodings.hpp +++ b/include/webfront/http/Encodings.hpp @@ -11,12 +11,11 @@ #include #include #include +#include #include #include #include -#include - namespace webfront { namespace uri { @@ -52,22 +51,26 @@ inline void appendPercentEncodedByte(std::string& encoded, unsigned char byte) { decoded.reserve(uri.size()); for (std::size_t index = 0; index < uri.size(); ++index) { switch (uri[index]) { - case '%': - if (index + 3 <= uri.size() && std::isxdigit(static_cast(uri[index + 1])) - && std::isxdigit(static_cast(uri[index + 2]))) { - auto hexToValue = [](char c) -> uint8_t { - if (c >= '0' && c <= '9') return uint8_t(c - '0'); - if (c >= 'A' && c <= 'F') return uint8_t(c - 'A' + 10); - return uint8_t(c - 'a' + 10); - }; - decoded += char(hexToValue(uri[index + 1]) * 16 + hexToValue(uri[index + 2])); - index += 2; - } - else + case '%': + if (index + 3 <= uri.size() && std::isxdigit(static_cast(uri[index + 1])) + && std::isxdigit(static_cast(uri[index + 2]))) { + auto hexToValue = [](char c) -> uint8_t { + if (c >= '0' && c <= '9') + return uint8_t(c - '0'); + if (c >= 'A' && c <= 'F') + return uint8_t(c - 'A' + 10); + return uint8_t(c - 'a' + 10); + }; + decoded += char(hexToValue(uri[index + 1]) * 16 + hexToValue(uri[index + 2])); + index += 2; + } else + decoded += uri[index]; + break; + case '+': + decoded += plusAsSpace ? ' ' : '+'; + break; + default: decoded += uri[index]; - break; - case '+': decoded += plusAsSpace ? ' ' : '+'; break; - default: decoded += uri[index]; } } return decoded; @@ -81,55 +84,90 @@ inline void appendPercentEncodedByte(std::string& encoded, unsigned char byte) { // └─┬─┘ └─────────────┬────────────┘└───────┬───────┘ └────────────┬────────────┘ └┬┘ // scheme authority path query fragment struct URI { - URI(std::string_view uri) : string(decode(uri)), scheme(next(string)), authority(next(string)), path(next(string)), query(next(string)), - fragment(next(string)), userinfo(next(authority)), host(next(authority)), port(next(authority)) {} - - const std::string string; + URI(std::string_view uri) + : string(decode(uri)), + scheme(next(string)), + authority(next(string)), + path(next(string)), + query(next(string)), + fragment(next(string)), + userinfo(next(authority)), + host(next(authority)), + port(next(authority)) {} + + const std::string string; const std::string_view scheme, authority, path, query, fragment, userinfo, host, port; -private: +private: std::string_view next(std::string_view uri) const { - static constexpr size_t schem{0}, autho{1}, path_{2}, quer_{3}, fragm{4}, usrnf{5}, host_{6}, port_{7}, npos = std::string_view::npos; - static size_t step{port_}, mark{0}, mark2{0}; + static constexpr size_t schem{0}, autho{1}, path_{2}, quer_{3}, fragm{4}, usrnf{5}, host_{6}, port_{7}, npos = std::string_view::npos; + static size_t step{port_}, mark{0}, mark2{0}; step = (step == port_) ? schem : step + 1; switch (step) { - case schem: mark = uri.find("://"); return mark == npos ? std::string_view{} : uri.substr(0, mark); - case autho: mark2 = uri.find("/", scheme.empty() ? 0 : mark + 3); - if (mark2 == npos) { mark2 = uri.size() - 1; return {}; } - if (scheme.empty()) return {}; + case schem: + mark = uri.find("://"); + return mark == npos ? std::string_view{} : uri.substr(0, mark); + case autho: + mark2 = uri.find("/", scheme.empty() ? 0 : mark + 3); + if (mark2 == npos) { + mark2 = uri.size() - 1; + return {}; + } + if (scheme.empty()) + return {}; return uri.substr(mark + 3, mark2 - mark - 3); - case path_: mark = uri.find("?", scheme.empty() ? 0 : mark2 + 1); + case path_: + mark = uri.find("?", scheme.empty() ? 0 : mark2 + 1); if (mark == npos) { mark = uri.find("#"); - if (mark == npos) { mark = uri.size() - 1; return uri.substr(mark2); } + if (mark == npos) { + mark = uri.size() - 1; + return uri.substr(mark2); + } } return uri.substr(mark2, mark - mark2); - case quer_: mark2 = uri.find("#", mark + 1); - if (mark2 == npos) { mark2 = uri.size() - 1; return uri.substr(mark + 1); } else return uri.substr(mark + 1, mark2 - mark - 1); - case fragm: return uri.substr(mark2 + 1); - case usrnf: mark = uri.find("@"); - if (mark == npos) return {}; else return uri.substr(0, mark); - case host_: mark2 = uri.find(":", mark + 1); - if (mark2 == npos) return uri.substr(mark + 1); else return uri.substr(mark + 1, mark2 - mark - 1); - case port_: if (mark2 != npos) return uri.substr(mark2 + 1); + case quer_: + mark2 = uri.find("#", mark + 1); + if (mark2 == npos) { + mark2 = uri.size() - 1; + return uri.substr(mark + 1); + } else + return uri.substr(mark + 1, mark2 - mark - 1); + case fragm: + return uri.substr(mark2 + 1); + case usrnf: + mark = uri.find("@"); + if (mark == npos) + return {}; + else + return uri.substr(0, mark); + case host_: + mark2 = uri.find(":", mark + 1); + if (mark2 == npos) + return uri.substr(mark + 1); + else + return uri.substr(mark + 1, mark2 - mark - 1); + case port_: + if (mark2 != npos) + return uri.substr(mark2 + 1); } - return {}; + return {}; } }; -} // namespace uri +} // namespace uri namespace base64 { namespace detail { -[[nodiscard]]inline std::string encode(const uint8_t* input, size_t size) { +[[nodiscard]] inline std::string encode(const uint8_t* input, size_t size) { static constexpr std::array code = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', - 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', - 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; std::string output(4 * ((size + 2) / 3), '\0'); - auto coded = output.begin(); - size_t i = 0; + auto coded = output.begin(); + size_t i = 0; for (; size - i >= 3; i += 3) { *coded++ = code[(input[i] >> 2) & 0x3Fu]; *coded++ = code[((input[i] & 0x3u) << 4) | ((input[i + 1] & 0xF0u) >> 4)]; @@ -141,8 +179,7 @@ namespace detail { if (i == (size - 1)) { *coded++ = code[static_cast(input[i] & 0x3u) << 4]; *coded++ = '='; - } - else { + } else { *coded++ = code[static_cast((input[i] & 0x3u) << 4 | ((input[i + 1] & 0xF0u) >> 4)) & 0x3Fu]; *coded++ = code[static_cast((input[i + 1] & 0xFu) << 2) & 0x3Fu]; } @@ -150,9 +187,9 @@ namespace detail { } return output; } -} // namespace detail +} // namespace detail -template +template concept Container = ::std::movable || requires(T t) { t.data(); t.size(); @@ -165,51 +202,53 @@ concept Container = ::std::movable || requires(T t) { [[nodiscard]] inline std::string encodeInNetworkOrder(Container auto input) { if constexpr (std::endian::native == std::endian::little) - for (auto& elem : input) elem = std::byteswap(elem); + for (auto& elem : input) + elem = std::byteswap(elem); return encode(std::move(input)); } -} // namespace base64 +} // namespace base64 namespace crypto { -static constexpr size_t sha1Length = 5; +static constexpr size_t sha1Length = 5; [[nodiscard]] constexpr std::array sha1(std::string_view input) { std::array digest = {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0}; - std::array block{0}; - size_t blockByteIndex{0}, byteCount{0}; - auto next = [&](uint8_t byte) { + std::array block{0}; + size_t blockByteIndex{0}, byteCount{0}; + auto next = [&](uint8_t byte) { block[blockByteIndex++] = byte; ++byteCount; if ((blockByteIndex = blockByteIndex % 64) == 0) { - auto leftRotate = [](uint32_t value, size_t count) { return (value << count) ^ (value >> (32 - count)); }; + auto leftRotate = [](uint32_t value, size_t count) { + return (value << count) ^ (value >> (32 - count)); + }; uint32_t a{digest[0]}, b{digest[1]}, c{digest[2]}, d{digest[3]}, e{digest[4]}, w[80]; - for (size_t i = 0; i < 16; i++) w[i] = (block[i * 4 + 0] << 24) | (block[i * 4 + 1] << 16) | (block[i * 4 + 2] << 8) | (block[i * 4 + 3]); - for (size_t i = 16; i < 80; i++) w[i] = leftRotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1); + for (size_t i = 0; i < 16; i++) + w[i] = (block[i * 4 + 0] << 24) | (block[i * 4 + 1] << 16) | (block[i * 4 + 2] << 8) | (block[i * 4 + 3]); + for (size_t i = 16; i < 80; i++) + w[i] = leftRotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1); for (std::size_t i = 0; i < 80; ++i) { uint32_t f{0}, k{0}; if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; - } - else if (i < 40) { + } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; - } - else if (i < 60) { + } else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; - } - else { + } else { f = b ^ c ^ d; k = 0xCA62C1D6; } auto temp = leftRotate(a, 5) + f + e + k + w[i]; - e = d; - d = c; - c = leftRotate(b, 30); - b = a; - a = temp; + e = d; + d = c; + c = leftRotate(b, 30); + b = a; + a = temp; } digest[0] += a; digest[1] += b; @@ -219,25 +258,30 @@ static constexpr size_t sha1Length = 5; } }; - for (auto c : input) next(static_cast(c)); + for (auto c : input) + next(static_cast(c)); auto b = byteCount * 8; next(0x80); if (blockByteIndex > 56) - while (blockByteIndex != 0) next(0); - while (blockByteIndex < 56) next(0); - for (auto value : {uint8_t(0), uint8_t(0), uint8_t(0), uint8_t(0), uint8_t(b >> 24), uint8_t(b >> 16), uint8_t(b >> 8), uint8_t(b)}) next(value); + while (blockByteIndex != 0) + next(0); + while (blockByteIndex < 56) + next(0); + for (auto value : {uint8_t(0), uint8_t(0), uint8_t(0), uint8_t(0), uint8_t(b >> 24), uint8_t(b >> 16), uint8_t(b >> 8), uint8_t(b)}) + next(value); return digest; } [[nodiscard]] inline std::string sha1String(std::string_view input) { static const char* digits = "0123456789abcdef"; - std::string output; + std::string output; for (auto d : sha1(input)) - for (int8_t shift = 28; shift >= 0; shift -= 4) output += digits[(d >> shift) & 0xF]; + for (int8_t shift = 28; shift >= 0; shift -= 4) + output += digits[(d >> shift) & 0xF]; return output; } -} // namespace crypto -} // namespace webfront +} // namespace crypto +} // namespace webfront diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 23f3adfe..6869111c 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -39,12 +39,14 @@ #include #include #include -#include #include +#include #include #include -namespace webfront::tls { class Credentials; } +namespace webfront::tls { +class Credentials; +} namespace webfront::http { @@ -60,7 +62,8 @@ class Headers { /// @return the header value with headerName name (or at least the first one) [[nodiscard]] std::optional getHeaderValue(std::string_view headerName) const { for (auto& header : headers) - if (caseInsensitiveEqual(header.name, headerName)) return header.value; + if (caseInsensitiveEqual(header.name, headerName)) + return header.value; return {}; } @@ -68,16 +71,22 @@ class Headers { [[nodiscard]] std::list getHeadersValues(std::string_view headerName) const { std::list values{}; for (auto& header : headers) - if (caseInsensitiveEqual(header.name, headerName)) values.push_back(header.value); + if (caseInsensitiveEqual(header.name, headerName)) + values.push_back(header.value); return values; } /// @return true if text is contained in the value field of headerName (case insensitive) [[nodiscard]] bool headersContain(std::string_view headerName, std::string_view text) const { for (auto header : getHeadersValues(headerName)) { - if (std::search(header.cbegin(), header.cend(), text.cbegin(), text.cend(), [](char c1, char c2) { - return (c1 == c2 || std::toupper(c1) == std::toupper(c2)); - }) != header.cend()) + if (std::search(header.cbegin(), + header.cend(), + text.cbegin(), + text.cend(), + [](char c1, char c2) { + return (c1 == c2 || std::toupper(c1) == std::toupper(c2)); + }) + != header.cend()) return true; } return false; @@ -107,10 +116,10 @@ struct BadRequestException : public std::runtime_error { struct Request : Headers { enum class Method { Connect, Delete, Get, Head, Options, Patch, Post, Put, Trace, Undefined }; - Method method; + Method method; std::string uri; - int httpVersionMajor; - int httpVersionMinor; + int httpVersionMajor; + int httpVersionMinor; void reset() { headers.clear(); @@ -119,34 +128,43 @@ struct Request : Headers { [[nodiscard]] static Method getMethodFromString(std::string_view text) { for (size_t index = 0; index < methodNames.size(); ++index) - if (methodNames[index] == text) return static_cast(index); + if (methodNames[index] == text) + return static_cast(index); return Method::Undefined; } - [[nodiscard]] std::string_view getMethodName() const { return method == Method::Undefined ? "Undefined" : methodNames[static_cast(method)]; } - - void setMethod(std::string_view text) { method = getMethodFromString(text); } + [[nodiscard]] std::string_view getMethodName() const { + return method == Method::Undefined ? "Undefined" : methodNames[static_cast(method)]; + } + + void setMethod(std::string_view text) { + method = getMethodFromString(text); + } [[nodiscard]] bool isUpgradeRequest(std::string_view protocol) const { return headersContain("Connection", "upgrade") && headersContain("Upgrade", protocol); } - template + template bool parseSomeData(InputIterator begin, InputIterator end) { while (begin != end) - if (completeRequest(*begin++)) return true; + if (completeRequest(*begin++)) + return true; return false; } /// Parses up to the end of the headers and returns where it stopped: the bytes after it start the body. - template + template InputIterator consume(InputIterator begin, InputIterator end) { - while (begin != end && !completed()) completeRequest(*begin++); + while (begin != end && !completed()) + completeRequest(*begin++); return begin; } - bool completed() const { return state == State::completed; } + bool completed() const { + return state == State::completed; + } private: std::string methodBuffer; @@ -232,7 +250,7 @@ struct Request : Headers { return false; } inline static std::array methodNames{"CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"}; -}; // clang-format on +}; // clang-format on struct Response : Headers { enum StatusCode : uint16_t { @@ -255,28 +273,28 @@ struct Response : Headers { serviceUnavailable = 503, variantAlsoNegotiates = 506 }; - StatusCode statusCode; + StatusCode statusCode; std::string content; static Response getStatusResponse(StatusCode code) { Response response; response.statusCode = code; - response.content = "" + toString(code) + ""; - response.content += "

" + std::to_string(code) + " " + toString(code) + "

"; + response.content = "" + toString(code) + ""; + response.content += "

" + std::to_string(code) + " " + toString(code) + "

"; response.headers.emplace_back("Content-Length", std::to_string(response.content.size())); response.headers.emplace_back("Content-Type", "text/html"); return response; } - template + template [[nodiscard]] std::vector toBuffers() const { std::vector buffers; httpStatus = "HTTP/1.1 " + std::to_string(statusCode) + " " + toString(statusCode) + "\r\n"; buffers.push_back(Net::Buffer(httpStatus)); static const char separator[] = {':', ' '}; - static const char crlf[] = {'\r', '\n'}; + static const char crlf[] = {'\r', '\n'}; for (auto& header : headers) { buffers.push_back(Net::Buffer(header.name)); buffers.push_back(Net::Buffer(separator)); @@ -288,7 +306,8 @@ struct Response : Headers { if (statusCode != switchingProtocols) buffers.push_back(Net::Buffer(std::string_view{"Connection: close\r\n"})); buffers.push_back(Net::Buffer(crlf)); - if (!content.empty()) buffers.push_back(Net::Buffer(content)); + if (!content.empty()) + buffers.push_back(Net::Buffer(content)); return buffers; } @@ -328,9 +347,9 @@ struct Response : Headers { /// The request a dynamic route answers: the parsed request, its decoded path and its raw query. struct RouteRequest { const Request& request; - std::string_view path; ///< Percent-decoded, without the query; always starts with the route's prefix. - std::string_view query; ///< After the '?', undecoded; empty when there is none. - std::string_view body{}; ///< The body of a `POST` (see RouteOptions::postBodyLimit); empty for `GET` and `HEAD`. + std::string_view path; ///< Percent-decoded, without the query; always starts with the route's prefix. + std::string_view query; ///< After the '?', undecoded; empty when there is none. + std::string_view body{}; ///< The body of a `POST` (see RouteOptions::postBodyLimit); empty for `GET` and `HEAD`. }; /// What a route handler produces. The server adds `Content-Length` (from `contentLength`) and `Connection`; @@ -372,7 +391,7 @@ class RouteTable { std::string prefix; RouteHandler handler; /// The path after the prefix carries a secret (a read token): the server never writes it to its logs. - bool secretPath = false; + bool secretPath = false; /// Applied to the answers the server generates for this route (4xx, 500), which never pass through the handler. std::function harden; /// See RouteOptions::postBodyLimit: unset, the route refuses `POST` with 405. @@ -390,7 +409,7 @@ class RouteTable { /// running keeps the handler it started with; no later request reaches it. class Registration { public: - Registration() = default; + Registration() = default; Registration(const Registration&) = delete; Registration& operator=(const Registration&) = delete; Registration(Registration&& other) noexcept : state(std::move(other.state)), entry(std::move(other.entry)) {} @@ -402,7 +421,9 @@ class RouteTable { } return *this; } - ~Registration() { reset(); } + ~Registration() { + reset(); + } void reset() noexcept { if (auto owner = state.lock()) { @@ -412,12 +433,14 @@ class RouteTable { state.reset(); entry.reset(); } - [[nodiscard]] explicit operator bool() const noexcept { return !state.expired(); } + [[nodiscard]] explicit operator bool() const noexcept { + return !state.expired(); + } private: friend class RouteTable; Registration(std::weak_ptr owner, std::shared_ptr route) : state(std::move(owner)), entry(std::move(route)) {} - std::weak_ptr state; + std::weak_ptr state; std::shared_ptr entry; }; @@ -431,12 +454,15 @@ class RouteTable { /// The same, with the options of RouteOptions (`POST` accepted with a bounded body...). [[nodiscard]] Registration add(std::string prefix, RouteHandler handler, RouteOptions options) { - if (!handler) throw std::invalid_argument("A route needs a handler"); - if (!validPrefix(prefix)) throw std::invalid_argument("Invalid route prefix '" + prefix + "'"); + if (!handler) + throw std::invalid_argument("A route needs a handler"); + if (!validPrefix(prefix)) + throw std::invalid_argument("Invalid route prefix '" + prefix + "'"); // The log redaction recognizes the services space only: a secret route elsewhere could not be masked reliably. if (options.secretPath && !prefix.starts_with("/webfront/services/")) throw std::invalid_argument("A secret route must live under /webfront/services/, not '" + prefix + "'"); - auto entry = std::make_shared(Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit}); + auto entry = std::make_shared( + Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit}); std::lock_guard lock(state->mutex); for (const auto& other : state->entries) if (other->prefix.starts_with(entry->prefix) || entry->prefix.starts_with(other->prefix)) @@ -449,7 +475,8 @@ class RouteTable { [[nodiscard]] std::shared_ptr find(std::string_view path) const { std::lock_guard lock(state->mutex); for (const auto& entry : state->entries) - if (path.starts_with(entry->prefix)) return entry; + if (path.starts_with(entry->prefix)) + return entry; return {}; } @@ -457,7 +484,8 @@ class RouteTable { std::shared_ptr state = std::make_shared(); static bool validPrefix(std::string_view prefix) { - if (prefix.size() < 2 || !prefix.starts_with('/') || !prefix.ends_with('/')) return false; + if (prefix.size() < 2 || !prefix.starts_with('/') || !prefix.ends_with('/')) + return false; if (prefix.find("..") != std::string_view::npos || prefix.find("//") != std::string_view::npos || prefix.find("/./") != std::string_view::npos) return false; return std::none_of(prefix.begin(), prefix.end(), [](char c) { @@ -478,17 +506,21 @@ inline bool mentionsServices(std::string_view target) { for (int pass = 0; pass < 3; ++pass) { std::string lowered; lowered.reserve(text.size()); - for (const char c : text) lowered += c == '\\' ? '/' : static_cast(std::tolower(static_cast(c))); + for (const char c : text) + lowered += c == '\\' ? '/' : static_cast(std::tolower(static_cast(c))); std::string normalized; for (std::size_t from = 0; from <= lowered.size();) { const auto end = std::min(lowered.find('/', from), lowered.size()); const auto segment = std::string_view(lowered).substr(from, end - from); - if (!segment.empty() && segment != ".") normalized += (normalized.empty() ? "" : "/") + std::string(segment); + if (!segment.empty() && segment != ".") + normalized += (normalized.empty() ? "" : "/") + std::string(segment); from = end + 1; } - if (normalized.find(marker) != std::string::npos) return true; + if (normalized.find(marker) != std::string::npos) + return true; auto decoded = uri::decode(lowered, false); - if (decoded == lowered) return false; + if (decoded == lowered) + return false; text = std::move(decoded); } return true; // still encoded after three layers: nothing is worth showing @@ -500,14 +532,18 @@ inline constexpr std::uint64_t malformedLength = std::numeric_limits(a)) == std::tolower(static_cast(b)); }); + return std::ranges::equal(header.name, name, [](char a, char b) { + return std::tolower(static_cast(a)) == std::tolower(static_cast(b)); + }); }); } /// The text without the optional whitespace (spaces and tabs) around it (RFC 9110 §5.6.3). inline std::string_view trimmed(std::string_view text) { - while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1); - while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.remove_suffix(1); + while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) + text.remove_prefix(1); + while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); return text; } @@ -522,11 +558,14 @@ inline std::optional contentLength(const Request& request) { const auto comma = rest.find(','); more = comma != std::string_view::npos; const auto value = trimmed(rest.substr(0, comma)); - if (more) rest.remove_prefix(comma + 1); - std::uint64_t parsed = 0; + if (more) + rest.remove_prefix(comma + 1); + std::uint64_t parsed = 0; const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), parsed); - if (value.empty() || error != std::errc{} || end != value.data() + value.size() || parsed == malformedLength) return malformedLength; - if (length && *length != parsed) return malformedLength; + if (value.empty() || error != std::errc{} || end != value.data() + value.size() || parsed == malformedLength) + return malformedLength; + if (length && *length != parsed) + return malformedLength; length = parsed; } } @@ -542,7 +581,8 @@ inline bool hasField(const Request& request, std::string_view name) { /// a comma-separated list, each element a token compared without case, not a substring), from an HTTP/1.1 or later /// client, as an interim answer is never sent to 1.0. inline bool expectsContinue(const Request& request) { - if (request.httpVersionMajor < 1 || (request.httpVersionMajor == 1 && request.httpVersionMinor < 1)) return false; + if (request.httpVersionMajor < 1 || (request.httpVersionMajor == 1 && request.httpVersionMinor < 1)) + return false; constexpr std::string_view token = "100-continue"; for (const auto& field : fieldsNamed(request, "Expect")) { std::string_view rest = field.value; @@ -550,8 +590,12 @@ inline bool expectsContinue(const Request& request) { const auto comma = rest.find(','); more = comma != std::string_view::npos; const auto text = trimmed(rest.substr(0, comma)); - if (more) rest.remove_prefix(comma + 1); - if (std::ranges::equal(text, token, [](char a, char b) { return std::tolower(static_cast(a)) == b; })) return true; + if (more) + rest.remove_prefix(comma + 1); + if (std::ranges::equal(text, token, [](char a, char b) { + return std::tolower(static_cast(a)) == b; + })) + return true; } } return false; @@ -571,10 +615,12 @@ inline std::string collapseSegments(std::string path) { collapsed += '/'; collapsed += segment; } - if (end == std::string::npos) break; + if (end == std::string::npos) + break; start = end + 1; } - if (collapsed.empty() || path.ends_with('/')) collapsed += '/'; + if (collapsed.empty() || path.ends_with('/')) + collapsed += '/'; return collapsed; } @@ -583,8 +629,12 @@ inline std::string collapseSegments(std::string path) { inline std::optional> splitTarget(const std::string& uri) { const auto mark = uri.find('?'); const auto decoded = uri::decode(std::string_view(uri).substr(0, mark), false); - if (!decoded.starts_with('/') || decoded.find("..") != std::string::npos) return {}; - if (std::any_of(decoded.begin(), decoded.end(), [](char c) { return static_cast(c) < 32 || c == 127; })) return {}; + if (!decoded.starts_with('/') || decoded.find("..") != std::string::npos) + return {}; + if (std::any_of(decoded.begin(), decoded.end(), [](char c) { + return static_cast(c) < 32 || c == 127; + })) + return {}; return std::pair{collapseSegments(decoded), mark == std::string::npos ? std::string{} : uri.substr(mark + 1)}; } @@ -593,12 +643,16 @@ inline void validateReply(const RouteReply& reply) { const auto isToken = [](std::string_view name) { return !name.empty() && std::all_of(name.begin(), name.end(), [](char c) { // RFC 9110 tchar, spelled out: std::isalnum depends on the locale and may accept non-ASCII bytes. - return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || std::string_view("!#$%&'*+-.^_`|~").find(c) != std::string_view::npos; + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') + || std::string_view("!#$%&'*+-.^_`|~").find(c) != std::string_view::npos; }); }; for (const auto& [name, value] : reply.headers) { - if (!isToken(name)) throw std::runtime_error("Invalid response header name '" + name + "'"); - if (std::any_of(value.begin(), value.end(), [](char c) { return c == '\r' || c == '\n' || c == '\0'; })) + if (!isToken(name)) + throw std::runtime_error("Invalid response header name '" + name + "'"); + if (std::any_of(value.begin(), value.end(), [](char c) { + return c == '\r' || c == '\n' || c == '\0'; + })) throw std::runtime_error("Invalid value for response header '" + name + "'"); for (const auto reserved : {std::string_view("Content-Length"), std::string_view("Connection"), std::string_view("Transfer-Encoding")}) if (std::ranges::equal(name, reserved, [](char a, char b) { @@ -608,7 +662,7 @@ inline void validateReply(const RouteReply& reply) { } } -} // namespace routing +} // namespace routing /// The reply of a route that serves `file` as `contentType`, with the byte ranges of RFC 9110 §14: `Range` selects /// one part (206 with `Content-Range`, 416 when it starts past the end), `If-Range` conditions it on the file's @@ -631,12 +685,15 @@ inline void validateReply(const RouteReply& reply) { } if (file.isEncoded() || !size) { reply.headers.emplace_back("Accept-Ranges", "none"); - reply.body = [file = std::make_shared(std::move(file))](std::span out) { return file->read(out); }; + reply.body = [file = std::make_shared(std::move(file))](std::span out) { + return file->read(out); + }; reply.contentLength = size; return reply; } reply.headers.emplace_back("Accept-Ranges", "bytes"); - if (file.entityTag()) reply.headers.emplace_back("ETag", *file.entityTag()); + if (file.entityTag()) + reply.headers.emplace_back("ETag", *file.entityTag()); // Range is defined for GET only (RFC 9110 §14.2): HEAD describes the full response. const auto selection = request.method == Request::Method::Get ? range::select(request, *size, file.entityTag()) : range::Selection{}; if (selection.outcome == range::Outcome::unsatisfiable) { @@ -656,13 +713,15 @@ inline void validateReply(const RouteReply& reply) { reply.contentLength = length; reply.body = [file = std::make_shared(std::move(file)), first, remaining = length, positioned = first == 0](std::span out) mutable { if (!positioned) { - if (!file->seek(first)) throw std::runtime_error("The file cannot seek"); + if (!file->seek(first)) + throw std::runtime_error("The file cannot seek"); positioned = true; } const auto count = static_cast(std::min(out.size(), remaining)); - if (count == 0) return std::size_t{0}; + if (count == 0) + return std::size_t{0}; const auto read = file->read(out.first(count)); - remaining -= read; + remaining -= read; return read; }; return reply; @@ -672,37 +731,44 @@ template file{}; /// The part of `file` a `Range` request selected: its first byte, and how many bytes follow (206). - bool partial = false; - std::uint64_t offset = 0; - std::uint64_t length = 0; - std::size_t limit = maxDecodedAssetSize(); + bool partial = false; + std::uint64_t offset = 0; + std::uint64_t length = 0; + std::size_t limit = maxDecodedAssetSize(); }; // Explicit synchronous low-level API; Server always uses prepareRequest and the owned worker. - Response handleRequest(Request request) { return prepare(std::move(request), false).response; } - Prepared prepareRequest(Request request) { return prepare(std::move(request), true); } + Response handleRequest(Request request) { + return prepare(std::move(request), false).response; + } + Prepared prepareRequest(Request request) { + return prepare(std::move(request), true); + } template Response finish(Prepared prepared, Lease& lease) { - if (!lease) return encodingError(Response::serviceUnavailable); + if (!lease) + return encodingError(Response::serviceUnavailable); if (!lease.valid() || lease.decoded().size() > maxDecodedAssetSize()) return encodingError(Response::internalServerError); fallbackCache.remember(lease.encoded(), lease.decoded()); @@ -714,10 +780,12 @@ class RequestHandler { private: Prepared prepare(Request request, bool asynchronous) { auto requestPath = filePath(request.uri); - if (!requestPath) return {Response::getStatusResponse(Response::badRequest)}; + if (!requestPath) + return {Response::getStatusResponse(Response::badRequest)}; switch (request.method) { case Request::Method::Get: - if (auto upgrade = webSocketUpgrade(request)) return {std::move(*upgrade)}; + if (auto upgrade = webSocketUpgrade(request)) + return {std::move(*upgrade)}; [[fallthrough]]; case Request::Method::Head: break; @@ -725,10 +793,10 @@ class RequestHandler { return {Response::getStatusResponse(Response::notImplemented)}; } Prepared result; - result.head = request.method == Request::Method::Head; + result.head = request.method == Request::Method::Head; auto& response = result.response; if (auto error = readFile(request, *requestPath, result, asynchronous)) { - response = std::move(*error); + response = std::move(*error); result.needsDecode = false; return result; } @@ -737,10 +805,12 @@ class RequestHandler { if (!result.needsDecode) { if (!response.getHeaderValue("Content-Length")) response.headers.emplace_back("Content-Length", std::to_string(response.content.size())); - if (result.head) response.content.clear(); + if (result.head) + response.content.clear(); } // Only an unencoded file of known size is served by ranges, and it announced them when it was opened. - if (!response.getHeaderValue("Accept-Ranges")) response.headers.emplace_back("Accept-Ranges", "none"); + if (!response.getHeaderValue("Accept-Ranges")) + response.headers.emplace_back("Accept-Ranges", "none"); return result; } @@ -749,27 +819,34 @@ class RequestHandler { // The query is not part of the file name; it is cut before decoding, so "%3F" stays in the name. const auto rawPath = std::string_view(uri).substr(0, uri.find('?')); auto requestUri = uri::decode(rawPath); - const bool secret = routing::mentionsServices(uri) || routing::mentionsServices(requestUri); - if (!secret) log::debug("Request path - raw:'{}' decoded:'{}'", rawPath, requestUri); // never the query - if (!isSafePath(requestUri)) return {}; + const bool secret = routing::mentionsServices(uri) || routing::mentionsServices(requestUri); + if (!secret) + log::debug("Request path - raw:'{}' decoded:'{}'", rawPath, requestUri); // never the query + if (!isSafePath(requestUri)) + return {}; auto requestPath = std::filesystem::path(requestUri).relative_path(); - if (!secret) log::debug(" -> requestPath : {}", requestPath.string()); - if (!requestPath.has_filename()) requestPath /= "index.html"; + if (!secret) + log::debug(" -> requestPath : {}", requestPath.string()); + if (!requestPath.has_filename()) + requestPath /= "index.html"; return requestPath; } static bool isSafePath(std::string_view path) { - if (!path.starts_with('/')) return false; + if (!path.starts_with('/')) + return false; return path.find("..") == std::string_view::npos; } std::optional webSocketUpgrade(const Request& request) const { - if (!request.isUpgradeRequest("websocket")) return {}; + if (!request.isUpgradeRequest("websocket")) + return {}; const auto origins = request.getHeadersValues("Origin"); if (origins.size() > 1 || !contentPolicy.allowsBridge(origins.empty() ? std::nullopt : std::optional{origins.front()})) return rejectWebSocketOrigin(); auto key = request.getHeaderValue("Sec-WebSocket-Key"); - if (!key) return {}; + if (!key) + return {}; Response response; response.statusCode = Response::StatusCode::switchingProtocols; response.headers.emplace_back("Upgrade", "websocket"); @@ -794,15 +871,17 @@ class RequestHandler { // Reads the file into the response content, or returns the error response. std::optional readFile(const Request& request, const std::filesystem::path& requestPath, Prepared& prepared, bool asynchronous) { auto file = fs.open(requestPath); - if (!file) return Response::getStatusResponse(Response::notFound); - auto& response = prepared.response; - const bool fallback = file->isEncoded() && encoding::isGzip(file->getEncoding()) && - !request.acceptsEncoding(file->getEncoding()) && request.acceptsEncoding("identity"); + if (!file) + return Response::getStatusResponse(Response::notFound); + auto& response = prepared.response; + const bool fallback = file->isEncoded() && encoding::isGzip(file->getEncoding()) && !request.acceptsEncoding(file->getEncoding()) + && request.acceptsEncoding("identity"); prepared.identityFallback = fallback; if (asynchronous && !file->isEncoded()) { if (const auto size = file->knownSize()) { response.headers.emplace_back("Accept-Ranges", "bytes"); - if (file->entityTag()) response.headers.emplace_back("ETag", *file->entityTag()); + if (file->entityTag()) + response.headers.emplace_back("ETag", *file->entityTag()); // Range is defined for GET only (RFC 9110 §14.2): HEAD describes the full response. const auto selection = request.method == Request::Method::Get ? range::select(request, *size, file->entityTag()) : range::Selection{}; if (selection.outcome == range::Outcome::unsatisfiable) { @@ -822,18 +901,21 @@ class RequestHandler { response.headers.emplace_back("Content-Range", range::contentRange(selection, *size)); } response.headers.emplace_back("Content-Length", std::to_string(prepared.length)); - if (prepared.head) return {}; + if (prepared.head) + return {}; prepared.file = std::make_unique(std::move(*file)); return {}; } } - const auto inputLimit = asynchronous && fallback ? maxEncodedAssetSize : std::numeric_limits::max(); + const auto inputLimit = asynchronous && fallback ? maxEncodedAssetSize : std::numeric_limits::max(); std::array buffer{}; while (auto bytesRead = file->read(buffer)) { - if (bytesRead > inputLimit - response.content.size()) return encodingError(Response::internalServerError); + if (bytesRead > inputLimit - response.content.size()) + return encodingError(Response::internalServerError); response.content.append(buffer.data(), bytesRead); } - if (!file->isEncoded()) return {}; + if (!file->isEncoded()) + return {}; return negotiateEncoding(request, file->getEncoding(), prepared, asynchronous); } @@ -854,7 +936,8 @@ class RequestHandler { return encodingError(Response::notAcceptable); if (asynchronous) { if (auto cached = fallbackCache.lookup(response.content, prepared.limit, prepared.head)) { - if (!cached->allowed) return encodingError(Response::internalServerError); + if (!cached->allowed) + return encodingError(Response::internalServerError); response.headers.emplace_back("Content-Length", std::to_string(cached->length)); } else { prepared.needsDecode = true; @@ -868,38 +951,47 @@ class RequestHandler { return {}; } - FS fs; + FS fs; detail::BoundContentPolicy contentPolicy; - gzip::ValidatedCache fallbackCache{maxDecodedAssetCacheSize()}; - std::size_t maxEncodedAssetSize{gzip::decodeLimits().encoded}; + gzip::ValidatedCache fallbackCache{maxDecodedAssetCacheSize()}; + std::size_t maxEncodedAssetSize{gzip::decodeLimits().encoded}; }; -template +template class Server { public: - Server(std::string_view address, std::string_view port, std::filesystem::path docRoot = ".", ContentPolicy policy = {}, Decode decode = {}, + Server(std::string_view address, + std::string_view port, + std::filesystem::path docRoot = ".", + ContentPolicy policy = {}, + Decode decode = {}, std::shared_ptr credentials = {}) : acceptor(ioContext), listeningPort((configureTransport(std::move(credentials)), bind(address, port))), - requestHandler(docRoot, detail::BoundContentPolicy{detail::applicationOrigin(address, listeningPort, networking::secureTransport), std::move(policy)}), + requestHandler(docRoot, + detail::BoundContentPolicy{detail::applicationOrigin(address, listeningPort, networking::secureTransport), std::move(policy)}), decodeExecutor(gzip::decodeLimits(), std::move(decode)) { spawn(acceptConnections()); } ~Server() noexcept { drainUntilJoined(); } - Server(const Server&) = delete; - Server(Server&&) = delete; + Server(const Server&) = delete; + Server(Server&&) = delete; Server& operator=(const Server&) = delete; - Server& operator=(Server&&) = delete; + Server& operator=(Server&&) = delete; /// The bound port, including the OS-assigned port when constructed with "0". const std::string& port() const noexcept { return listeningPort; } - void run() { ioContext.run(); } - void runOne() { ioContext.run_one(); } + void run() { + ioContext.run(); + } + void runOne() { + ioContext.run_one(); + } /// Thread-safe. Cancels the acceptor and the connections, and makes run() return. void stop() { @@ -928,7 +1020,8 @@ class Server { tasks.drain(ioContext); break; } catch (const std::logic_error&) { - if (!route.busy && !file.busy && route == routeWorker.activity() && file == fileWorker.activity()) throw; + if (!route.busy && !file.busy && route == routeWorker.activity() && file == fileWorker.activity()) + throw; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } @@ -971,7 +1064,8 @@ class Server { /// Answers the `GET` and `HEAD` requests under `prefix` with `handler` (see RouteTable::add for the /// prefix rules). The route lasts as long as the returned registration; it never masks the embedded /// `WebFront.js`, and takes precedence over the file providers. Thread-safe. - [[nodiscard]] RouteTable::Registration addRoute(std::string prefix, RouteHandler handler, bool secretPath = false, std::function harden = {}) { + [[nodiscard]] RouteTable::Registration + addRoute(std::string prefix, RouteHandler handler, bool secretPath = false, std::function harden = {}) { return routes.add(std::move(prefix), std::move(handler), secretPath, std::move(harden)); } @@ -985,21 +1079,23 @@ class Server { upgradeHandler = std::move(handler); } - [[nodiscard]] auto fallbackDecodeStatistics() const { return decodeExecutor.statistics(); } + [[nodiscard]] auto fallbackDecodeStatistics() const { + return decodeExecutor.statistics(); + } [[nodiscard]] auto fallbackCacheStatistics() const { - auto result = requestHandler.fallbackCacheStatistics(); + auto result = requestHandler.fallbackCacheStatistics(); result.decodes = decodeExecutor.statistics().decodes; return result; } private: - typename Net::IoContext ioContext; - typename Net::Acceptor acceptor; - std::string listeningPort; - networking::TaskScope tasks; - RequestHandler requestHandler; - gzip::DecodeExecutor decodeExecutor; - RouteTable routes; + typename Net::IoContext ioContext; + typename Net::Acceptor acceptor; + std::string listeningPort; + networking::TaskScope tasks; + RequestHandler requestHandler; + gzip::DecodeExecutor decodeExecutor; + RouteTable routes; // Route handlers may block for as long as they like: they get their own threads, so that the files of the // providers (WebFront.js, pages) keep flowing for the other browsers. BlockingWorker routeWorker{4}; @@ -1042,7 +1138,12 @@ class Server { // two applications would answer each other's requests. SO_EXCLUSIVEADDRUSE makes the second bind fail instead. if constexpr (requires { acceptor.native_handle(); }) { const BOOL exclusive = TRUE; - if (::setsockopt(static_cast(acceptor.native_handle()), SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&exclusive), sizeof exclusive) != 0) + if (::setsockopt(static_cast(acceptor.native_handle()), + SOL_SOCKET, + SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&exclusive), + sizeof exclusive) + != 0) throw std::system_error(::WSAGetLastError(), std::system_category(), "SO_EXCLUSIVEADDRUSE"); } #else @@ -1052,14 +1153,17 @@ class Server { acceptor.listen(); } catch (const std::system_error& error) { // Name the address and port: the bare "bind: Address already in use" does not say which server failed. - throw std::system_error(error.code(), "WebFront cannot listen on " + std::string(address) + ":" + std::string(requestedPort) + ": " + error.code().message() - + (error.code() == std::errc::address_in_use ? " (another instance may use this port; set WEBFRONT_PORT=0 or WebFrontConfig::port to \"0\" for a free port)" : "")); + throw std::system_error(error.code(), + "WebFront cannot listen on " + std::string(address) + ":" + std::string(requestedPort) + ": " + error.code().message() + + (error.code() == std::errc::address_in_use + ? " (another instance may use this port; set WEBFRONT_PORT=0 or WebFrontConfig::port to \"0\" for a free port)" + : "")); } // The port really bound, whatever the request said: the resolver also accepts "00", "65536" or a service name. if constexpr (requires { acceptor.local_endpoint().port(); }) return std::to_string(acceptor.local_endpoint().port()); else - return std::string(requestedPort); // Preserve legacy providers/mocks which have no endpoint query. + return std::string(requestedPort); // Preserve legacy providers/mocks which have no endpoint query. } void spawn(networking::Task task) { @@ -1071,9 +1175,9 @@ class Server { while (!tasks.stopRequested()) { try { spawn(serve(co_await Net::Accept(acceptor))); - } - catch (const std::system_error& error) { - if (error.code() == std::errc::operation_canceled) co_return; + } catch (const std::system_error& error) { + if (error.code() == std::errc::operation_canceled) + co_return; log::error("Accept failed: {}", error.what()); } } @@ -1087,39 +1191,52 @@ class Server { // A request, other than a WebSocket upgrade, under a registered prefix. Every method under a prefix // belongs to the route (405 for those it does not serve): its URLs never fall through to the providers. std::optional matchRoute(const Request& request) const { - if (request.isUpgradeRequest("websocket")) return {}; + if (request.isUpgradeRequest("websocket")) + return {}; auto split = routing::splitTarget(request.uri); - if (!split) return {}; + if (!split) + return {}; auto route = routes.find(split->first); - if (!route) return {}; + if (!route) + return {}; return RouteMatch{std::move(route), std::move(split->first), std::move(split->second)}; } // Sends a body read on the worker in chunks of at most emissionBufferSize bytes, each read after the // previous one was sent (back-pressure). A failure cannot change the status line already sent: it is // logged, and the caller closes the connection, which the client sees as a truncated body. - networking::Task streamBody(BlockingWorker& worker, typename Net::Socket& socket, std::function)> body, - std::optional length, std::string label, bool secret = false) { + networking::Task streamBody(BlockingWorker& worker, + typename Net::Socket& socket, + std::function)> body, + std::optional length, + std::string label, + bool secret = false) { try { std::vector chunk(Policy::emissionBufferSize); std::uint64_t sent = 0; for (;;) { std::size_t count = 0; - co_await networking::ex::continues_on(worker.run([&] { count = body(chunk); }), Net::Scheduler(socket)); - if (count == 0) break; - if (count > chunk.size() || (length && count > *length - sent)) throw std::length_error("The body is longer than announced"); + co_await networking::ex::continues_on(worker.run([&] { + count = body(chunk); + }), + Net::Scheduler(socket)); + if (count == 0) + break; + if (count > chunk.size() || (length && count > *length - sent)) + throw std::length_error("The body is longer than announced"); sent += count; std::vector buffers{Net::Buffer(static_cast(chunk.data()), count)}; co_await Net::Send(socket, buffers); } - if (length && sent != *length) throw std::length_error("The body is shorter than announced"); - } - catch (const std::exception& error) { + if (length && sent != *length) + throw std::length_error("The body is shorter than announced"); + } catch (const std::exception& error) { // The message of a handler can quote the request path, which holds a token on a secret route. - if (secret) log::warn("{} ended its response early (the error is not logged)", label); - else log::warn("{} ended its response early: {}", label, error.what()); - } - catch (...) { + if (secret) + log::warn("{} ended its response early (the error is not logged)", label); + else + log::warn("{} ended its response early: {}", label, error.what()); + } catch (...) { log::warn("{} ended its response early: unknown exception", label); } } @@ -1136,14 +1253,18 @@ class Server { Response response; // The route's policy for the answers the server writes itself; the type and disposition stay those of the error page. const auto sameHeader = [](std::string_view a, std::string_view b) { - return std::ranges::equal(a, b, [](char x, char y) { return std::tolower(static_cast(x)) == std::tolower(static_cast(y)); }); + return std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == std::tolower(static_cast(y)); + }); }; const auto hardenError = [&] { - if (!match.route->harden) return; + if (!match.route->harden) + return; RouteReply policy; match.route->harden(policy); for (auto& [name, value] : policy.headers) - if (!sameHeader(name, "Content-Type") && !sameHeader(name, "Content-Disposition")) response.headers.emplace_back(name, value); + if (!sameHeader(name, "Content-Type") && !sameHeader(name, "Content-Disposition")) + response.headers.emplace_back(name, value); }; // The body of a POST outlives the handler: its answer may stream from the view it was given. `body` holds it only // when it did not come with the headers (then `view` is in the reception buffer of serve()); both live as long as this call. @@ -1153,10 +1274,14 @@ class Server { std::optional refusal; if (post) { const auto length = routing::contentLength(request); - if (routing::hasField(request, "Transfer-Encoding")) refusal = Response::notImplemented; // no chunked bodies - else if (!length) refusal = Response::lengthRequired; - else if (*length == routing::malformedLength) refusal = Response::badRequest; - else if (*length > *match.route->postBodyLimit) refusal = Response::payloadTooLarge; + if (routing::hasField(request, "Transfer-Encoding")) + refusal = Response::notImplemented; // no chunked bodies + else if (!length) + refusal = Response::lengthRequired; + else if (*length == routing::malformedLength) + refusal = Response::badRequest; + else if (*length > *match.route->postBodyLimit) + refusal = Response::payloadTooLarge; else { if (received.size() < *length && routing::expectsContinue(request)) { // The client waits for this interim answer before it sends the body (curl does beyond 1 KiB). @@ -1193,30 +1318,36 @@ class Server { co_await networking::ex::continues_on(routeWorker.run([&] { reply = match.route->handler(RouteRequest{request, match.path, match.query, view}); routing::validateReply(reply); - }), Net::Scheduler(socket)); + }), + Net::Scheduler(socket)); response.statusCode = reply.status; - for (auto& [name, value] : reply.headers) response.headers.emplace_back(name, value); - if (reply.contentLength) response.headers.emplace_back("Content-Length", std::to_string(*reply.contentLength)); - else if (!reply.body) response.headers.emplace_back("Content-Length", "0"); + for (auto& [name, value] : reply.headers) + response.headers.emplace_back(name, value); + if (reply.contentLength) + response.headers.emplace_back("Content-Length", std::to_string(*reply.contentLength)); + else if (!reply.body) + response.headers.emplace_back("Content-Length", "0"); } - } - catch (const std::exception& error) { - if (match.route->secretPath) log::warn("Route {} failed (the error is not logged: it may quote a secret)", match.route->prefix); - else log::warn("Route {} failed: {}", match.route->prefix, error.what()); + } catch (const std::exception& error) { + if (match.route->secretPath) + log::warn("Route {} failed (the error is not logged: it may quote a secret)", match.route->prefix); + else + log::warn("Route {} failed: {}", match.route->prefix, error.what()); response = Response::getStatusResponse(Response::internalServerError); hardenError(); reply.body = nullptr; - } - catch (...) { + } catch (...) { log::warn("Route {} failed with an exception which is not a std::exception", match.route->prefix); response = Response::getStatusResponse(Response::internalServerError); hardenError(); reply.body = nullptr; } const bool streaming = !head && reply.body; // the built-in 405 has no reply.body - if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body + if (head) + response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body co_await Net::Send(socket, response.toBuffers()); - if (streaming) co_await streamBody(routeWorker, socket, std::move(reply.body), reply.contentLength, match.route->prefix, match.route->secretPath); + if (streaming) + co_await streamBody(routeWorker, socket, std::move(reply.body), reply.contentLength, match.route->prefix, match.route->secretPath); co_await closeResponse(socket); } @@ -1225,22 +1356,27 @@ class Server { // The deadline and the server's shutdown cancel the handshake through this source. struct Forward { networking::ex::inplace_stop_source& source; - void operator()() noexcept { source.request_stop(); } + void operator()() noexcept { + source.request_stop(); + } }; - const auto expired = std::make_shared(); - const auto settled = std::make_shared(); + const auto expired = std::make_shared(); + const auto settled = std::make_shared(); networking::ex::stop_callback_for_t shutdown(tasks.stopToken(), Forward{*expired}); spawn(handshakeDeadline(expired, settled)); struct Settle { networking::ex::inplace_stop_source& source; - ~Settle() { source.request_stop(); } + ~Settle() { + source.request_stop(); + } } settle{*settled}; try { co_await networking::ex::stopped_as_error( networking::ex::write_env(Net::Handshake(socket, acceptor), networking::ex::prop{networking::ex::get_stop_token, expired->get_token()}), std::make_error_code(std::errc::timed_out)); } catch (const std::system_error& error) { - if (tasks.stopRequested()) co_return; // interrupted by the server's shutdown, not a failed or expired handshake + if (tasks.stopRequested()) + co_return; // interrupted by the server's shutdown, not a failed or expired handshake log::debug("TLS handshake failed ({}:{}): {}", error.code().category().name(), error.code().value(), error.what()); co_return; } catch (const std::exception& error) { @@ -1248,22 +1384,24 @@ class Server { co_return; } } - Request request; + Request request; std::optional::Lease> lease; - std::unique_ptr streamed; - std::uint64_t streamOffset = 0, streamLength = 0; - bool head = false; - bool servicesTarget = false; - Response response; + std::unique_ptr streamed; + std::uint64_t streamOffset = 0, streamLength = 0; + bool head = false; + bool servicesTarget = false; + Response response; try { std::array buffer; - std::string_view rest; // received after the headers, still in `buffer`: the start of a body + std::string_view rest; // received after the headers, still in `buffer`: the start of a body while (!request.completed()) { const auto received = co_await Net::Receive(socket, Net::Buffer(buffer)); - if (received == 0) co_return; // the client closed the connection - const char* end = buffer.data() + received; + if (received == 0) + co_return; // the client closed the connection + const char* end = buffer.data() + received; const char* stop = request.consume(static_cast(buffer.data()), end); - if (request.completed()) rest = std::string_view(stop, end); + if (request.completed()) + rest = std::string_view(stop, end); } auto match = matchRoute(request); if (match && match->route->secretPath) @@ -1271,17 +1409,19 @@ class Server { else if (routing::mentionsServices(request.uri)) log::info("Received request {} on a services path (not logged)", request.getMethodName()); else - log::info("Received request {} on {}", request.getMethodName(), std::string_view(request.uri).substr(0, request.uri.find('?'))); // the query may quote a URL + log::info("Received request {} on {}", + request.getMethodName(), + std::string_view(request.uri).substr(0, request.uri.find('?'))); // the query may quote a URL if (match) { co_await serveRoute(socket, std::move(request), std::move(*match), rest, buffer); co_return; } - head = request.method == Request::Method::Head; + head = request.method == Request::Method::Head; servicesTarget = routing::mentionsServices(request.uri); // before the request is moved away - auto prepared = requestHandler.prepareRequest(std::move(request)); + auto prepared = requestHandler.prepareRequest(std::move(request)); if (prepared.needsDecode) { - lease.emplace(co_await networking::ex::continues_on( - decodeExecutor.submit(std::move(prepared.response.content), prepared.limit, prepared.head), Net::Scheduler(socket))); + lease.emplace(co_await networking::ex::continues_on(decodeExecutor.submit(std::move(prepared.response.content), prepared.limit, prepared.head), + Net::Scheduler(socket))); response = requestHandler.finish(std::move(prepared), *lease); } else { if (prepared.identityFallback && prepared.response.statusCode == Response::ok) { @@ -1299,38 +1439,43 @@ class Server { response = std::move(prepared.response); } log::info(" responding http {}", static_cast(response.statusCode)); - } - catch (const BadRequestException&) { + } catch (const BadRequestException&) { response = Response::getStatusResponse(Response::badRequest); - } - catch (const std::bad_alloc&) { + } catch (const std::bad_alloc&) { response = Response::getStatusResponse(Response::serviceUnavailable); response.headers.emplace_back("Vary", "Accept-Encoding"); - } - catch (const std::exception& error) { - if (servicesTarget) log::warn("HTTP asset request on a services path failed (the error is not logged)"); - else log::warn("HTTP asset request failed: {}", error.what()); + } catch (const std::exception& error) { + if (servicesTarget) + log::warn("HTTP asset request on a services path failed (the error is not logged)"); + else + log::warn("HTTP asset request failed: {}", error.what()); response = Response::getStatusResponse(Response::internalServerError); - } - catch (...) { + } catch (...) { log::warn("HTTP asset request failed with an exception which is not a std::exception"); response = Response::getStatusResponse(Response::internalServerError); } - if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body + if (head) + response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body co_await Net::Send(socket, response.toBuffers()); if (streamed) - co_await streamBody(fileWorker, socket, [&file = *streamed, offset = streamOffset, remaining = streamLength, - positioned = streamOffset == 0](std::span out) mutable { - if (!positioned) { - if (!file.seek(offset)) throw std::runtime_error("The file cannot seek"); - positioned = true; - } - const auto count = static_cast(std::min(out.size(), remaining)); - if (count == 0) return std::size_t{0}; - const auto read = file.read(out.first(count)); - remaining -= read; - return read; - }, streamLength, "File response"); + co_await streamBody( + fileWorker, + socket, + [&file = *streamed, offset = streamOffset, remaining = streamLength, positioned = streamOffset == 0](std::span out) mutable { + if (!positioned) { + if (!file.seek(offset)) + throw std::runtime_error("The file cannot seek"); + positioned = true; + } + const auto count = static_cast(std::min(out.size(), remaining)); + if (count == 0) + return std::size_t{0}; + const auto read = file.read(out.first(count)); + remaining -= read; + return read; + }, + streamLength, + "File response"); if (response.statusCode != Response::switchingProtocols || tasks.stopRequested()) co_await closeResponse(socket); // a stopped server hands nothing over: its drain would never end else if (upgradeHandler) @@ -1338,4 +1483,4 @@ class Server { } }; -} // namespace webfront::http +} // namespace webfront::http diff --git a/include/webfront/http/MimeType.hpp b/include/webfront/http/MimeType.hpp index 130d8809..fc7f2a35 100644 --- a/include/webfront/http/MimeType.hpp +++ b/include/webfront/http/MimeType.hpp @@ -19,13 +19,32 @@ struct MimeType { std::string_view extension; Type type; }; - constexpr auto mappings = std::array{{ - {"js", js}, {"mjs", js}, {"htm", html}, {"html", html}, {"jpg", jpg}, {"jpeg", jpg}, {"css", css}, {"png", png}, - {"gif", gif}, {"json", json}, {"pdf", pdf}, {"ttf", ttf}, {"ico", ico}, {"svg", svg}, {"webp", webp}, {"csv", csv}, {"wasm", wasm}, - }}; - if (e.starts_with('.')) e.remove_prefix(1); + constexpr auto mappings = std::array{ + { + {"js", js}, + {"mjs", js}, + {"htm", html}, + {"html", html}, + {"jpg", jpg}, + {"jpeg", jpg}, + {"css", css}, + {"png", png}, + {"gif", gif}, + {"json", json}, + {"pdf", pdf}, + {"ttf", ttf}, + {"ico", ico}, + {"svg", svg}, + {"webp", webp}, + {"csv", csv}, + {"wasm", wasm}, + } + }; + if (e.starts_with('.')) + e.remove_prefix(1); for (const auto& mapping : mappings) - if (e == mapping.extension) return mapping.type; + if (e == mapping.extension) + return mapping.type; return plain; } @@ -51,4 +70,4 @@ struct MimeType { } }; -} // namespace webfront::http +} // namespace webfront::http diff --git a/include/webfront/http/Ranges.hpp b/include/webfront/http/Ranges.hpp index 4f6c546a..6a9275a2 100644 --- a/include/webfront/http/Ranges.hpp +++ b/include/webfront/http/Ranges.hpp @@ -11,9 +11,9 @@ namespace webfront::http::range { enum class Outcome { - whole, ///< No usable range: answer 200 with the entire representation. - partial, ///< Answer 206 with `[first, first + length)`. - unsatisfiable ///< Answer 416. + whole, ///< No usable range: answer 200 with the entire representation. + partial, ///< Answer 206 with `[first, first + length)`. + unsatisfiable ///< Answer 416. }; struct Selection { @@ -25,17 +25,21 @@ struct Selection { namespace detail { inline std::string_view trim(std::string_view text) { - while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1); - while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.remove_suffix(1); + while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) + text.remove_prefix(1); + while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); return text; } /// Digits only; a number too large for 64 bits saturates, which every comparison below treats as "past the end". inline std::optional number(std::string_view digits) { - if (digits.empty()) return {}; + if (digits.empty()) + return {}; std::uint64_t value = 0; for (const char c : digits) { - if (c < '0' || c > '9') return {}; + if (c < '0' || c > '9') + return {}; const auto digit = static_cast(c - '0'); value = value > (std::numeric_limits::max() - digit) / 10 ? std::numeric_limits::max() : value * 10 + digit; } @@ -49,7 +53,7 @@ inline bool startsWithBytes(std::string_view spec) { }); } -} // namespace detail +} // namespace detail /// The part of a representation of `size` bytes that the request asks for. /// @@ -62,40 +66,51 @@ inline bool startsWithBytes(std::string_view spec) { template [[nodiscard]] Selection select(const Fields& request, std::uint64_t size, const std::optional& entityTag) { const auto ranges = request.getHeadersValues("Range"); - if (ranges.size() != 1) return {}; + if (ranges.size() != 1) + return {}; const auto conditions = request.getHeadersValues("If-Range"); - if (conditions.size() > 1) return {}; + if (conditions.size() > 1) + return {}; if (!conditions.empty()) { // A date cannot match: the representation has no Last-Modified. A weak tag never matches (strong comparison). const auto condition = detail::trim(conditions.front()); - if (!entityTag || condition != *entityTag) return {}; + if (!entityTag || condition != *entityTag) + return {}; } auto spec = detail::trim(ranges.front()); - if (!detail::startsWithBytes(spec)) return {}; + if (!detail::startsWithBytes(spec)) + return {}; spec.remove_prefix(6); - if (spec.find(',') != std::string_view::npos) return {}; + if (spec.find(',') != std::string_view::npos) + return {}; const auto dash = spec.find('-'); - if (dash == std::string_view::npos) return {}; + if (dash == std::string_view::npos) + return {}; const auto firstText = spec.substr(0, dash); const auto lastText = spec.substr(dash + 1); if (firstText.empty()) { // "-n": the last n bytes const auto suffix = detail::number(lastText); - if (!suffix) return {}; - if (*suffix == 0 || size == 0) return {Outcome::unsatisfiable}; + if (!suffix) + return {}; + if (*suffix == 0 || size == 0) + return {Outcome::unsatisfiable}; const auto length = std::min(*suffix, size); return {Outcome::partial, size - length, length}; } const auto first = detail::number(firstText); - if (!first) return {}; + if (!first) + return {}; std::optional last; if (!lastText.empty()) { last = detail::number(lastText); - if (!last || *last < *first) return {}; + if (!last || *last < *first) + return {}; } - if (*first >= size) return {Outcome::unsatisfiable}; + if (*first >= size) + return {Outcome::unsatisfiable}; const auto end = last ? std::min(*last, size - 1) : size - 1; return {Outcome::partial, *first, end - *first + 1}; } @@ -110,4 +125,4 @@ template return "bytes */" + std::to_string(size); } -} // namespace webfront::http::range +} // namespace webfront::http::range diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index ceceb291..ed4a2fb3 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -2,12 +2,12 @@ /// @author Ambroise Leclerc /// @brief WebSocket protocol implementation - RFC6455 #pragma once -#include "BuffersPolicy.hpp" -#include "Encodings.hpp" -#include "../tooling/HexDump.hpp" -#include "../networking/Tasks.hpp" #include "../networking/BasicNetworking.hpp" +#include "../networking/Tasks.hpp" +#include "../tooling/HexDump.hpp" #include "../tooling/Logger.hpp" +#include "BuffersPolicy.hpp" +#include "Encodings.hpp" #include #include @@ -30,7 +30,7 @@ namespace webfront::websocket { using Handle = uint32_t; struct Header { - static constexpr size_t maxHeaderSize = 14; + static constexpr size_t maxHeaderSize = 14; std::array raw{}; enum class Opcode { @@ -52,27 +52,47 @@ struct Header { ctrl5, }; - [[nodiscard]] bool FIN() const { return test(0, 7); } - [[nodiscard]] bool RSV1() const { return test(0, 6); } - [[nodiscard]] bool RSV2() const { return test(0, 5); } - [[nodiscard]] bool RSV3() const { return test(0, 4); } - [[nodiscard]] Opcode opcode() const { return static_cast(std::to_integer(raw[0] & std::byte(0b1111))); } - [[nodiscard]] bool MASK() const { return test(1, 7); } - [[nodiscard]] uint8_t payloadLenField() const { return std::to_integer(raw[1] & std::byte(0b1111111)); } + [[nodiscard]] bool FIN() const { + return test(0, 7); + } + [[nodiscard]] bool RSV1() const { + return test(0, 6); + } + [[nodiscard]] bool RSV2() const { + return test(0, 5); + } + [[nodiscard]] bool RSV3() const { + return test(0, 4); + } + [[nodiscard]] Opcode opcode() const { + return static_cast(std::to_integer(raw[0] & std::byte(0b1111))); + } + [[nodiscard]] bool MASK() const { + return test(1, 7); + } + [[nodiscard]] uint8_t payloadLenField() const { + return std::to_integer(raw[1] & std::byte(0b1111111)); + } [[nodiscard]] uint64_t extendedLenField() const { - if (payloadLenField() < 126) return 0; - auto s = [this](size_t i, uint8_t shift = 0) constexpr { return std::to_integer(raw[i]) << shift; }; + if (payloadLenField() < 126) + return 0; + auto s = [this](size_t i, uint8_t shift = 0) constexpr { + return std::to_integer(raw[i]) << shift; + }; return payloadLenField() == 126 ? s(2, 8) | s(3) : s(2, 56) | s(3, 48) | s(4, 40) | s(5, 32) | s(6, 24) | s(7, 16) | s(8, 8) | s(9, 0); } [[nodiscard]] size_t headerSize() const { - if (payloadLenField() < 126) return MASK() ? 6 : 2; - if (payloadLenField() == 126) return MASK() ? 8 : 4; + if (payloadLenField() < 126) + return MASK() ? 6 : 2; + if (payloadLenField() == 126) + return MASK() ? 8 : 4; return MASK() ? 14 : 10; } [[nodiscard]] std::array maskingKey() const { - if (!MASK()) return {}; + if (!MASK()) + return {}; auto index = headerSize() - 4; return {raw[index], raw[index + 1], raw[index + 2], raw[index + 3]}; } @@ -82,19 +102,27 @@ struct Header { return len < 126 ? len : extendedLenField(); } - [[nodiscard]] uint64_t getFrameSize() const { return payloadSize() + headerSize(); } + [[nodiscard]] uint64_t getFrameSize() const { + return payloadSize() + headerSize(); + } void dump() const { log::debug("FIN:{} RSV1:{} RSV2:{} RSV3:{} opcode:{}", FIN(), RSV1(), RSV2(), RSV3(), static_cast(opcode())); log::debug("-> MASK:{} payloadLenField:{} extendedLenField:{}", MASK(), +payloadLenField(), extendedLenField()); auto k = maskingKey(); - log::debug("-> maskingKey:0x{:02x}{:02x}{:02x}{:02x} getPayloadSize:{} headerSize:{}", std::to_integer(k[0]), std::to_integer(k[1]), - std::to_integer(k[2]), std::to_integer(k[3]), payloadSize(), headerSize()); + log::debug("-> maskingKey:0x{:02x}{:02x}{:02x}{:02x} getPayloadSize:{} headerSize:{}", + std::to_integer(k[0]), + std::to_integer(k[1]), + std::to_integer(k[2]), + std::to_integer(k[3]), + payloadSize(), + headerSize()); } /// @return true if first 'size' bytes constitute a complete header [[nodiscard]] bool isComplete(size_t size) const { - if (size < 2) return false; + if (size < 2) + return false; return size >= headerSize(); } @@ -111,21 +139,24 @@ struct Header { } void setPayloadSize(size_t size) { - raw[1] = (raw[1] & std::byte(0b10000000)) | std::byte(size < 126 ? size : size < 65536 ? 126 : 127); + raw[1] = (raw[1] & std::byte(0b10000000)) | std::byte(size < 126 ? size : size < 65536 ? 126 : 127); size_t len = size < 126 ? 0 : size < 65536 ? 2 : 8; - for (size_t i = 0; i < len; ++i) raw[2 + i] = std::byte(size >> (8 * (len - i - 1))); + for (size_t i = 0; i < len; ++i) + raw[2 + i] = std::byte(size >> (8 * (len - i - 1))); } protected: - bool test(size_t index, uint8_t bit) const { return std::to_integer(raw[index] & std::byte(1 << bit)); } + bool test(size_t index, uint8_t bit) const { + return std::to_integer(raw[index] & std::byte(1 << bit)); + } }; struct CloseEvent { - uint16_t status; + uint16_t status; std::string reason; }; -template +template struct Frame : public Header { Frame(std::string_view text) { setFIN(true); @@ -139,20 +170,24 @@ struct Frame : public Header { setOpcode(Opcode::binary); setPayloadSize(dataHead.size() + dataNext.size()); borrowedBuffers.emplace_back(dataHead); - if (!dataNext.empty()) borrowedBuffers.emplace_back(dataNext); + if (!dataNext.empty()) + borrowedBuffers.emplace_back(dataNext); } - Frame(const Frame&) = delete; + Frame(const Frame&) = delete; Frame& operator=(const Frame&) = delete; - Frame(Frame&&) = default; - Frame& operator=(Frame&&) = default; + Frame(Frame&&) = default; + Frame& operator=(Frame&&) = default; - [[nodiscard]] size_t size() const { return payloadSize(); }; + [[nodiscard]] size_t size() const { + return payloadSize(); + }; std::vector toBuffers() const { std::vector buffers; - auto appendPayload = [&buffers](const auto& source) { - for (const auto& buffer : source) buffers.emplace_back(buffer.data(), buffer.size()); + auto appendPayload = [&buffers](const auto& source) { + for (const auto& buffer : source) + buffers.emplace_back(buffer.data(), buffer.size()); }; // freeze() moves the payload from borrowedBuffers into ownedBuffers, so only one of the two holds it. buffers.reserve((ownedBuffers.empty() ? borrowedBuffers.size() : ownedBuffers.size()) + 1); @@ -165,10 +200,12 @@ struct Frame : public Header { } void freeze() { - if (borrowedBuffers.empty()) return; + if (borrowedBuffers.empty()) + return; ownedBuffers.clear(); ownedBuffers.reserve(borrowedBuffers.size()); - for (const auto buffer : borrowedBuffers) ownedBuffers.emplace_back(buffer.begin(), buffer.end()); + for (const auto buffer : borrowedBuffers) + ownedBuffers.emplace_back(buffer.begin(), buffer.end()); borrowedBuffers.clear(); } @@ -189,55 +226,65 @@ struct Frame : public Header { private: std::vector> borrowedBuffers; - std::vector> ownedBuffers; + std::vector> ownedBuffers; }; class FrameDecoder { public: Header::Opcode frameType; - bool finalFrame = true; ///< FIN bit: false for every fragment of a message but its last + bool finalFrame = true; ///< FIN bit: false for every fragment of a message but its last public: - FrameDecoder() : payloadBuffer(sizeof(Header)) { reset(); } - std::span payload() const { return std::span(payloadBuffer.data(), payloadSize); } - [[nodiscard]] size_t consumed() const { return consumedSize; } + FrameDecoder() : payloadBuffer(sizeof(Header)) { + reset(); + } + std::span payload() const { + return std::span(payloadBuffer.data(), payloadSize); + } + [[nodiscard]] size_t consumed() const { + return consumedSize; + } /// True when the last frame's header announced more than its budget: nothing was reserved for it. - [[nodiscard]] bool rejected() const { return oversized; } + [[nodiscard]] bool rejected() const { + return oversized; + } // Parses some incoming data and tries to decode it. // @return true if the frame is complete, false if it needs more data bool parse(std::span buffer) { - return parse(buffer, [](Header::Opcode) { return std::numeric_limits::max(); }); + return parse(buffer, [](Header::Opcode) { + return std::numeric_limits::max(); + }); } // Same, rejecting a frame whose header announces more than maxPayload(opcode) bytes before // reserving them: parse() then returns false and rejected() true. - template + template bool parse(std::span buffer, Budget&& maxPayload) { consumedSize = 0; switch (state) { - case DecodingState::starting: - return parseStart(buffer, maxPayload); - case DecodingState::partialHeader: - return parsePartialHeader(buffer, maxPayload); - case DecodingState::decodingPayload: - return parsePayload(buffer); + case DecodingState::starting: + return parseStart(buffer, maxPayload); + case DecodingState::partialHeader: + return parsePartialHeader(buffer, maxPayload); + case DecodingState::decodingPayload: + return parsePayload(buffer); } return false; } void reset() { - maskIndex = 0; + maskIndex = 0; headerBufferParser = 0; payloadBuffer.clear(); - state = DecodingState::starting; + state = DecodingState::starting; consumedSize = 0; - oversized = false; + oversized = false; } private: // A frame whose header may be complete in `buffer`; otherwise its first bytes are kept. - template + template bool parseStart(std::span buffer, Budget& maxPayload) { const auto* header = reinterpret_cast(buffer.data()); if (!header->isComplete(buffer.size())) { @@ -250,7 +297,7 @@ class FrameDecoder { return startPayload(*header, buffer.subspan(consumedSize), maxPayload); } - template + template bool parsePartialHeader(std::span buffer, Budget& maxPayload) { consumedSize = bufferizeHeaderData(buffer); if (!headerBuffer.isComplete(headerBufferParser)) @@ -259,7 +306,7 @@ class FrameDecoder { } // Decodes a complete header, then the start of its payload found in `rest`. - template + template bool startPayload(const Header& header, std::span rest, Budget& maxPayload) { if (!decodeHeader(header, maxPayload)) return false; @@ -276,7 +323,7 @@ class FrameDecoder { } // Rejects a frame announcing more than maxPayload(opcode) bytes before reserving them. - template + template bool decodeHeader(const Header& header, Budget& maxPayload) { payloadSize = header.payloadSize(); headerSize = header.headerSize(); @@ -306,17 +353,17 @@ class FrameDecoder { } enum class DecodingState { starting, partialHeader, decodingPayload } state; - std::vector payloadBuffer; - Header headerBuffer; - size_t headerBufferParser; - size_t payloadSize, headerSize; - size_t consumedSize; - bool oversized = false; + std::vector payloadBuffer; + Header headerBuffer; + size_t headerBufferParser; + size_t payloadSize, headerSize; + size_t consumedSize; + bool oversized = false; std::array mask; - uint8_t maskIndex; + uint8_t maskIndex; }; -template +template class WebSocket : public std::enable_shared_from_this> { typename Net::Socket socket; @@ -327,11 +374,13 @@ class WebSocket : public std::enable_shared_from_this> { [[nodiscard]] static std::shared_ptr create(typename Net::Socket netSocket, networking::TaskScope& scope) { return std::shared_ptr(new WebSocket(std::move(netSocket), scope)); } - WebSocket(const WebSocket&) = delete; - WebSocket(WebSocket&&) = delete; + WebSocket(const WebSocket&) = delete; + WebSocket(WebSocket&&) = delete; WebSocket& operator=(const WebSocket&) = delete; - WebSocket& operator=(WebSocket&&) = delete; - ~WebSocket() { log::debug("WebSocket destructor"); } + WebSocket& operator=(WebSocket&&) = delete; + ~WebSocket() { + log::debug("WebSocket destructor"); + } void start() { started = true; @@ -344,18 +393,36 @@ class WebSocket : public std::enable_shared_from_this> { stopSource->request_stop(); } - void onMessage(std::function&& handler) { textHandler = std::move(handler); } - void onMessage(std::function)>&& handler) { binaryHandler = std::move(handler); } - void onClose(std::function&& handler) { closeHandler = std::move(handler); } + void onMessage(std::function&& handler) { + textHandler = std::move(handler); + } + void onMessage(std::function)>&& handler) { + binaryHandler = std::move(handler); + } + void onClose(std::function&& handler) { + closeHandler = std::move(handler); + } /// Called on every failed write, before its diagnostic and even after stop(): frames queued /// before stopping still fail, and their producer must be detached rather than fed the error. - void onWriteError(std::function&& handler) { writeErrorHandler = std::move(handler); } + void onWriteError(std::function&& handler) { + writeErrorHandler = std::move(handler); + } /// Called, outside the write lock, each time the queue shrinks: a frame was written, or a failure dropped them all. - void onWritten(std::function&& handler) { writtenHandler = std::move(handler); } - void write(std::string_view text) { writeData(Frame(text)); } - void write(std::span data) { writeData(Frame(data)); } - void write(std::span data, std::span data2) { writeData(Frame(data, data2)); } - void write(Frame frame) { writeData(std::move(frame)); } + void onWritten(std::function&& handler) { + writtenHandler = std::move(handler); + } + void write(std::string_view text) { + writeData(Frame(text)); + } + void write(std::span data) { + writeData(Frame(data)); + } + void write(std::span data, std::span data2) { + writeData(Frame(data, data2)); + } + void write(Frame frame) { + writeData(std::move(frame)); + } /// Queue a frame made by Frame::share(), without copying it. void write(std::shared_ptr> frame) { static_cast(enqueue(std::move(frame), std::numeric_limits::max())); @@ -368,8 +435,9 @@ class WebSocket : public std::enable_shared_from_this> { { std::lock_guard lock(writeMutex); if constexpr (networking::secureTransport) - if (closing) return; - auto group = latestGroups.find(key); + if (closing) + return; + auto group = latestGroups.find(key); if (group == latestGroups.end()) group = latestGroups.emplace(std::string(key), LatestGroup{}).first; auto& latest = group->second; @@ -399,13 +467,13 @@ class WebSocket : public std::enable_shared_from_this> { private: std::array readBuffer; - FrameDecoder decoder; - std::function textHandler; - std::function)> binaryHandler; - std::function closeHandler; - std::function writeErrorHandler; - std::function writtenHandler; - mutable std::mutex writeMutex; + FrameDecoder decoder; + std::function textHandler; + std::function)> binaryHandler; + std::function closeHandler; + std::function writeErrorHandler; + std::function writtenHandler; + mutable std::mutex writeMutex; // The frames of a writeLatest() key that are queued, and the one held back; guarded by writeMutex. struct LatestGroup { std::size_t queued = 0; @@ -415,10 +483,10 @@ class WebSocket : public std::enable_shared_from_this> { using LatestGroups = std::map>; LatestGroups latestGroups; // a key is forgotten once nothing is queued for it struct PendingFrame { - std::shared_ptr> frame; - std::optional group{}; // for writeLatest(): valid while the frame is queued + std::shared_ptr> frame; + std::optional group{}; // for writeLatest(): valid while the frame is queued }; - std::deque writeQueue; // the first frame is the one being written + std::deque writeQueue; // the first frame is the one being written networking::TaskScope& taskScope; std::shared_ptr stopSource{std::make_shared()}; struct StopConnection { @@ -431,13 +499,13 @@ class WebSocket : public std::enable_shared_from_this> { } }; networking::ex::stop_callback_for_t parentStop; - std::atomic_bool started; + std::atomic_bool started; std::atomic_bool closing{false}; // set once the close is claimed: no frame is queued after it, whether or not start() ran // A message sent in several frames (RFC 6455, 5.4), as browsers do with large messages: its // type and the payloads received so far, at most http::maxMessageSize() bytes // (payloadBudget()). std::optional fragmentedType; - std::vector fragments; + std::vector fragments; private: explicit WebSocket(typename Net::Socket netSocket, networking::TaskScope& scope) @@ -477,16 +545,18 @@ class WebSocket : public std::enable_shared_from_this> { } processFrames(std::span(readBuffer.data(), received)); } - } - catch (const std::system_error& error) { + } catch (const std::system_error& error) { failure = error.code(); } - if (failure) closeOnError(failure); + if (failure) + closeOnError(failure); } void processFrames(std::span received) { while (!received.empty() && started) { - const auto frameComplete = decoder.parse(received, [this](Header::Opcode type) { return payloadBudget(type); }); + const auto frameComplete = decoder.parse(received, [this](Header::Opcode type) { + return payloadBudget(type); + }); if (decoder.rejected()) return rejectFrame(); received = received.subspan(decoder.consumed()); @@ -572,7 +642,9 @@ class WebSocket : public std::enable_shared_from_this> { // Control frames (close, ping, pong) carry at most 125 bytes (RFC 6455, 5.5), whatever maxMessageSize. static constexpr size_t maxControlPayload = 125; - static bool isControl(Header::Opcode type) { return type >= Header::Opcode::connectionClose; } + static bool isControl(Header::Opcode type) { + return type >= Header::Opcode::connectionClose; + } // The largest payload a frame may announce: 125 bytes for a control frame, what is left of // maxMessageSize for a continuation, all of it for another frame. Checked on the header, before @@ -614,8 +686,7 @@ class WebSocket : public std::enable_shared_from_this> { if (type == Header::Opcode::text) { if (textHandler) textHandler(std::string_view(reinterpret_cast(data.data()), data.size())); - } - else if (binaryHandler) + } else if (binaryHandler) binaryHandler(data); } @@ -630,7 +701,9 @@ class WebSocket : public std::enable_shared_from_this> { stopSource->request_stop(); } - void writeData(Frame frame) { static_cast(enqueue(std::move(frame), std::numeric_limits::max())); } + void writeData(Frame frame) { + static_cast(enqueue(std::move(frame), std::numeric_limits::max())); + } bool enqueue(Frame frame, std::size_t maxPending) { return enqueue(std::move(frame).share(), maxPending); @@ -640,10 +713,13 @@ class WebSocket : public std::enable_shared_from_this> { { std::lock_guard lock(writeMutex); if constexpr (networking::secureTransport) - if (closing) return false; - if (writeQueue.size() >= maxPending) return false; + if (closing) + return false; + if (writeQueue.size() >= maxPending) + return false; writeQueue.push_back({std::move(frame)}); - if (writeQueue.size() > 1) return true; // the running writeFrames() task will get to it + if (writeQueue.size() > 1) + return true; // the running writeFrames() task will get to it } spawn(writeFrames(this->shared_from_this())); return true; @@ -658,24 +734,26 @@ class WebSocket : public std::enable_shared_from_this> { if constexpr (networking::secureTransport) { if (frame->opcode() == Header::Opcode::connectionClose) { nextFrame(true); - if (writtenHandler) writtenHandler(); + if (writtenHandler) + writtenHandler(); co_await Net::Close(socket); stopSource->request_stop(); // the reply is out: ends closeDeadline() co_return; } } frame = nextFrame(true); - if (writtenHandler) writtenHandler(); + if (writtenHandler) + writtenHandler(); } - } - catch (const std::system_error& error) { + } catch (const std::system_error& error) { { std::lock_guard lock(writeMutex); writeQueue.clear(); latestGroups.clear(); // nothing will be written any more: the frames held back go too } onWriteFailed(error.code()); // reports the closure before the waiters for the queue resume - if (writtenHandler) writtenHandler(); + if (writtenHandler) + writtenHandler(); } } @@ -701,7 +779,8 @@ class WebSocket : public std::enable_shared_from_this> { /// The producer is detached before the diagnostic; the flag only gates the close sequence. void onWriteFailed(std::error_code ec) { - if (writeErrorHandler) writeErrorHandler(ec); + if (writeErrorHandler) + writeErrorHandler(ec); closeOnError(ec); } }; @@ -709,6 +788,6 @@ class WebSocket : public std::enable_shared_from_this> { [[nodiscard]] inline std::string getHashedSecKey(std::string key) { constexpr auto rfc6455Guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; return base64::encodeInNetworkOrder(crypto::sha1(key + rfc6455Guid)); -} +} -} // namespace webfront::websocket +} // namespace webfront::websocket diff --git a/include/webfront/networking/NetworkingMock.hpp b/include/webfront/networking/NetworkingMock.hpp index 2a60e575..84563689 100644 --- a/include/webfront/networking/NetworkingMock.hpp +++ b/include/webfront/networking/NetworkingMock.hpp @@ -23,7 +23,9 @@ struct StoppedSender { template struct Operation { Receiver receiver; - void start() noexcept { ex::set_stopped(std::move(receiver)); } + void start() noexcept { + ex::set_stopped(std::move(receiver)); + } }; template @@ -34,7 +36,7 @@ struct StoppedSender { class IoContextMock { public: - void run() {} + void run() {} std::size_t run_one() { return 0; } @@ -47,7 +49,9 @@ class EndpointMock { public: EndpointMock(std::string_view address, std::string_view port) : originalAddress(address), originalPort(port) {} - auto protocol() const { return originalPort; } + auto protocol() const { + return originalPort; + } }; class SocketBaseMock { @@ -56,14 +60,21 @@ class SocketBaseMock { struct reuse_address { bool isSet; - explicit reuse_address(bool reuse) - : isSet(reuse) {} + explicit reuse_address(bool reuse) : isSet(reuse) {} - bool value() const { return isSet; } + bool value() const { + return isSet; + } }; - void set_option(reuse_address option) { log::debug("SocketBaseMock::set_option(reuse_address({}))", option.value()); } - void bind(const EndpointMock&) { log::debug("SocketBaseMock::bind()"); } - void listen(int backlog = max_connections) { log::debug("SocketBaseMock::listen({})", backlog); } + void set_option(reuse_address option) { + log::debug("SocketBaseMock::set_option(reuse_address({}))", option.value()); + } + void bind(const EndpointMock&) { + log::debug("SocketBaseMock::bind()"); + } + void listen(int backlog = max_connections) { + log::debug("SocketBaseMock::listen({})", backlog); + } public: static const int max_connections = 2; @@ -72,7 +83,7 @@ class SocketBaseMock { class SocketMock : public SocketBaseMock { public: inline static std::array debugBuffer; - inline static size_t bufferIndex = 0; + inline static size_t bufferIndex = 0; enum shutdown_type { shutdown_receive, shutdown_send, shutdown_both }; @@ -88,43 +99,58 @@ class SocketMock : public SocketBaseMock { return inputBuffer.size(); } - void close() { log::debug("SocketMock::close()"); } - void shutdown(shutdown_type type) { log::debug("SocketMock::shutdown({})", static_cast(type)); } + void close() { + log::debug("SocketMock::close()"); + } + void shutdown(shutdown_type type) { + log::debug("SocketMock::shutdown({})", static_cast(type)); + } }; class AcceptorMock : public SocketBaseMock { bool isOpen = false; public: - AcceptorMock(IoContextMock){}; + AcceptorMock(IoContextMock) {}; void open(auto protocol) { log::debug("AcceptorMock::open({})", protocol); isOpen = true; } - bool is_open() const { return isOpen; } + bool is_open() const { + return isOpen; + } }; class NetworkingMock : public BasicNetworking<> { public: - using Acceptor = AcceptorMock; - using Endpoint = EndpointMock; + using Acceptor = AcceptorMock; + using Endpoint = EndpointMock; using IoContext = IoContextMock; - using Socket = SocketMock; + using Socket = SocketMock; using super::ConstBuffer; using super::MutableBuffer; - static EndpointMock Resolve(std::string_view address, std::string_view port) { return {address, port}; } - static auto Scheduler(auto&) { return ex::inline_scheduler{}; } + static EndpointMock Resolve(std::string_view address, std::string_view port) { + return {address, port}; + } + static auto Scheduler(auto&) { + return ex::inline_scheduler{}; + } /// Nothing is ever received or accepted: the tasks awaiting these operations end at once. - static StoppedSender Receive(Socket&, MutableBuffer) { return {}; } - static StoppedSender Accept(auto&) { return {}; } + static StoppedSender Receive(Socket&, MutableBuffer) { + return {}; + } + static StoppedSender Accept(auto&) { + return {}; + } static auto Send(Socket& socket, const auto& buffers) { std::error_code ec; - std::size_t bytesTransferred = 0; - for (const auto& buffer : buffers) bytesTransferred += socket.write_some(buffer, ec); + std::size_t bytesTransferred = 0; + for (const auto& buffer : buffers) + bytesTransferred += socket.write_some(buffer, ec); return ex::just(bytesTransferred); } }; -} // namespace webfront::networking +} // namespace webfront::networking diff --git a/include/webfront/networking/TCPNetworkingStdnet.hpp b/include/webfront/networking/TCPNetworkingStdnet.hpp index 2da48cc7..7c62f26d 100644 --- a/include/webfront/networking/TCPNetworkingStdnet.hpp +++ b/include/webfront/networking/TCPNetworkingStdnet.hpp @@ -29,11 +29,17 @@ class TCPStdnet : public BasicNetworking<::stdnet::const_buffer, ::stdnet::mutab } /// The scheduler running the operations of a socket or an acceptor. - static auto Scheduler(auto& ioObject) { return ioObject.context().get_scheduler(); } + static auto Scheduler(auto& ioObject) { + return ioObject.context().get_scheduler(); + } /// Completes with the number of bytes read, zero at the end of the stream. - static auto Receive(Socket& socket, MutableBuffer buffer) { return ::stdnet::async_receive(socket, buffer); } - static auto Send(Socket& socket, const auto& buffers) { return ::stdnet::async_write(socket, buffers); } + static auto Receive(Socket& socket, MutableBuffer buffer) { + return ::stdnet::async_receive(socket, buffer); + } + static auto Send(Socket& socket, const auto& buffers) { + return ::stdnet::async_write(socket, buffers); + } /// Completes with an accepted socket whose Nagle algorithm is disabled. The option is a latency optimisation: macOS refuses it /// (EINVAL) on a connection that the peer already reset, which is not an accept failure. The socket is delivered anyway and /// its first read or write reports the closed connection (#628). @@ -41,8 +47,7 @@ class TCPStdnet : public BasicNetworking<::stdnet::const_buffer, ::stdnet::mutab return ::stdnet::ex::then(::stdnet::async_accept(acceptor), [](Socket socket) { try { socket.set_option(::stdnet::ip::tcp_no_delay(true)); - } catch (const std::system_error&) { - } + } catch (const std::system_error&) {} return socket; }); } diff --git a/include/webfront/networking/TCPSockets.hpp b/include/webfront/networking/TCPSockets.hpp index 8a97f0ad..0430348a 100644 --- a/include/webfront/networking/TCPSockets.hpp +++ b/include/webfront/networking/TCPSockets.hpp @@ -1,19 +1,20 @@ /// @date 26/01/2022 11:38:19 /// @author Ambroise Leclerc -/// @brief A BSD socket/ winsock implementation +/// @brief A BSD socket/ winsock implementation #pragma once #include "BasicNetworking.hpp" #ifdef _WIN32 -#pragma comment(lib, "Ws2_32.lib") + #pragma comment(lib, "Ws2_32.lib") #else -#include -#include -#include -#include -#include -#include -#include + #include + #include + + #include + #include + #include + #include + #include #endif #include @@ -31,48 +32,71 @@ class SocketLibOS { #ifdef _WIN32 static bool initializeLib() noexcept { WSADATA wsa_data; - int init_value = WSAStartup(MAKEWORD(2, 2), &wsa_data); + int init_value = WSAStartup(MAKEWORD(2, 2), &wsa_data); return init_value == 0; } - static void cleanupLib() noexcept { WSACleanup(); } + static void cleanupLib() noexcept { + WSACleanup(); + } protected: - using SocketType = SOCKET; - using SockLen = int; + using SocketType = SOCKET; + using SockLen = int; static const SocketType invalidSocket = INVALID_SOCKET; - static const int socketError = SOCKET_ERROR; + static const int socketError = SOCKET_ERROR; enum class Shutdown { Read = SD_SEND, Write = SD_RECEIVE, ReadWrite = SD_BOTH }; enum class Error { Timeout = WSAETIMEDOUT, WouldBlock = WSAEWOULDBLOCK }; - static bool closeSocket(SocketType socket) noexcept { return closesocket(socket) != socketError; } - static auto getLastError() { return WSAGetLastError(); } - static std::string getErrorText(bool prependErrorId = true) { return getErrorText(getLastError(), prependErrorId); } + static bool closeSocket(SocketType socket) noexcept { + return closesocket(socket) != socketError; + } + static auto getLastError() { + return WSAGetLastError(); + } + static std::string getErrorText(bool prependErrorId = true) { + return getErrorText(getLastError(), prependErrorId); + } static std::string getErrorText(int error, bool prependErrorId = true) { LPVOID lpMsgBuf{}; - auto bufLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, 0, - reinterpret_cast(&lpMsgBuf), 0, nullptr); + auto bufLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + error, + 0, + reinterpret_cast(&lpMsgBuf), + 0, + nullptr); if (bufLen) { - auto lpMsgStr = reinterpret_cast(lpMsgBuf); + auto lpMsgStr = reinterpret_cast(lpMsgBuf); std::string result(lpMsgStr, lpMsgStr + bufLen); LocalFree(lpMsgBuf); - if (prependErrorId) { result.insert(0, std::to_string(error) + ":"); } + if (prependErrorId) { + result.insert(0, std::to_string(error) + ":"); + } return result; } return {}; } - static constexpr auto toTimeout(const std::chrono::microseconds value) noexcept { return static_cast(value.count() / 1000); } + static constexpr auto toTimeout(const std::chrono::microseconds value) noexcept { + return static_cast(value.count() / 1000); + } }; #else - static bool initializeLib() noexcept { return true; } + static bool initializeLib() noexcept { + return true; + } static void cleanupLib() noexcept {} - static std::string getErrorText(bool prependErrorId = true) { return getErrorText(getLastError(), prependErrorId); } + static std::string getErrorText(bool prependErrorId = true) { + return getErrorText(getLastError(), prependErrorId); + } static std::string getErrorText(int error, bool prependErrorId = true) { - auto errorText = strerror(error); + auto errorText = strerror(error); std::string result(errorText ? errorText : ""); - if (prependErrorId) { result.insert(0, std::to_string(error) + ":"); } + if (prependErrorId) { + result.insert(0, std::to_string(error) + ":"); + } return result; } @@ -84,26 +108,29 @@ class SocketLibOS { } protected: - using SocketType = int; - using SockLen = socklen_t; + using SocketType = int; + using SockLen = socklen_t; static const SocketType invalidSocket = -1; - static const int socketError = -1; + static const int socketError = -1; enum class Shutdown { Read = SHUT_RD, Write = SHUT_WR, ReadWrite = SHUT_RDWR }; enum class Error { Timeout = EAGAIN, WouldBlock = EWOULDBLOCK }; - static bool closeSocket(SocketType socket) { return ::close(socket) != socketError; } - static int getLastError() { return errno; } + static bool closeSocket(SocketType socket) { + return ::close(socket) != socketError; + } + static int getLastError() { + return errno; + } #endif -}; +}; // namespace class TCPSockets : public BasicNetworking<> { public: using super::ConstBuffer; using super::MutableBuffer; - }; -} // namespace networking -} // namespace webfront \ No newline at end of file +} // namespace networking +} // namespace webfront \ No newline at end of file diff --git a/include/webfront/networking/Tasks.hpp b/include/webfront/networking/Tasks.hpp index ee7eeebf..077db7c7 100644 --- a/include/webfront/networking/Tasks.hpp +++ b/include/webfront/networking/Tasks.hpp @@ -168,7 +168,7 @@ class TaskScope { static void reportDeferredShutdown() noexcept { try { log::error("Task shutdown has not joined yet; waiting for suspended operations to finish"); - } catch (...) { } // Logging must not make the destructor path throw. + } catch (...) {} // Logging must not make the destructor path throw. } }; diff --git a/include/webfront/system/DefaultFS.hpp b/include/webfront/system/DefaultFS.hpp index 553ad89e..511fd362 100644 --- a/include/webfront/system/DefaultFS.hpp +++ b/include/webfront/system/DefaultFS.hpp @@ -19,8 +19,10 @@ class ProtectedWebFrontJsFS { explicit ProtectedWebFrontJsFS(std::filesystem::path /*docRoot*/) {} static std::optional open(std::filesystem::path file) { - if (file.relative_path().string() == "WebFront.js") return File{IndexFS::WebFrontJs{}}; - if (file.relative_path().string() == "webfront-dom.mjs") return IndexFS::open(file); + if (file.relative_path().string() == "WebFront.js") + return File{IndexFS::WebFrontJs{}}; + if (file.relative_path().string() == "webfront-dom.mjs") + return IndexFS::open(file); return {}; } }; @@ -32,9 +34,11 @@ class OptionalDevRootFS { explicit OptionalDevRootFS(std::filesystem::path docRoot) : root(std::move(docRoot)) {} std::optional open(std::filesystem::path file) const { - if (root.empty()) return {}; + if (root.empty()) + return {}; std::ifstream stream(root / file, std::ios::binary); - if (stream.is_open()) return File{std::move(stream)}; + if (stream.is_open()) + return File{std::move(stream)}; return {}; } @@ -42,7 +46,7 @@ class OptionalDevRootFS { std::filesystem::path root; }; -} // namespace detail +} // namespace detail /// Precedence (Multi<> serves the first provider that returns a file): /// 1. The embedded, version-matched WebFront.js and webfront-dom.mjs - never overridable. @@ -57,4 +61,4 @@ using DefaultFS = Multi using DefaultFSWith = Multi; -} // namespace webfront::fs +} // namespace webfront::fs diff --git a/include/webfront/system/DeveloperFS.hpp b/include/webfront/system/DeveloperFS.hpp index 45a0b49d..b3df88c4 100644 --- a/include/webfront/system/DeveloperFS.hpp +++ b/include/webfront/system/DeveloperFS.hpp @@ -160,7 +160,7 @@ class DeveloperFS { if (stream) return File{std::move(stream)}; #endif - } catch (const std::exception&) { } + } catch (const std::exception&) {} return std::nullopt; } diff --git a/include/webfront/system/DeveloperFiles.hpp b/include/webfront/system/DeveloperFiles.hpp index 771a0752..d3efe4be 100644 --- a/include/webfront/system/DeveloperFiles.hpp +++ b/include/webfront/system/DeveloperFiles.hpp @@ -109,7 +109,7 @@ inline void removeStaleStaging(const std::filesystem::path& root) { } catch (const std::exception&) { return; } - const auto now = std::filesystem::file_time_type::clock::now(); + const auto now = std::filesystem::file_time_type::clock::now(); for (const auto& entry : std::filesystem::directory_iterator(stagingRoot, error)) if (const auto written = entry.last_write_time(error); !error && now - written >= staleStagingAfter) std::filesystem::remove_all(entry.path(), error); diff --git a/include/webfront/system/DeveloperJournal.hpp b/include/webfront/system/DeveloperJournal.hpp index b00b9749..0ce6e806 100644 --- a/include/webfront/system/DeveloperJournal.hpp +++ b/include/webfront/system/DeveloperJournal.hpp @@ -1,9 +1,9 @@ /// @brief Intent journal of the developer store: publishing several files as one all-or-nothing change. #pragma once -#include "WindowsCompat.hpp" #include "DeveloperFiles.hpp" #include "DeveloperPaths.hpp" +#include "WindowsCompat.hpp" #include #include @@ -25,9 +25,9 @@ #include #if !defined(_WIN32) -#include -#include -#include + #include + #include + #include #endif namespace webfront::developer { @@ -48,8 +48,7 @@ struct InjectedFault : std::runtime_error { /// Flushes a file's content to stable storage. inline void syncFile(const std::filesystem::path& file) { #if defined(_WIN32) - HANDLE handle = CreateFileW(file.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE handle = CreateFileW(file.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot open " + file.string() + " for synchronization"); const bool flushed = FlushFileBuffers(handle) != 0; @@ -60,11 +59,11 @@ inline void syncFile(const std::filesystem::path& file) { const int descriptor = ::open(file.c_str(), O_RDONLY); if (descriptor < 0) throw std::runtime_error("Cannot open " + file.string() + " for synchronization"); -#if defined(__APPLE__) && defined(F_FULLFSYNC) + #if defined(__APPLE__) && defined(F_FULLFSYNC) const bool flushed = ::fcntl(descriptor, F_FULLFSYNC) == 0 || ::fsync(descriptor) == 0; -#else + #else const bool flushed = ::fsync(descriptor) == 0; -#endif + #endif ::close(descriptor); if (!flushed) throw std::runtime_error("Cannot synchronize " + file.string()); @@ -82,14 +81,15 @@ inline void syncDirectory(const std::filesystem::path& directory) { /// Creates the missing directories between the project root and `directory`, synchronizing the parent /// of each one it creates: the entry of a new directory is only durable once its parent is. -inline void createDirectoriesDurably(const std::filesystem::path& root, const std::filesystem::path& directory, +inline void createDirectoriesDurably(const std::filesystem::path& root, + const std::filesystem::path& directory, const std::function& sync = syncDirectory) { // The ordinary spellings are compared; each directory takes the extended form once its path is long. auto current = plainPath(root); for (const auto& part : plainPath(directory).lexically_relative(current)) { if (part == ".") continue; - current /= part; + current /= part; const auto path = extendedPath(current); if (!std::filesystem::exists(path)) { std::filesystem::create_directory(path); @@ -106,8 +106,8 @@ class ProjectLock { public: explicit ProjectLock(const std::filesystem::path& file) { #if defined(_WIN32) - handle = CreateFileW(file.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, nullptr); + handle = + CreateFileW(file.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); OVERLAPPED region{}; if (handle == INVALID_HANDLE_VALUE || !LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, ®ion)) { release(); @@ -178,7 +178,9 @@ inline std::optional> parseJournal(const std::string& std::vector entries; for (std::size_t i = 1; i + 1 < lines.size(); i += 2) { const auto& source = lines[i + 1]; - if (source.empty() || !std::ranges::all_of(source, [](unsigned char c) { return std::isdigit(c) != 0; })) + if (source.empty() || !std::ranges::all_of(source, [](unsigned char c) { + return std::isdigit(c) != 0; + })) return std::nullopt; entries.push_back({lines[i], source}); } @@ -194,7 +196,7 @@ inline std::string fingerprint(const std::filesystem::path& root, const std::vec hash = (hash ^ static_cast(data[i])) * 1099511628211ULL; }; for (const auto& path : paths) { - const auto file = projectPath(root, path); + const auto file = projectPath(root, path); std::ifstream stream(file, std::ios::binary); const char present = std::filesystem::is_regular_file(file) && stream ? 1 : 0; feed(&present, 1); @@ -215,10 +217,13 @@ inline std::string fingerprint(const std::filesystem::path& root, const std::vec /// after an interruption, including one of this very function. A source that is gone was already /// renamed: sources are only removed after the journal, and a publication that never reached its /// journal is never rolled forward. -inline void rollForward(const std::filesystem::path& root, const std::filesystem::path& directory, const std::string& number, - const std::vector& entries, const StepHook& hook) { - const auto owned = directory / (number + ".d"); - int done = 0; +inline void rollForward(const std::filesystem::path& root, + const std::filesystem::path& directory, + const std::string& number, + const std::vector& entries, + const StepHook& hook) { + const auto owned = directory / (number + ".d"); + int done = 0; std::set directories{owned}; for (const auto& [target, source] : entries) { const auto staged = owned / source; @@ -247,8 +252,8 @@ inline void rollForward(const std::filesystem::path& root, const std::filesystem /// recovery (the next state() or group publication, or the next opening of the project) completes it. struct IncompletePublication : std::runtime_error { explicit IncompletePublication(const std::string& reason) - : std::runtime_error("A committed publication of the project is not applied yet (" + reason + - "); fix the cause and run the command again to complete it") {} + : std::runtime_error("A committed publication of the project is not applied yet (" + reason + + "); fix the cause and run the command again to complete it") {} }; /// Completes the journals that reached their commit point and abandons the others. A journal is diff --git a/include/webfront/system/DeveloperPaths.hpp b/include/webfront/system/DeveloperPaths.hpp index 6a15fa98..75e4a8a8 100644 --- a/include/webfront/system/DeveloperPaths.hpp +++ b/include/webfront/system/DeveloperPaths.hpp @@ -15,9 +15,18 @@ inline constexpr std::size_t extendedPathThreshold = 200; #ifdef _WIN32 // Spelled with \x5c (a backslash): the prefixes are \?\ and \?\UNC\ for a network share, which is \ in its ordinary form. -inline constexpr std::wstring_view networkPrefix = L"\x5c" L"\x5c"; -inline constexpr std::wstring_view extendedPrefix = L"\x5c" L"\x5c" L"?" L"\x5c"; -inline constexpr std::wstring_view uncPrefix = L"\x5c" L"\x5c" L"?" L"\x5c" L"UNC" L"\x5c"; +inline constexpr std::wstring_view networkPrefix = L"\x5c" + L"\x5c"; +inline constexpr std::wstring_view extendedPrefix = L"\x5c" + L"\x5c" + L"?" + L"\x5c"; +inline constexpr std::wstring_view uncPrefix = L"\x5c" + L"\x5c" + L"?" + L"\x5c" + L"UNC" + L"\x5c"; #endif /// The form of an absolute path that the Windows file APIs accept beyond MAX_PATH; other platforms keep the path as is. diff --git a/include/webfront/system/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index d911d528..71bc47d1 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -1,10 +1,10 @@ /// @brief Explicit development project access and staged publication, without shell access. #pragma once -#include "DeveloperFiles.hpp" -#include "DeveloperJournal.hpp" #include "../utils/Json.hpp" #include "../utils/Sha256.hpp" +#include "DeveloperFiles.hpp" +#include "DeveloperJournal.hpp" #include #include @@ -35,8 +35,7 @@ class Store { /// the previous process stopped and abandons the others. A publication that cannot be completed /// does not prevent opening the project: state() and commitGroup() retry it and report why it fails, /// and recoveryFailure() describes it meanwhile. The hook is for tests only. - explicit Store(std::filesystem::path project, std::chrono::steady_clock::duration abandoned = defaultAbandonedAfter, - StepHook stepHook = {}) + explicit Store(std::filesystem::path project, std::chrono::steady_clock::duration abandoned = defaultAbandonedAfter, StepHook stepHook = {}) : root(canonicalDirectory(project)), abandonedAfter(abandoned), hook(std::move(stepHook)) { if (!std::filesystem::is_directory(root)) throw std::invalid_argument("Developer project must be a directory"); @@ -58,9 +57,9 @@ class Store { } std::vector read(std::string path, std::uint64_t offset) const { - std::scoped_lock lock(mutex); - const auto source = projectPath(root, path); - std::ifstream file = openForReading(source, path, offset); + std::scoped_lock lock(mutex); + const auto source = projectPath(root, path); + std::ifstream file = openForReading(source, path, offset); std::vector bytes(chunkSize); file.read(reinterpret_cast(bytes.data()), static_cast(bytes.size())); if (file.bad()) @@ -127,7 +126,8 @@ class Store { const auto resolved = std::filesystem::weakly_canonical(target); requireFreeDestination(resolved, std::filesystem::weakly_canonical(stagingRoot)); const auto [id, staging] = createStaging(stagingRoot); - transactions.emplace(id, Transaction{staging, target, resolved, std::move(destination), directory, replace, 0, {}, {}, std::chrono::steady_clock::now()}); + transactions.emplace(id, + Transaction{staging, target, resolved, std::move(destination), directory, replace, 0, {}, {}, std::chrono::steady_clock::now()}); return id; } @@ -198,7 +198,7 @@ class Store { /// IncompletePublication and the next state(), commitGroup() or opening of the project completes it. void commitGroup(const std::vector& ids, const std::vector& paths, const std::string& expected) { std::scoped_lock lock(mutex); - const auto directory = projectPath(root, journalDirectory); + const auto directory = projectPath(root, journalDirectory); // Before the commit point: the journal directory must itself survive a power cut. createDirectoriesDurably(root, directory); // From here to the end, no other process recovers, checks the precondition or publishes. @@ -266,20 +266,21 @@ class Store { if (!std::filesystem::is_directory(source, error) || std::filesystem::is_symlink(source, error)) throw std::runtime_error("Cannot list project directory: " + directory); std::vector sorted; - for (std::filesystem::directory_iterator entries(source, error); !error && entries != std::filesystem::directory_iterator{}; - entries.increment(error)) + for (std::filesystem::directory_iterator entries(source, error); !error && entries != std::filesystem::directory_iterator{}; entries.increment(error)) sorted.push_back(*entries); if (error) throw std::runtime_error("Cannot list project directory: " + directory); - std::ranges::sort(sorted, {}, [](const auto& entry) { return entry.path().filename(); }); + std::ranges::sort(sorted, {}, [](const auto& entry) { + return entry.path().filename(); + }); for (const auto& entry : sorted) { const auto name = entry.path().filename().generic_string(); const auto path = directory.empty() ? name : directory + "/" + name; const auto key = json::quote(prefix + name); const auto status = entry.symlink_status(error); if (error || (!std::filesystem::is_regular_file(status) && !std::filesystem::is_directory(status))) { - text += (text.size() > 1 ? "," : "") + key + ":\"" + (std::filesystem::is_symlink(status) ? "link" : "other") + "\""; - error = {}; + text += (text.size() > 1 ? "," : "") + key + ":\"" + (std::filesystem::is_symlink(status) ? "link" : "other") + "\""; + error = {}; continue; } if (std::filesystem::is_directory(status)) { @@ -341,7 +342,7 @@ class Store { std::optional listedName(const std::string& directory, const std::string& name) const { std::error_code error; try { - const auto resolved = projectPath(root, directory.empty() ? name : directory + "/" + name); + const auto resolved = projectPath(root, directory.empty() ? name : directory + "/" + name); const bool isDirectory = std::filesystem::is_directory(resolved, error); if (error && error != std::errc::no_such_file_or_directory) return std::nullopt; @@ -441,7 +442,8 @@ class Store { } // Completes the committed publications, recording why one cannot be completed. - template void recordRecovery(Recovery recovery) { + template + void recordRecovery(Recovery recovery) { try { recovery(root, hook); pendingRecovery.reset(); @@ -463,15 +465,15 @@ class Store { } struct Transaction { - std::filesystem::path staging; - std::filesystem::path target; - std::filesystem::path resolved; - std::string destination; - bool directory; - bool replace; - std::uint64_t size; - std::map files; - std::set folded; + std::filesystem::path staging; + std::filesystem::path target; + std::filesystem::path resolved; + std::string destination; + bool directory; + bool replace; + std::uint64_t size; + std::map files; + std::set folded; std::chrono::steady_clock::time_point lastUse; }; Transaction& transaction(const std::string& id) { @@ -519,7 +521,9 @@ class Store { // Two paths differing only by case are one file on Windows and macOS: refuse them instead of concatenating. static void requireDistinctCase(Transaction& tx, const std::string& key) { std::string lowered = key; - std::ranges::transform(lowered, lowered.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(lowered, lowered.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); if (tx.files.contains(key)) return; if (!tx.folded.insert(lowered).second) @@ -541,12 +545,12 @@ class Store { return relative; } - std::filesystem::path root; - std::chrono::steady_clock::duration abandonedAfter; - StepHook hook; - std::optional pendingRecovery; - mutable std::mutex mutex; - std::map transactions; + std::filesystem::path root; + std::chrono::steady_clock::duration abandonedAfter; + StepHook hook; + std::optional pendingRecovery; + mutable std::mutex mutex; + std::map transactions; }; } // namespace webfront::developer diff --git a/include/webfront/system/FileSystem.hpp b/include/webfront/system/FileSystem.hpp index 9e36b8f2..0a517e15 100644 --- a/include/webfront/system/FileSystem.hpp +++ b/include/webfront/system/FileSystem.hpp @@ -9,8 +9,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -21,19 +21,19 @@ namespace webfront::fs { -template +template concept HasEncoding = requires(T t) { T::encoding; }; -template +template concept IsData = requires(T t) { T::data; T::dataSize; }; -template +template concept EncodedData = IsData && HasEncoding; -template +template concept RawData = IsData; /// @brief The bytes of a file a provider or a storage reads through its own handle: a descriptor opened relative to a @@ -52,25 +52,36 @@ class ByteSource { class File { enum class FileType { nativeFStream, staticData, byteSource }; + public: File(EncodedData auto t) : File(decltype(t)::data, decltype(t)::dataSize, decltype(t)::encoding) {} File(RawData auto t) : File(decltype(t)::data, decltype(t)::dataSize) {} File(std::span input, size_t fileSize, std::string_view contentEncoding = "") - : fileType{FileType::staticData}, data(input), size(fileSize), eofBit(fileSize==0), encoding(contentEncoding) {} - File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} { measureStream(); } + : fileType{FileType::staticData}, data(input), size(fileSize), eofBit(fileSize == 0), encoding(contentEncoding) {} + File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} { + measureStream(); + } /// A file read through a provider's own handle (see ByteSource). explicit File(std::unique_ptr byteSource) : fileType{FileType::byteSource}, source{std::move(byteSource)} { - if (!source) throw std::invalid_argument("A File needs a byte source"); + if (!source) + throw std::invalid_argument("A File needs a byte source"); } - [[nodiscard]] bool isEncoded() const { return !encoding.empty(); } - [[nodiscard]] std::string_view getEncoding() const { return encoding; } - [[nodiscard]] bool eof() const { return eofBit; } + [[nodiscard]] bool isEncoded() const { + return !encoding.empty(); + } + [[nodiscard]] std::string_view getEncoding() const { + return encoding; + } + [[nodiscard]] bool eof() const { + return eofBit; + } /// The number of bytes this file yields, when known before reading it (always for embedded data, and for a /// native file whose stream can seek). A server uses it to announce a length and stream the file in chunks. [[nodiscard]] std::optional knownSize() const { - if (fileType == FileType::byteSource) return source->size(); + if (fileType == FileType::byteSource) + return source->size(); return fileType == FileType::staticData ? std::optional{size} : streamSize; } @@ -79,10 +90,14 @@ class File { /// the opened stream (replacement between the open and the lookup, rewrite that keeps the time). A provider /// whose storage is versioned (a content hash, a revision number) sets it with setEntityTag(); without one, a /// range request conditioned by `If-Range` is answered in full. - [[nodiscard]] const std::optional& entityTag() const { return entityTagValue; } + [[nodiscard]] const std::optional& entityTag() const { + return entityTagValue; + } /// @param tag a quoted tag that changes whenever the bytes this file yields change, such as `"rev-42"`. - void setEntityTag(std::string tag) { entityTagValue = std::move(tag); } + void setEntityTag(std::string tag) { + entityTagValue = std::move(tag); + } /// Positions the next read at `offset` bytes from the start of the content (the position the file had when it /// was built), when knownSize() is set. An offset past the end positions at the end. @@ -97,7 +112,8 @@ class File { eofBit = false; return source->seek(offset); } - if (!streamSize || !fstream.is_open()) return false; + if (!streamSize || !fstream.is_open()) + return false; const auto target = std::min(offset, *streamSize); fstream.clear(); fstream.seekg(streamOrigin + static_cast(target)); @@ -109,26 +125,29 @@ class File { // @param buffer buffer which will receive extracted data // @return bytes read size_t read(std::span buffer) { - if (fileType == FileType::staticData) return readData(buffer); - if (fileType == FileType::byteSource) return readSource(buffer); + if (fileType == FileType::staticData) + return readData(buffer); + if (fileType == FileType::byteSource) + return readSource(buffer); return readFStream(buffer); } private: - FileType fileType; - std::span data; - size_t readIndex{}, size{}; + FileType fileType; + std::span data; + size_t readIndex{}, size{}; std::optional streamSize; - std::streamoff streamOrigin{}; - std::optional entityTagValue; - bool eofBit{false}; - const std::string encoding{}; - std::ifstream fstream; - std::unique_ptr source; + std::streamoff streamOrigin{}; + std::optional entityTagValue; + bool eofBit{false}; + const std::string encoding{}; + std::ifstream fstream; + std::unique_ptr source; size_t readSource(std::span buffer) { const auto count = source->read(buffer); - if (count < buffer.size()) eofBit = true; + if (count < buffer.size()) + eofBit = true; return count; } @@ -148,7 +167,8 @@ class File { // The bytes left from the stream's current position, which the caller may have moved past a prefix. void measureStream() { - if (!fstream.is_open()) return; + if (!fstream.is_open()) + return; const auto start = fstream.tellg(); fstream.seekg(0, std::ios::end); const auto end = fstream.tellg(); @@ -156,25 +176,26 @@ class File { if (start >= 0 && end >= start && fstream) { streamSize = static_cast(end - start); streamOrigin = static_cast(start); - } - else fstream.clear(); + } else + fstream.clear(); } size_t readFStream(std::span buffer) { fstream.read(buffer.data(), static_cast(buffer.size())); // The stream stays open at the end of the file, so that seek() can position it again. - if (fstream.eof()) eofBit = true; + if (fstream.eof()) + eofBit = true; return static_cast(fstream.gcount()); } }; -template +template concept Provider = requires(T t, std::filesystem::path filename) { { t.open(filename) } -> std::same_as>; requires std::constructible_from; }; -template +template class Multi : FSs... { public: Multi(std::filesystem::path docRoot) : FSs(docRoot)... {} @@ -183,15 +204,17 @@ class Multi : FSs... { } private: - template + template std::optional openFile(std::filesystem::path filename) { auto file = this->First::open(filename); - if constexpr (sizeof...(Rest) == 0) return file; + if constexpr (sizeof...(Rest) == 0) + return file; else { - if (file.has_value()) return file; + if (file.has_value()) + return file; return openFile(filename); } } }; -} // namespace webfront::fs +} // namespace webfront::fs diff --git a/include/webfront/system/FontStacks.hpp b/include/webfront/system/FontStacks.hpp index d2385b2f..884a0953 100644 --- a/include/webfront/system/FontStacks.hpp +++ b/include/webfront/system/FontStacks.hpp @@ -36,7 +36,9 @@ namespace detail { inline std::string lower(std::string_view text) { std::string result(text); - std::ranges::transform(result, result.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(result, result.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); return result; } @@ -133,10 +135,10 @@ inline bool wordAt(std::string_view text, std::size_t at, std::string_view word) /// the value of `content`) are not declarations; the property name is read whatever its case. A declaration whose value /// uses `var()` or `inherit` is not analysed. Pure and total: any text is accepted. inline std::vector longStacks(std::string_view css) { - const auto clean = detail::withoutComments(css); - std::vector found; + const auto clean = detail::withoutComments(css); + std::vector found; constexpr std::string_view property = "font-family"; - char quote = 0; + char quote = 0; for (std::size_t at = 0; at < clean.size(); ++at) { const char c = clean[at]; if (quote) { @@ -160,7 +162,7 @@ inline std::vector longStacks(std::string_view css) { if (colon >= clean.size() || clean[colon] != ':') continue; // The value ends at the first `;` or `}` outside quotes. - std::size_t end = colon + 1; + std::size_t end = colon + 1; char valueQuote = 0; for (; end < clean.size(); ++end) { const char v = clean[end]; @@ -175,8 +177,8 @@ inline std::vector longStacks(std::string_view css) { break; } } - end = std::min(end, clean.size()); - at = end; // resume after the declaration (the loop increments past the terminator) + end = std::min(end, clean.size()); + at = end; // resume after the declaration (the loop increments past the terminator) const auto value = std::string(detail::trim(std::string_view(clean).substr(colon + 1, end - colon - 1))); if (value.find("var(") != std::string::npos || detail::lower(value) == "inherit") continue; @@ -196,9 +198,9 @@ inline std::ostream* warningOutput = nullptr; /// The version of a stylesheet file: its size and its last write time, compared as they are (no conversion of the file /// clock's representation, which differs between standard libraries). struct Stamp { - std::uintmax_t size = 0; + std::uintmax_t size = 0; std::filesystem::file_time_type written{}; - friend bool operator==(const Stamp&, const Stamp&) = default; + friend bool operator==(const Stamp&, const Stamp&) = default; }; namespace detail { @@ -234,7 +236,7 @@ inline std::size_t warnLongStacks(const std::string& name, std::string_view css, entry->second = stamp; } } - const auto stacks = longStacks(css); + const auto stacks = longStacks(css); std::scoped_lock lock{detail::seenMutex()}; auto& out = warningOutput ? *warningOutput : std::cerr; for (const auto& stack : stacks) diff --git a/include/webfront/system/IndexFS.hpp b/include/webfront/system/IndexFS.hpp index d65dede5..4106d1dd 100644 --- a/include/webfront/system/IndexFS.hpp +++ b/include/webfront/system/IndexFS.hpp @@ -17,13 +17,13 @@ namespace webfront::fs { class IndexFS { public: IndexFS(std::filesystem::path /*docRoot*/) {} - IndexFS() = delete; - IndexFS(const IndexFS&) = default; - IndexFS(IndexFS&&) = default; + IndexFS() = delete; + IndexFS(const IndexFS&) = default; + IndexFS(IndexFS&&) = default; IndexFS& operator=(const IndexFS&) = default; - IndexFS& operator=(IndexFS&&) = default; + IndexFS& operator=(IndexFS&&) = default; - using IndexHtml = generated::FallbackIndexHtmlData; + using IndexHtml = generated::FallbackIndexHtmlData; using FallbackModule = generated::FallbackModuleData; using WebFrontIco = generated::FaviconData; @@ -32,13 +32,18 @@ class IndexFS { static std::optional open(std::filesystem::path file) { auto filename = file.relative_path().string(); - if (filename == "index.html") return File(IndexHtml{}); - if (filename == "favicon.ico") return File{WebFrontIco{}}; - if (filename == "webfront-dom.mjs") return File{generated::DomInterpreterData{}}; - if (filename == "WebFront.js") return File{WebFrontJs{}}; - if (filename == "webfront-fallback.mjs") return File{FallbackModule{}}; + if (filename == "index.html") + return File(IndexHtml{}); + if (filename == "favicon.ico") + return File{WebFrontIco{}}; + if (filename == "webfront-dom.mjs") + return File{generated::DomInterpreterData{}}; + if (filename == "WebFront.js") + return File{WebFrontJs{}}; + if (filename == "webfront-fallback.mjs") + return File{FallbackModule{}}; return {}; } }; -} // namespace webfront::fs +} // namespace webfront::fs diff --git a/include/webfront/system/MemoryStorage.hpp b/include/webfront/system/MemoryStorage.hpp index e6506b51..085614f9 100644 --- a/include/webfront/system/MemoryStorage.hpp +++ b/include/webfront/system/MemoryStorage.hpp @@ -41,7 +41,7 @@ class MemoryStorage { // The bytes a File reads: shared with the node, so a later replacement does not change an opened file. class Content : public ByteSource { public: - explicit Content(std::shared_ptr shared) : bytes(std::move(shared)) { } + explicit Content(std::shared_ptr shared) : bytes(std::move(shared)) {} std::size_t read(std::span buffer) override { const auto count = std::min(buffer.size(), bytes->size() - position); std::copy_n(bytes->data() + position, count, buffer.data()); @@ -62,7 +62,7 @@ class MemoryStorage { }; public: - MemoryStorage() : state(std::make_shared()) { } + MemoryStorage() : state(std::make_shared()) {} /// A write in progress, buffered in memory until commit(). class Writer { @@ -97,7 +97,7 @@ class MemoryStorage { private: friend class MemoryStorage; Writer(std::shared_ptr storageState, std::vector path, WriteMode writeMode) - : state(std::move(storageState)), components(std::move(path)), mode(writeMode) { } + : state(std::move(storageState)), components(std::move(path)), mode(writeMode) {} std::shared_ptr state; std::vector components; diff --git a/include/webfront/system/NativeFS.hpp b/include/webfront/system/NativeFS.hpp index 55b01787..4564e338 100644 --- a/include/webfront/system/NativeFS.hpp +++ b/include/webfront/system/NativeFS.hpp @@ -5,6 +5,7 @@ #include "FileSystem.hpp" #include "FontStacks.hpp" + #include #include @@ -17,13 +18,15 @@ class NativeRawFS { std::optional open(std::filesystem::path path) { std::ifstream file; file.open(rootPath / path, std::ios::binary); - if (file.is_open()) return File{std::move(file)}; + if (file.is_open()) + return File{std::move(file)}; return {}; } + protected: std::filesystem::path rootPath; }; -} // namespace detail +} // namespace detail /// @brief Native file system for debugging purposes. class NativeDebugFS : public detail::NativeRawFS { @@ -66,4 +69,4 @@ class NativeDebugFS : public detail::NativeRawFS { } }; -} // namespace webfront::fs +} // namespace webfront::fs diff --git a/include/webfront/system/NativeStorage.hpp b/include/webfront/system/NativeStorage.hpp index 98a42e85..8f7cc15b 100644 --- a/include/webfront/system/NativeStorage.hpp +++ b/include/webfront/system/NativeStorage.hpp @@ -185,8 +185,8 @@ inline constexpr int searchFlags = O_RDONLY | O_DIRECTORY; class Fd { public: Fd() = default; - explicit Fd(int value) : descriptor(value) { } - Fd(Fd&& other) noexcept : descriptor(std::exchange(other.descriptor, -1)) { } + explicit Fd(int value) : descriptor(value) {} + Fd(Fd&& other) noexcept : descriptor(std::exchange(other.descriptor, -1)) {} Fd& operator=(Fd&& other) noexcept { if (this != &other) { reset(); @@ -490,7 +490,7 @@ inline void clearAccessControl(int file, const std::string& what) { // The content of a file opened relative to a directory of the root. class FdSource : public ByteSource { public: - FdSource(Fd opened, std::uint64_t length) : file(std::move(opened)), total(length) { } + FdSource(Fd opened, std::uint64_t length) : file(std::move(opened)), total(length) {} std::size_t read(std::span buffer) override { std::size_t count = 0; @@ -844,7 +844,7 @@ class NativeStorage::Writer { private: friend class NativeStorage; Writer(std::shared_ptr storageState, State::Walk opened, std::vector path, std::string finalName, WriteMode writeMode) - : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) { } + : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) {} // Gives the temporary file the group, the permission bits (never setuid, setgid nor sticky) and the ACL of the file it replaces, // read now, under the lock that serializes the storage's operations: whatever the storage moved to that name since @@ -1036,9 +1036,9 @@ inline NativeStorage::Writer NativeStorage::beginWrite(std::string_view path, Wr for (int attempt = 0; !writer.file; ++attempt) { writer.temporary = detail::temporaryName(); writer.file = detail::posix::openAt(writer.fileDirectory(), - writer.temporary.c_str(), - O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, - mode == WriteMode::replace ? 0600 : 0644); + writer.temporary.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, + mode == WriteMode::replace ? 0600 : 0644); if (!writer.file && (errno != EEXIST || attempt == 8)) detail::posix::fail(errno, "Cannot write " + detail::quoted(writer.components)); } @@ -1129,8 +1129,8 @@ inline constexpr NTSTATUS statusDirectoryNotEmpty = static_cast(0xC0 class Handle { public: Handle() = default; - explicit Handle(HANDLE value) : handle(value == INVALID_HANDLE_VALUE ? nullptr : value) { } - Handle(Handle&& other) noexcept : handle(std::exchange(other.handle, nullptr)) { } + explicit Handle(HANDLE value) : handle(value == INVALID_HANDLE_VALUE ? nullptr : value) {} + Handle(Handle&& other) noexcept : handle(std::exchange(other.handle, nullptr)) {} Handle& operator=(Handle&& other) noexcept { if (this != &other) { reset(); @@ -1283,16 +1283,16 @@ inline NTSTATUS openRelative(Handle& result, HANDLE parent, const std::wstring& IO_STATUS_BLOCK io{}; HANDLE handle = nullptr; const auto status = Ntdll::get().createFile(&handle, - access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, - &attributes, - &io, - nullptr, - FILE_ATTRIBUTE_NORMAL, - share, - disposition, - options | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT, - nullptr, - 0); + access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, + &attributes, + &io, + nullptr, + FILE_ATTRIBUTE_NORMAL, + share, + disposition, + options | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT, + nullptr, + 0); if (status >= 0) result = Handle{handle}; return status; @@ -1383,7 +1383,7 @@ inline std::wstring finalPath(HANDLE handle) { // The content of a file opened relative to a directory of the root. class HandleSource : public ByteSource { public: - HandleSource(Handle opened, std::uint64_t length) : file(std::move(opened)), total(length) { } + HandleSource(Handle opened, std::uint64_t length) : file(std::move(opened)), total(length) {} std::size_t read(std::span buffer) override { std::size_t count = 0; @@ -1692,7 +1692,7 @@ class NativeStorage::Writer { private: friend class NativeStorage; Writer(std::shared_ptr storageState, State::Walk opened, std::vector path, std::string finalName, WriteMode writeMode) - : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) { } + : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) {} void abandon() noexcept { if (!file) @@ -1836,12 +1836,12 @@ inline void NativeStorage::createDirectory(std::string_view path) { state->notify(StoragePoint::resolved, name); detail::windows::Handle directory; const auto status = detail::windows::openRelative(directory, - walk.top(), - detail::windows::wide(name), - detail::windows::directoryAccess, - detail::windows::fullSharing, - FILE_CREATE, - FILE_DIRECTORY_FILE); + walk.top(), + detail::windows::wide(name), + detail::windows::directoryAccess, + detail::windows::fullSharing, + FILE_CREATE, + FILE_DIRECTORY_FILE); if (status < 0) detail::windows::failStatus(status, "Cannot create " + detail::quoted(components)); directory.reset(); diff --git a/include/webfront/system/Storage.hpp b/include/webfront/system/Storage.hpp index c7f48e41..7bdbb891 100644 --- a/include/webfront/system/Storage.hpp +++ b/include/webfront/system/Storage.hpp @@ -80,7 +80,7 @@ enum class StorageErrc { */ class StorageError : public BridgeError { public: - StorageError(StorageErrc errc, const std::string& message) : BridgeError(std::string(storageErrorCode(errc)), message), errcValue(errc) { } + StorageError(StorageErrc errc, const std::string& message) : BridgeError(std::string(storageErrorCode(errc)), message), errcValue(errc) {} [[nodiscard]] StorageErrc errc() const noexcept { return errcValue; diff --git a/include/webfront/system/WindowsCompat.hpp b/include/webfront/system/WindowsCompat.hpp index a52ca13e..c154d0db 100644 --- a/include/webfront/system/WindowsCompat.hpp +++ b/include/webfront/system/WindowsCompat.hpp @@ -5,31 +5,31 @@ #ifdef _WIN32 -// Prevent Windows min/max macros from interfering with std::min/max -#ifndef NOMINMAX -#define NOMINMAX -#endif - -// Reduce Windows header bloat and compilation time -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -// Define required macros to prevent header conflicts -#ifndef STRICT -#define STRICT -#endif - -#ifndef _WINSOCKAPI_ -#define _WINSOCKAPI_ -#endif - -// Ensure WinSock2.h is included before any headers that might include WinSock.h -// This prevents conflicts between WinSock and WinSock2 definitions -#include -#include - -// Common Windows headers that benefit from the above macros -#include - -#endif // _WIN32 \ No newline at end of file + // Prevent Windows min/max macros from interfering with std::min/max + #ifndef NOMINMAX + #define NOMINMAX + #endif + + // Reduce Windows header bloat and compilation time + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + + // Define required macros to prevent header conflicts + #ifndef STRICT + #define STRICT + #endif + + #ifndef _WINSOCKAPI_ + #define _WINSOCKAPI_ + #endif + + // Ensure WinSock2.h is included before any headers that might include WinSock.h + // This prevents conflicts between WinSock and WinSock2 definitions + #include + #include + + // Common Windows headers that benefit from the above macros + #include + +#endif // _WIN32 \ No newline at end of file diff --git a/include/webfront/testing/Bdd.hpp b/include/webfront/testing/Bdd.hpp index bcaae886..2ee8ed49 100644 --- a/include/webfront/testing/Bdd.hpp +++ b/include/webfront/testing/Bdd.hpp @@ -47,11 +47,11 @@ namespace webfront::bdd { /// Thrown by a fatal failure. It does not derive from std::exception, so the `catch (const std::exception&)` of a test does /// not swallow it. -struct AssertionFailure { }; +struct AssertionFailure {}; /// Thrown by skip(). -struct Skipped { }; +struct Skipped {}; /// The type requireThrows() accepts when it is not given one: any exception. -struct AnyException { }; +struct AnyException {}; /// A predicate on a string with a description of what it expects. template @@ -333,7 +333,7 @@ struct Body { Body() = default; template requires(std::invocable && !std::same_as, Body>) - Body(F&& callable) : object{const_cast(static_cast(std::addressof(callable)))}, call{&invoke>} { } + Body(F&& callable) : object{const_cast(static_cast(std::addressof(callable)))}, call{&invoke>} {} void operator()() const { call(object); } @@ -396,7 +396,7 @@ struct NamePart { std::source_location location; template requires std::convertible_to - NamePart(const T& part, std::source_location where = std::source_location::current()) : text{part}, location{where} { } + NamePart(const T& part, std::source_location where = std::source_location::current()) : text{part}, location{where} {} }; /// A section whose name is made of several parts: given("q=", value, [&] { ... }). @@ -429,7 +429,7 @@ concept ComposedSection = sizeof...(Args) >= 2 && std::invocable F> - Scenario(std::string_view title, F body, std::source_location location = std::source_location::current()) : Scenario(title, {}, body, location) { } + Scenario(std::string_view title, F body, std::source_location location = std::source_location::current()) : Scenario(title, {}, body, location) {} template F> Scenario(std::string_view title, std::initializer_list tags, F body, std::source_location location = std::source_location::current()) { @@ -656,7 +656,7 @@ struct Condition { explicit Condition(F& predicate) : object{std::addressof(predicate)}, call{[](void* target) { return static_cast((*static_cast(target))()); - }} { } + }} {} bool operator()() const { return call(object); } @@ -850,7 +850,7 @@ struct Located { std::source_location location; template requires std::convertible_to - Located(const T& message, std::source_location where = std::source_location::current()) : text{message}, location{where} { } + Located(const T& message, std::source_location where = std::source_location::current()) : text{message}, location{where} {} }; /// Records a failure and goes on; the message is the concatenation of the arguments. diff --git a/include/webfront/testing/Process.hpp b/include/webfront/testing/Process.hpp index 13cbffda..a16ac0ef 100644 --- a/include/webfront/testing/Process.hpp +++ b/include/webfront/testing/Process.hpp @@ -17,12 +17,12 @@ #include #ifdef _WIN32 + #include "../system/WindowsArguments.hpp" #include "../system/WindowsCompat.hpp" #include #include - #include "../system/WindowsArguments.hpp" #else #include #include diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 1d2a6746..62e7abbd 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -3,13 +3,14 @@ #include "../networking/TCPNetworkingStdnet.hpp" #include "Credentials.hpp" #include "detail/Protocol.hpp" + #include #ifdef _MSC_VER -// C4737: MSVC cannot always turn the awaits of the handshake coroutines into tail calls. It costs stack depth, not correctness, -// and /WX would otherwise break every consumer of this header. -#pragma warning(push) -#pragma warning(disable : 4737) + // C4737: MSVC cannot always turn the awaits of the handshake coroutines into tail calls. It costs stack depth, not correctness, + // and /WX would otherwise break every consumer of this header. + #pragma warning(push) + #pragma warning(disable : 4737) #endif namespace webfront::tls { @@ -72,7 +73,9 @@ class Server : public networking::TCPStdnet { ++acceptor.pendingHandshakes; struct Slot { std::size_t& pending; - ~Slot() { --pending; } + ~Slot() { + --pending; + } } slot{acceptor.pendingHandshakes}; co_await runHandshake(socket, acceptor); } @@ -314,26 +317,25 @@ class Server : public networking::TCPStdnet { } #ifdef _MSC_VER -// MSVC reports C4737 as an error from its optimizer. The handshake stages run once per connection: build them unoptimized, -// and keep the data path (Receive, Send) optimized. -#pragma optimize("", off) + // MSVC reports C4737 as an error from its optimizer. The handshake stages run once per connection: build them unoptimized, + // and keep the data path (Receive, Send) optimized. + #pragma optimize("", off) #endif // MSVC refuses (C4737) one coroutine holding the whole flight, so the handshake runs in three stages. static Task negotiate(Socket& socket, std::shared_ptr identity) { using namespace detail; - Sha256 transcript; - Bytes message; - ClientHello hello; - Secret<> shared{}, clientHandshake{}; - Digest afterFinished{}; + Sha256 transcript; + Bytes message; + ClientHello hello; + Secret<> shared{}, clientHandshake{}; + Digest afterFinished{}; co_await receiveHello(socket, transcript, message, hello, shared); co_await sendFlight(socket, transcript, *identity, hello.alpn, shared, clientHandshake, afterFinished); co_await receiveFinished(socket, clientHandshake, afterFinished); } // From the first ClientHello to the ServerHello, including a HelloRetryRequest. Fills the X25519 shared secret. - static Task receiveHello(Socket& socket, detail::Sha256& transcript, detail::Bytes& message, detail::ClientHello& hello, - detail::Secret<>& shared) { + static Task receiveHello(Socket& socket, detail::Sha256& transcript, detail::Bytes& message, detail::ClientHello& hello, detail::Secret<>& shared) { using namespace detail; auto& state = *socket.connection; message = co_await readHandshake(socket, 65536, false, true); @@ -403,8 +405,13 @@ class Server : public networking::TCPStdnet { } // EncryptedExtensions to server Finished, then the application keys. - static Task sendFlight(Socket& socket, detail::Sha256& transcript, const detail::Identity& identity, bool alpn, const detail::Secret<>& shared, - detail::Secret<>& client, detail::Digest& afterFinished) { + static Task sendFlight(Socket& socket, + detail::Sha256& transcript, + const detail::Identity& identity, + bool alpn, + const detail::Secret<>& shared, + detail::Secret<>& client, + detail::Digest& afterFinished) { using namespace detail; auto& state = *socket.connection; const auto empty = hash(); @@ -449,11 +456,11 @@ class Server : public networking::TCPStdnet { state.established = true; } #ifdef _MSC_VER -#pragma optimize("", on) + #pragma optimize("", on) #endif }; } // namespace webfront::tls #ifdef _MSC_VER -#pragma warning(pop) + #pragma warning(pop) #endif diff --git a/include/webfront/tooling/HexDump.hpp b/include/webfront/tooling/HexDump.hpp index b6734178..014ac501 100644 --- a/include/webfront/tooling/HexDump.hpp +++ b/include/webfront/tooling/HexDump.hpp @@ -15,44 +15,47 @@ namespace webfront::utils { -template +template concept Buffer = std::movable || requires(T t) { t.data(); t.size(); }; /// Provides an hexadecimal dump of a container or a buffer -template +template struct HexDump { HexDump(const BufferType& buf, size_t startAddr = 0) : buffer(buf), startAddress(startAddr) {} const BufferType& buffer; - size_t startAddress; + size_t startAddress; }; -template +template std::ostream& operator<<(std::ostream& os, const HexDump& h) { using namespace std; - size_t address = 0; - const auto buffer = - span(reinterpret_cast(h.buffer.data()), h.buffer.size() * sizeof(typename pointer_traits::element_type)); - auto iosFlags{os.flags()}; + size_t address = 0; + const auto buffer = span(reinterpret_cast(h.buffer.data()), + h.buffer.size() * sizeof(typename pointer_traits::element_type)); + auto iosFlags{os.flags()}; os << hex << setfill('0'); while (address < buffer.size()) { os << setw(8) << address + h.startAddress; for (auto index = address; index < address + 16; ++index) { - if (index % 8 == 0) os << ' '; + if (index % 8 == 0) + os << ' '; if (index < buffer.size()) os << ' ' << setw(2) << +buffer[index]; -// os << ", 0x" << setw(2) << +buffer[index]; + // os << ", 0x" << setw(2) << +buffer[index]; else os << " "; } os << ' '; for (auto index = address; index < address + 16; ++index) - if (index < buffer.size()) os << (static_cast(buffer[index]) < 32 ? '.' : index < buffer.size() ? static_cast(buffer[index]) : '.'); + if (index < buffer.size()) + os << (static_cast(buffer[index]) < 32 ? '.' : index < buffer.size() ? static_cast(buffer[index]) : '.'); address += 16; - if (address < buffer.size()) os << '\n'; + if (address < buffer.size()) + os << '\n'; } os.flags(iosFlags); @@ -90,4 +93,4 @@ std::ostream& operator<<(std::ostream& os, const HexDump& h) { return ss.str(); } -} // namespace webfront::utils +} // namespace webfront::utils diff --git a/include/webfront/tooling/Logger.hpp b/include/webfront/tooling/Logger.hpp index c7a4ec8a..71f1b939 100644 --- a/include/webfront/tooling/Logger.hpp +++ b/include/webfront/tooling/Logger.hpp @@ -4,39 +4,41 @@ #pragma once #if defined(WEBFRONT_USE_MDDLOG) && WEBFRONT_USE_MDDLOG -#include "MddlogLogger.hpp" // IWYU pragma: export + #include "MddlogLogger.hpp" // IWYU pragma: export #else -#include "../details/C++20Support.hpp" // Provides and -#include "HexDump.hpp" + #include "../details/C++20Support.hpp" // Provides and + #include "HexDump.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include namespace webfront::log { -using LogType = const uint8_t; +using LogType = const uint8_t; constinit LogType Disabled = 0, Error = 1, Warn = 2, Info = 3, Debug = 4; -const auto clogSink = [](std::string_view t) { std::clog << t << "\n"; }; +const auto clogSink = [](std::string_view t) { + std::clog << t << "\n"; +}; inline std::array, Debug + 1> logTypeEnabled{}; /// Identifies one registered sink. A slot is reused once its sink is gone, so the generation makes a stale id harmless: /// removing it again can never reach the sink that took the slot over. struct SinkId { - std::size_t index = std::numeric_limits::max(); - std::size_t generation = 0; + std::size_t index = std::numeric_limits::max(); + std::size_t generation = 0; friend bool operator==(const SinkId&, const SinkId&) = default; }; inline struct Sinks { @@ -99,7 +101,7 @@ inline struct Sinks { // Contract: never remove a sink while holding a lock that the sink's callback takes (the removal would wait for a // callback that waits for that lock). WebLink removes its transport after releasing transportMutex. struct Entry : std::enable_shared_from_this { - explicit Entry(std::function function) : callback(std::move(function)) { } + explicit Entry(std::function function) : callback(std::move(function)) {} void invoke(std::string_view line) { { const std::lock_guard lock(mutex); @@ -111,7 +113,7 @@ inline struct Sinks { Entry& entry; ~Exit() { std::function released; // destroyed after the lock is dropped - const std::lock_guard lock(entry.mutex); + const std::lock_guard lock(entry.mutex); entry.runners.erase(std::find(entry.runners.begin(), entry.runners.end(), std::this_thread::get_id())); entry.idle.notify_all(); released = entry.takeCallbackIfQuiet(); @@ -120,7 +122,7 @@ inline struct Sinks { callback(line); } void retire() { - const auto self = std::this_thread::get_id(); + const auto self = std::this_thread::get_id(); std::function released; // destroyed after the lock is dropped { const std::lock_guard lock(mutex); @@ -130,7 +132,12 @@ inline struct Sinks { // This thread's own deliveries of the sink (it removes itself) cannot end before this call returns. WaitRegistry::Waiting waiting{self, this->weak_from_this()}; std::unique_lock lock(mutex); - while (std::count_if(runners.begin(), runners.end(), [&](auto id) { return id != self; }) != 0) { + while (std::count_if(runners.begin(), + runners.end(), + [&](auto id) { + return id != self; + }) + != 0) { lock.unlock(); const bool cycle = WaitRegistry::wouldWaitForever(self, *this); lock.lock(); @@ -152,18 +159,18 @@ inline struct Sinks { return !alive && runners.empty(); } std::vector runnersOtherThan(std::thread::id self) { - const std::lock_guard lock(mutex); + const std::lock_guard lock(mutex); std::vector others; for (const auto id : runners) if (id != self) others.push_back(id); return others; } - std::mutex mutex; - std::condition_variable idle; - bool alive = true; - std::vector runners; // one item per callback running now - std::function callback; + std::mutex mutex; + std::condition_variable idle; + bool alive = true; + std::vector runners; // one item per callback running now + std::function callback; }; // Which sink each thread is waiting to see finish. A removal that would wait for a thread that is itself (directly or // through others) waiting for a callback of the remover is a deadlock, and gives up instead. @@ -217,7 +224,7 @@ inline struct Sinks { }; SinkId addOne(auto&& callback) { const std::lock_guard lock(mutex); - auto entry = std::make_shared(std::forward(callback)); + auto entry = std::make_shared(std::forward(callback)); // A slot is free once its sink was removed and no thread still runs the callback; a bounded table keeps the // snapshot and the search proportional to the sinks alive, not to every sink ever added. std::size_t index = 0; @@ -225,8 +232,8 @@ inline struct Sinks { ++index; if (index == slots.size()) slots.emplace_back(); - slots[index].entry = std::move(entry); - slots[index].retired = nullptr; + slots[index].entry = std::move(entry); + slots[index].retired = nullptr; const auto generation = ++slots[index].generation; publish(); return {index, generation}; @@ -247,63 +254,118 @@ inline struct Sinks { // NOTE : functions below are defined inline static in order to avoir clang "uneeded function" and "unused function" errors namespace { - using namespace std; - using srcLoc = source_location; - - constexpr auto toChar(LogType l) { return l == Debug ? 'D' : l == Warn ? 'W' : l == Error ? 'E' : 'I'; } - inline static void log(LogType l, string_view text) { out(format("[{}] {:%T} | {}", toChar(l), chrono::system_clock::now(), text));} - inline static void log(LogType l, string_view text, const srcLoc& s) { - out(format("[{}] {:%T} | {:16}:{:4} | {}", toChar(l), chrono::system_clock::now(), filesystem::path(s.file_name()).filename().string(), s.line(), text)); - } - template static void log(LogType l, string_view fmt, Ts&&... ts) { -#ifdef __cpp_lib_format - log(l, vformat(fmt, make_format_args(ts...))); -#else - log(l, format(fmt, std::forward(ts)...)); -#endif - } - template static void log(LogType l, string_view fmt, const srcLoc& s, Ts&&... ts) { -#if __cpp_lib_format - log(l, vformat(fmt, make_format_args(ts...)), s); -#else - log(l, format(fmt, std::forward(ts)...), s); -#endif - } +using namespace std; +using srcLoc = source_location; - inline static void set(LogType logType, bool enabled) { logTypeEnabled[logType].store(enabled, std::memory_order_relaxed); } - inline static bool is(LogType logType) { return logTypeEnabled[logType].load(std::memory_order_relaxed); } - inline static void setLogLevel(LogType l) { set(Error, l >= Error); set(Warn, l >= Warn); set(Info, l >= Info); set(Debug, l >= Debug);} +constexpr auto toChar(LogType l) { + return l == Debug ? 'D' : l == Warn ? 'W' : l == Error ? 'E' : 'I'; +} +inline static void log(LogType l, string_view text) { + out(format("[{}] {:%T} | {}", toChar(l), chrono::system_clock::now(), text)); +} +inline static void log(LogType l, string_view text, const srcLoc& s) { + out(format("[{}] {:%T} | {:16}:{:4} | {}", toChar(l), chrono::system_clock::now(), filesystem::path(s.file_name()).filename().string(), s.line(), text)); +} +template +static void log(LogType l, string_view fmt, Ts&&... ts) { + #ifdef __cpp_lib_format + log(l, vformat(fmt, make_format_args(ts...))); + #else + log(l, format(fmt, std::forward(ts)...)); + #endif +} +template +static void log(LogType l, string_view fmt, const srcLoc& s, Ts&&... ts) { + #if __cpp_lib_format + log(l, vformat(fmt, make_format_args(ts...)), s); + #else + log(l, format(fmt, std::forward(ts)...), s); + #endif } -template struct debug { debug(string_view fmt, Ts&&... ts, const srcLoc& l = srcLoc::current()) { - if (is(Debug)) log(Debug, fmt, l, std::forward(ts)...); +inline static void set(LogType logType, bool enabled) { + logTypeEnabled[logType].store(enabled, std::memory_order_relaxed); +} +inline static bool is(LogType logType) { + return logTypeEnabled[logType].load(std::memory_order_relaxed); +} +inline static void setLogLevel(LogType l) { + set(Error, l >= Error); + set(Warn, l >= Warn); + set(Info, l >= Info); + set(Debug, l >= Debug); +} +} // namespace + +template +struct debug { + debug(string_view fmt, Ts&&... ts, const srcLoc& l = srcLoc::current()) { + if (is(Debug)) + log(Debug, fmt, l, std::forward(ts)...); } }; -template debug(string_view, Ts&&...) -> debug; -template void error(string_view fmt, Ts&&... ts) { if (is(Error)) log(Error, fmt, std::forward(ts)...); } -template void warn(string_view fmt, Ts&&... ts) { if (is(Warn)) log(Warn, fmt, std::forward(ts)...); } -template void info(string_view fmt, Ts&&... ts) { if (is(Info)) log(Info, fmt, std::forward(ts)...); } -void infoHex(string_view text, auto container) { if (is(Info)) { log(Info, text); out(utils::hexDump(container)); }} -auto addSinks(auto&&... ts) { return out.add(std::forward(ts)...); } -void removeSinks(auto&&... sinkIds) { (out.remove(sinkIds), ...); } +template +debug(string_view, Ts&&...) -> debug; +template +void error(string_view fmt, Ts&&... ts) { + if (is(Error)) + log(Error, fmt, std::forward(ts)...); +} +template +void warn(string_view fmt, Ts&&... ts) { + if (is(Warn)) + log(Warn, fmt, std::forward(ts)...); +} +template +void info(string_view fmt, Ts&&... ts) { + if (is(Info)) + log(Info, fmt, std::forward(ts)...); +} +void infoHex(string_view text, auto container) { + if (is(Info)) { + log(Info, text); + out(utils::hexDump(container)); + } +} +auto addSinks(auto&&... ts) { + return out.add(std::forward(ts)...); +} +void removeSinks(auto&&... sinkIds) { + (out.remove(sinkIds), ...); +} // Without mddlog no context is captured; the scope keeps call sites identical in both builds. enum class CallDirection : uint8_t { None, CppToJs, JsToCpp }; -struct Context { string_view component; string_view webLinkId; CallDirection direction = CallDirection::None; string_view callId; }; +struct Context { + string_view component; + string_view webLinkId; + CallDirection direction = CallDirection::None; + string_view callId; +}; struct ContextScope { explicit ContextScope(Context) noexcept {} - ContextScope(const ContextScope&) = delete; + ContextScope(const ContextScope&) = delete; ContextScope& operator=(const ContextScope&) = delete; }; // Without mddlog a transport is a synchronous text sink: records carry only the rendered line. -struct TransportRecord { string_view text; }; -struct TransportHandle { SinkId id; }; +struct TransportRecord { + string_view text; +}; +struct TransportHandle { + SinkId id; +}; inline TransportHandle addTransport(function write) { - return {addSinks([write = std::move(write)](string_view t) { write(TransportRecord{t}); })}; + return {addSinks([write = std::move(write)](string_view t) { + write(TransportRecord{t}); + })}; +} +inline void removeTransport(TransportHandle handle) { + out.remove(handle.id); +} +inline void reportTransportFailure(TransportHandle handle) { + removeTransport(handle); } -inline void removeTransport(TransportHandle handle) { out.remove(handle.id); } -inline void reportTransportFailure(TransportHandle handle) { removeTransport(handle); } inline void reportTransportOverflow() noexcept {} -} //namespace webfront::log +} // namespace webfront::log #endif diff --git a/include/webfront/tooling/PathUtils.hpp b/include/webfront/tooling/PathUtils.hpp index 7f910fd2..4755669a 100644 --- a/include/webfront/tooling/PathUtils.hpp +++ b/include/webfront/tooling/PathUtils.hpp @@ -1,7 +1,7 @@ /** * @file PathUtils.hpp * @brief Header-only utilities for path resolution and file discovery - * + * * This header-only library provides utilities for finding files in various * search paths, particularly useful for locating resource files in development * and testing contexts. @@ -10,30 +10,28 @@ #pragma once #include + #include +#include #include #include -#include namespace webfront::tooling { /** * @brief Find a file in a list of search paths relative to the WebFront project root - * + * * Search strategy: * 1. Current working directory * 2. System temp directory * 3. WebFront project subdirectories (configurable) - * + * * @param filename Name of the file to find * @param searchPaths List of subdirectories to search within WebFront project * @return std::filesystem::path Path to the directory containing the file * @throws std::runtime_error If file cannot be found in any location */ -inline std::filesystem::path findFileInPaths( - const std::string& filename, - const std::vector& searchPaths = {"src", "webtest"} -) { +inline std::filesystem::path findFileInPaths(const std::string& filename, const std::vector& searchPaths = {"src", "webtest"}) { using namespace std::filesystem; // 1. Check current directory @@ -49,20 +47,20 @@ inline std::filesystem::path findFileInPaths( } // 3. Check WebFront project subdirectories - path webfront; + path webfront; const auto currentPath{current_path()}; for (const auto& element : currentPath) { - webfront = webfront / element; + webfront = webfront / element; static constexpr std::string_view webFrontRootPath = "WebFront"; if (element == webFrontRootPath) { // Try each configured search path for (const auto& searchPath : searchPaths) { - path candidate = webfront / searchPath; - log::info(" not found : Looking now in source directory {}", candidate.string()); - if (exists(candidate / filename)) { - log::info("Found {} in {}", filename, candidate.string()); - return candidate; - } + path candidate = webfront / searchPath; + log::info(" not found : Looking now in source directory {}", candidate.string()); + if (exists(candidate / filename)) { + log::info("Found {} in {}", filename, candidate.string()); + return candidate; + } } } } @@ -72,9 +70,9 @@ inline std::filesystem::path findFileInPaths( /** * @brief Find document root for main application files - * + * * Searches in current directory, temp directory, and WebFront/src - * + * * @param filename Name of the file to find * @return std::filesystem::path Path to the directory containing the file */ @@ -84,9 +82,9 @@ inline std::filesystem::path findDocRoot(const std::string& filename) { /** * @brief Find test root for test-related files - * + * * Searches in current directory, temp directory, and WebFront/webtest - * + * * @param filename Name of the file to find * @return std::filesystem::path Path to the directory containing the file */ @@ -96,9 +94,9 @@ inline std::filesystem::path findTestRoot(const std::string& filename) { /** * @brief Find file in both development and test directories - * + * * Searches in current directory, temp directory, WebFront/src, and WebFront/webtest - * + * * @param filename Name of the file to find * @return std::filesystem::path Path to the directory containing the file */ @@ -106,4 +104,4 @@ inline std::filesystem::path findAnyRoot(const std::string& filename) { return findFileInPaths(filename, {"src", "webtest"}); } -} // namespace webfront::tooling \ No newline at end of file +} // namespace webfront::tooling \ No newline at end of file diff --git a/include/webfront/utils/Sha256.hpp b/include/webfront/utils/Sha256.hpp index 535acbec..a1751ea8 100644 --- a/include/webfront/utils/Sha256.hpp +++ b/include/webfront/utils/Sha256.hpp @@ -19,7 +19,7 @@ class Sha256 { /// Adds `bytes` to the message. Whole blocks are compressed where they lie; only a partial one is copied. void update(std::span bytes) { - length += bytes.size(); + length += bytes.size(); const auto* data = reinterpret_cast(bytes.data()); std::size_t size = bytes.size(); if (filled != 0) { @@ -92,7 +92,7 @@ class Sha256 { std::array words{}; for (std::size_t i = 0; i < 16; ++i) words[i] = (std::uint32_t{input[i * 4]} << 24) | (std::uint32_t{input[i * 4 + 1]} << 16) | (std::uint32_t{input[i * 4 + 2]} << 8) - | std::uint32_t{input[i * 4 + 3]}; + | std::uint32_t{input[i * 4 + 3]}; for (std::size_t i = 16; i < 64; ++i) { const auto x = words[i - 15], y = words[i - 2]; words[i] = words[i - 16] + (std::rotr(x, 7) ^ std::rotr(x, 18) ^ (x >> 3)) + words[i - 7] + (std::rotr(y, 17) ^ std::rotr(y, 19) ^ (y >> 10)); diff --git a/include/webfront/utils/TypeErasedFunction.hpp b/include/webfront/utils/TypeErasedFunction.hpp index 234bcf43..53051a8e 100644 --- a/include/webfront/utils/TypeErasedFunction.hpp +++ b/include/webfront/utils/TypeErasedFunction.hpp @@ -2,50 +2,49 @@ /// @author Ambroise Leclerc /// @brief Type erased functions for uniform storable functions #pragma once +#include +#include #include +#include #include #include #include -#include -#include -#include - namespace webfront::utils { -template +template struct function_traits : public function_traits {}; -template +template struct function_traits { using result_type = R; - using type = typename std::function; - using void_type = typename std::function; + using type = typename std::function; + using void_type = typename std::function; }; -template +template struct function_traits> { using result_type = R; - using type = typename std::function; - using void_type = typename std::function; + using type = typename std::function; + using void_type = typename std::function; }; -template +template struct function_traits { using result_type = R; - using type = typename std::function; - using void_type = typename std::function; + using type = typename std::function; + using void_type = typename std::function; }; -template +template struct function_traits { using result_type = R; - using type = typename std::function; - using void_type = typename std::function; + using type = typename std::function; + using void_type = typename std::function; }; namespace impl { -template +template constexpr const auto& RawTypeName() { #ifdef _MSC_VER return __FUNCSIG__; @@ -64,8 +63,8 @@ inline constexpr bool GetRawTypeNameFormat(RawTypeNameFormat* format) { for (std::size_t i = 0;; i++) { if (str[i] == 'i' && str[i + 1] == 'n' && str[i + 2] == 't') { if (format) { - format->leading_junk = i; - format->trailing_junk = sizeof(str) - i - 3 - 1; // `3` is the length of "int", `1` is the space for the null terminator. + format->leading_junk = i; + format->trailing_junk = sizeof(str) - i - 3 - 1; // `3` is the length of "int", `1` is the space for the null terminator. } return true; } @@ -79,23 +78,24 @@ inline static constexpr RawTypeNameFormat format = [] { GetRawTypeNameFormat(&rawFormat); return rawFormat; }(); -} // namespace impl +} // namespace impl // Returns the type name in a `std::array` (null-terminated). -template +template [[nodiscard]] constexpr auto CexprTypeName() { constexpr std::size_t len = sizeof(impl::RawTypeName()) - impl::format.leading_junk - impl::format.trailing_junk; std::array name{}; - for (std::size_t i = 0; i < len - 1; i++) name[i] = impl::RawTypeName()[i + impl::format.leading_junk]; + for (std::size_t i = 0; i < len - 1; i++) + name[i] = impl::RawTypeName()[i + impl::format.leading_junk]; return name; } -template +template [[nodiscard]] const char* TypeName() { static constexpr auto name = CexprTypeName(); return name.data(); } -template +template [[nodiscard]] const char* TypeName(const T&) { return TypeName(); } @@ -107,16 +107,16 @@ class TypeErasedFunction { virtual ~TypeErased() {} }; - template + template struct FunctionPointer : TypeErased { FunctionPointer(T arg) : functionPointer(arg) {} - template + template void call(Args&&... args) { functionPointer(std::forward(args)...); } - template + template R callRet(Args&&... args) { return functionPointer(std::forward(args)...); } @@ -125,13 +125,14 @@ class TypeErasedFunction { }; public: - template, TypeErasedFunction>, int> = 0> + template , TypeErasedFunction>, int> = 0> TypeErasedFunction(T&& t) - : function(new FunctionPointer>::type>(std::forward(t))), voidFunction(new FunctionPointer>::void_type>(std::forward(t))) { - std::cout << "TypeErasedFunction constructor()\n"; - } + : function(new FunctionPointer>::type>(std::forward(t))), + voidFunction(new FunctionPointer>::void_type>(std::forward(t))) { + std::cout << "TypeErasedFunction constructor()\n"; + } - template, TypeErasedFunction> && (sizeof...(Args) > 0), int> = 0> + template , TypeErasedFunction> && (sizeof...(Args) > 0), int> = 0> TypeErasedFunction(T&& t, Args&&... args) : function(new FunctionPointer>::type>(std::bind(std::forward(t), std::forward(args)...))), voidFunction(new FunctionPointer>::void_type>(std::bind(std::forward(t), std::forward(args)...))) { @@ -140,9 +141,11 @@ class TypeErasedFunction { std::cout << ")\n"; } - void operator()() { this->operator()<>(); } + void operator()() { + this->operator()<>(); + } - template + template void operator()(Args&&... args) { std::cout << "TypeErasedFunction operator("; ((std::cout << TypeName(args)), ...); @@ -155,10 +158,12 @@ class TypeErasedFunction { throw std::invalid_argument("Wrong argument type"); } - template + template R call(Args&&... args) { auto f = dynamic_cast>*>(function.get()); - if (f) { return f->template callRet(std::forward(args)...); } + if (f) { + return f->template callRet(std::forward(args)...); + } throw std::invalid_argument("Wrong argument type"); } @@ -166,4 +171,4 @@ class TypeErasedFunction { std::unique_ptr function, voidFunction; }; -} // namespace webfront::utils \ No newline at end of file +} // namespace webfront::utils \ No newline at end of file diff --git a/include/webfront/weblink/Messages.hpp b/include/webfront/weblink/Messages.hpp index f73c0a55..b6080596 100644 --- a/include/webfront/weblink/Messages.hpp +++ b/include/webfront/weblink/Messages.hpp @@ -220,8 +220,7 @@ inline constexpr std::size_t maxListTupleDepth = 32; template struct tuple_depth : std::integral_constant {}; template -struct tuple_depth> - : std::integral_constant>::value...})> {}; +struct tuple_depth> : std::integral_constant>::value...})> {}; template inline constexpr std::size_t tuple_depth_v = tuple_depth>::value; @@ -347,10 +346,10 @@ class TextCommand : public MessageBase { /// Shared header layout for function call/return messages template struct FunctionCallHeader { - Command command = Cmd; - uint8_t parametersCount = 0; // parameter 0 is the function name so parametersCount is always at least 1 - CallId callId{}; - uint32_t parametersDataSize = 0; + Command command = Cmd; + uint8_t parametersCount = 0; // parameter 0 is the function name so parametersCount is always at least 1 + CallId callId{}; + uint32_t parametersDataSize = 0; }; static_assert(sizeof(FunctionCallHeader) == 8, "FunctionCall header has to be 8 bytes long"); @@ -625,15 +624,24 @@ class FunctionCallBase : public MessageBase { if (data.empty()) throw std::runtime_error("Not enough data for msg::FunctionCall::decodeParameter"); const auto type = static_cast(data[0]); - if (type == CodedType::booleanTrue || type == CodedType::booleanFalse) return decodeBoolean(param, data); - if (type == CodedType::smallString) return decodeSmallString(param, data); - if (type == CodedType::string) return decodeLongString(param, data); - if (type == CodedType::exception) return decodeExceptionMessage(param, data); - if (type == CodedType::longString) return decodeHugeString(param, data); - if (type == CodedType::number) return decodeNumber(param, data); - if (isNumericArrayCode(type)) return decodeArray(param, data); - if (type == CodedType::tuple) return decodeTuple(param, data); - if (type == CodedType::list) return decodeList(param, data); + if (type == CodedType::booleanTrue || type == CodedType::booleanFalse) + return decodeBoolean(param, data); + if (type == CodedType::smallString) + return decodeSmallString(param, data); + if (type == CodedType::string) + return decodeLongString(param, data); + if (type == CodedType::exception) + return decodeExceptionMessage(param, data); + if (type == CodedType::longString) + return decodeHugeString(param, data); + if (type == CodedType::number) + return decodeNumber(param, data); + if (isNumericArrayCode(type)) + return decodeArray(param, data); + if (type == CodedType::tuple) + return decodeTuple(param, data); + if (type == CodedType::list) + return decodeList(param, data); throw std::runtime_error("Unsupported coded parameter type"); } @@ -767,13 +775,17 @@ class FunctionCallBase : public MessageBase { switch (type) { case CodedType::smallArrayU8: case CodedType::arrayU8: - case CodedType::array8: return 1; + case CodedType::array8: + return 1; case CodedType::arrayU16: - case CodedType::array16: return 2; + case CodedType::array16: + return 2; case CodedType::arrayU32: case CodedType::array32: - case CodedType::arrayFloat: return 4; - default: return 8; + case CodedType::arrayFloat: + return 4; + default: + return 8; } } @@ -823,7 +835,7 @@ class FunctionCallBase : public MessageBase { return header + size; } if (isNumericArrayCode(type)) { - const bool small = type == CodedType::smallArrayU8; + const bool small = type == CodedType::smallArrayU8; const std::size_t header = small ? 2 : 5; need(header); if (small) @@ -842,7 +854,7 @@ class FunctionCallBase : public MessageBase { throw std::runtime_error("List element tuples are nested too deeply"); need(2); std::size_t used = 2; - shape += '('; + shape += '('; for (std::size_t field = 0; field < static_cast(data[1]); ++field) { if (field != 0) shape += ','; @@ -903,16 +915,20 @@ class FunctionCallBase : public MessageBase { throw std::runtime_error("Truncated tuple header"); const auto tupleSize = static_cast(data[1]); if (std::tuple_size_v != tupleSize) - throw std::runtime_error("Parameter is a " + std::to_string(std::tuple_size_v) - + " elements tuple but decoded tuple only has " + std::to_string(tupleSize) + " elements."); + throw std::runtime_error("Parameter is a " + std::to_string(std::tuple_size_v) + " elements tuple but decoded tuple only has " + + std::to_string(tupleSize) + " elements."); data = data.subspan(2); - std::apply([&](auto&... tupleArgs) { ((decodeParameter(tupleArgs, data)), ...); }, param); + std::apply( + [&](auto&... tupleArgs) { + ((decodeParameter(tupleArgs, data)), ...); + }, + param); } else if constexpr (is_list_v) { // A JavaScript array that is not marked as a list arrives as a tuple of at most 255 elements. if (data.size() < 2u) throw std::runtime_error("Truncated tuple header"); const auto count = static_cast(data[1]); - data = data.subspan(2); + data = data.subspan(2); decodeListElements(param, count, data); } else throw std::runtime_error("Wrong parameter type : std::tuple expected"); @@ -965,7 +981,7 @@ class FunctionCallBase : public MessageBase { template static void decodeNumericArray(Array& param, std::span& data) { - using Element = std::remove_cv_t>; + using Element = std::remove_cv_t>; const auto [headerSize, elementCount] = readNumericArrayHeader(data); if (elementCount > std::numeric_limits::max() / sizeof(Element)) diff --git a/include/webfront/weblink/WebLink.hpp b/include/webfront/weblink/WebLink.hpp index a1e3ac66..b38d7340 100644 --- a/include/webfront/weblink/WebLink.hpp +++ b/include/webfront/weblink/WebLink.hpp @@ -40,22 +40,25 @@ struct WebLinkEvent { WebLinkEvent(Code eventCode, WebLinkId id, std::string message = {}, std::span dataView = {}, msg::CallId correlationId = 0) : code(eventCode), webLinkId(id), text(std::move(message)), data(dataView), callId(correlationId) {} - Code code; - WebLinkId webLinkId; - std::string text; + Code code; + WebLinkId webLinkId; + std::string text; std::span data; - msg::CallId callId; + msg::CallId callId; }; /// Decimal text of a link or call identifier for the diagnostic context, without allocating. class DecimalId { public: - explicit DecimalId(std::uint64_t value) : size(static_cast(std::to_chars(digits.data(), digits.data() + digits.size(), value).ptr - digits.data())) {} - [[nodiscard]] std::string_view view() const { return {digits.data(), size}; } + explicit DecimalId(std::uint64_t value) + : size(static_cast(std::to_chars(digits.data(), digits.data() + digits.size(), value).ptr - digits.data())) {} + [[nodiscard]] std::string_view view() const { + return {digits.data(), size}; + } private: std::array digits{}; - std::size_t size; + std::size_t size; }; /// Shared by a WebLink's WebSocket handlers, which can run after the link is destroyed: the @@ -63,17 +66,18 @@ class DecimalId { /// retire() returns without touching the link; retire() waits for handlers already running. class HandlerGuard { public: - template + template void run(Handler&& handler) { { std::lock_guard lock(mutex); - if (!alive) return; + if (!alive) + return; ++inFlight; } struct Exit { explicit Exit(HandlerGuard& value) : guard(value) {} HandlerGuard& guard; - Exit(const Exit&) = delete; + Exit(const Exit&) = delete; Exit& operator=(const Exit&) = delete; ~Exit() { auto& running = runningOnThisThread(); @@ -91,11 +95,13 @@ class HandlerGuard { /// Stop new handlers and wait for those on other threads. A handler of this link running on /// the calling thread (destruction from inside it) cannot be waited for and is not. void retire() { - const auto& running = runningOnThisThread(); - const auto own = static_cast(std::count(running.begin(), running.end(), this)); + const auto& running = runningOnThisThread(); + const auto own = static_cast(std::count(running.begin(), running.end(), this)); std::unique_lock lock(mutex); alive = false; - idle.wait(lock, [&] { return inFlight == own; }); + idle.wait(lock, [&] { + return inFlight == own; + }); } private: @@ -104,44 +110,61 @@ class HandlerGuard { return running; } - std::mutex mutex; + std::mutex mutex; std::condition_variable idle; - bool alive = true; - std::size_t inFlight = 0; + bool alive = true; + std::size_t inFlight = 0; }; /// The only size of handshake proof that is kept: the 64 hexadecimal characters of a launch secret (ADR-020). inline constexpr std::size_t handshakeProofSize = 64; -template +template class WebLink { - std::shared_ptr handlers{std::make_shared()}; + std::shared_ptr handlers{std::make_shared()}; std::shared_ptr> ws; - WebLinkId id; - DecimalId idText{id}; - bool sameEndian; - bool handshaken{}; /// The handshake is accepted once - std::mutex transportMutex; - std::optional transport; /// Browser log transport, attached at handshake - bool transportRetired{}; /// No transport may attach after disconnection - std::atomic droppedLogs{0}; /// Diagnostic frames refused by the bounded write queue - std::function eventsHandler; - std::span undecodedData; /// Data received but not yet consumed + WebLinkId id; + DecimalId idText{id}; + bool sameEndian; + bool handshaken{}; /// The handshake is accepted once + std::mutex transportMutex; + std::optional transport; /// Browser log transport, attached at handshake + bool transportRetired{}; /// No transport may attach after disconnection + std::atomic droppedLogs{0}; /// Diagnostic frames refused by the bounded write queue + std::function eventsHandler; + std::span undecodedData; /// Data received but not yet consumed std::shared_ptr> pending{std::make_shared>()}; public: /// Starts reading at once, unless `startNow` is false: start() then begins, once the owner can dispatch its events. - WebLink(typename Net::Socket&& socket, WebLinkId webLinkId, std::function eventHandler, networking::TaskScope& scope, - bool startNow = true) + WebLink(typename Net::Socket&& socket, + WebLinkId webLinkId, + std::function eventHandler, + networking::TaskScope& scope, + bool startNow = true) : ws(websocket::WebSocket::create(std::move(socket), scope)), id(webLinkId), eventsHandler(eventHandler) { log::debug("New WebLink created with id:{}", id); - ws->onMessage([](std::string_view text) { log::debug("onMessage(text) :{}", text); }); + ws->onMessage([](std::string_view text) { + log::debug("onMessage(text) :{}", text); + }); // Handlers capture the shared guard, never rely on `this` alone: completions may run after destruction. - ws->onMessage([this, guard = handlers](std::span data) { guard->run([&] { onBinaryMessage(data); }); }); + ws->onMessage([this, guard = handlers](std::span data) { + guard->run([&] { + onBinaryMessage(data); + }); + }); // Retire the transport before the WebSocket logs the write error, so it is never fed its own failure. - ws->onWriteError([this, guard = handlers](std::error_code) { guard->run([&] { detachTransport(true); }); }); - ws->onWritten([this, guard = handlers] { guard->run([&] { wakeWriters(); }); }); + ws->onWriteError([this, guard = handlers](std::error_code) { + guard->run([&] { + detachTransport(true); + }); + }); + ws->onWritten([this, guard = handlers] { + guard->run([&] { + wakeWriters(); + }); + }); ws->onClose([this, guard = handlers](websocket::CloseEvent event) { guard->run([&] { const log::ContextScope context(linkContext()); @@ -151,7 +174,7 @@ class WebLink { // The WebSocket reports its closure once, and never when it is stopped by the server or the link. const auto queue = writerQueue; // the event may release this link eventsHandler({WebLinkEvent::Code::closed, id}); - wakeAll(*queue); // after the closure is known: nothing will be written any more + wakeAll(*queue); // after the closure is known: nothing will be written any more }); }); @@ -160,11 +183,13 @@ class WebLink { } /// Starts reading, for a link constructed with `startNow` false. - void start() { ws->start(); } - WebLink(const WebLink&) = delete; - WebLink(WebLink&&) = delete; + void start() { + ws->start(); + } + WebLink(const WebLink&) = delete; + WebLink(WebLink&&) = delete; WebLink& operator=(const WebLink&) = delete; - WebLink& operator=(WebLink&&) = delete; + WebLink& operator=(WebLink&&) = delete; ~WebLink() { // First let no WebSocket handler reach this object again, then remove the transport (waiting @@ -183,8 +208,12 @@ class WebLink { /// Diagnostic frames are refused once this many frames of any kind await the network. static constexpr std::size_t maxPendingLogFrames = 64; - [[nodiscard]] std::uint64_t droppedLogFrames() const { return droppedLogs.load(std::memory_order_relaxed); } - [[nodiscard]] std::size_t pendingWrites() const { return ws->pendingWrites(); } + [[nodiscard]] std::uint64_t droppedLogFrames() const { + return droppedLogs.load(std::memory_order_relaxed); + } + [[nodiscard]] std::size_t pendingWrites() const { + return ws->pendingWrites(); + } /// Returns 0 when at most `limit` frames await the network. Otherwise registers `ready`, called once they do, on /// the thread that writes the frame bringing them down, and returns its identifier for cancelWrites(). The waiters @@ -201,15 +230,19 @@ class WebLink { /// Forgets a waiter of whenWritesAtMost() that was not called yet. void cancelWrites(std::uint64_t waiter) { std::function removed; // destroyed outside the lock - std::lock_guard lock(writerQueue->mutex); + std::lock_guard lock(writerQueue->mutex); if (auto found = writerQueue->writers.find(waiter); found != writerQueue->writers.end()) { removed = std::move(found->second.ready); writerQueue->writers.erase(found); } } - void sendCommand(const auto& message) { ws->write(message.header(), message.payload()); } - void sendFrame(websocket::Frame frame) { ws->write(std::move(frame)); } + void sendCommand(const auto& message) { + ws->write(message.header(), message.payload()); + } + void sendFrame(websocket::Frame frame) { + ws->write(std::move(frame)); + } /// A frame shared with other links (websocket::Frame::share()), never copied. void sendFrame(std::shared_ptr> frame) { ws->write(std::move(frame)); @@ -219,10 +252,10 @@ class WebLink { ws->writeLatest(std::move(frame), key, maxPending); } - template + template std::pair> expectResult() { - auto promise = std::make_shared>(); - auto future = promise->get_future(); + auto promise = std::make_shared>(); + auto future = promise->get_future(); msg::CallId callId{}; try { callId = pending->add({.complete = @@ -266,10 +299,17 @@ class WebLink { } switch (static_cast(data[0])) { - case msg::Command::handshake: handleHandshake(data); break; - case msg::Command::callFunction: handleCallFunction(data); break; - case msg::Command::functionReturn: completePending(*msg::FunctionReturn::castFromRawData(data)); break; - default: break; + case msg::Command::handshake: + handleHandshake(data); + break; + case msg::Command::callFunction: + handleCallFunction(data); + break; + case msg::Command::functionReturn: + completePending(*msg::FunctionReturn::castFromRawData(data)); + break; + default: + break; } } @@ -287,7 +327,7 @@ class WebLink { constexpr bool nativeIsLittle = std::endian::native == std::endian::little; constexpr bool nativeIsBig = std::endian::native == std::endian::big; const auto jsEndian = static_cast(command->getEndian()); - sameEndian = (nativeIsLittle && jsEndian == msg::JSEndian::little) || (nativeIsBig && jsEndian == msg::JSEndian::big); + sameEndian = (nativeIsLittle && jsEndian == msg::JSEndian::little) || (nativeIsBig && jsEndian == msg::JSEndian::big); // Anything after the two header bytes is the secret of an embedded view (ADR-020); the application judges it. // Only a proof of the exact size of a launch secret is copied: anything else cannot match and is not worth an allocation. @@ -298,18 +338,17 @@ class WebLink { } void handleCallFunction(std::span data) { - auto command = msg::FunctionCall::castFromRawData(data); - const DecimalId callText(command->getCallId()); - const log::ContextScope context({.component = "cppFunction", .webLinkId = idText.view(), .direction = log::CallDirection::JsToCpp, .callId = callText.view()}); + auto command = msg::FunctionCall::castFromRawData(data); + const DecimalId callText(command->getCallId()); + const log::ContextScope context( + {.component = "cppFunction", .webLinkId = idText.view(), .direction = log::CallDirection::JsToCpp, .callId = callText.view()}); log::info("Function called !"); auto [functionName, paramData] = command->getFunctionName(); try { eventsHandler(WebLinkEvent(WebLinkEvent::Code::cppFunctionCalled, id, functionName, paramData, command->getCallId())); - } - catch (const std::out_of_range& e) { + } catch (const std::out_of_range& e) { sendException(command->getCallId(), e); - } - catch (const std::exception& e) { + } catch (const std::exception& e) { log::info("event cppFunctionCalled failed with exception {}", e.what()); sendError(command->getCallId(), e.what()); } @@ -321,7 +360,8 @@ class WebLink { returnValue.setCallId(callId); websocket::Frame frame{std::span(reinterpret_cast(returnValue.header().data()), returnValue.header().size())}; returnValue.encodeParameter(error, frame); - if (callId != 0) sendFrame(std::move(frame)); + if (callId != 0) + sendFrame(std::move(frame)); } @@ -331,12 +371,13 @@ class WebLink { /// cannot forge an error that looks like the bridge's own. WebFront's own codes leave through the internal /// detail::rejectWithBridgeCode, not through a method of the link. void sendError(msg::CallId callId, std::string_view message, std::string_view code = bridge_code::generic) { - if (callId == 0) return; - const bool usable = BridgeError::isValidCode(code) && !BridgeError::isReserved(code); + if (callId == 0) + return; + const bool usable = BridgeError::isValidCode(code) && !BridgeError::isReserved(code); msg::FunctionReturn result; result.setCallId(callId); websocket::Frame frame{std::span(reinterpret_cast(result.header().data()), result.header().size())}; - const auto error = detail::makeBridgeError(usable ? code : bridge_code::generic, std::string(message)); + const auto error = detail::makeBridgeError(usable ? code : bridge_code::generic, std::string(message)); result.encodeParameter(error, frame); frame.freeze(); sendFrame(std::move(frame)); @@ -377,7 +418,9 @@ class WebLink { call(); } - void wakeAllWriters() { wakeAll(*writerQueue); } + void wakeAllWriters() { + wakeAll(*writerQueue); + } static void wakeAll(WriterQueue& queue) { std::map ready; @@ -395,7 +438,7 @@ class WebLink { } void attachTransport() { - auto handle = log::addTransport([this, guard = handlers](const log::TransportRecord& record) { + auto handle = log::addTransport([this, guard = handlers](const log::TransportRecord& record) { guard->run([&] { // A browser that stops reading must not grow the write queue without bound: diagnostics // are dropped and counted, never logged (that would feed this transport again). @@ -425,14 +468,18 @@ class WebLink { transportRetired = true; attached.swap(transport); } - if (!attached) return; - if (failed) log::reportTransportFailure(*attached); - else log::removeTransport(*attached); + if (!attached) + return; + if (failed) + log::reportTransportFailure(*attached); + else + log::removeTransport(*attached); } void completePending(const msg::FunctionReturn& result) { - const DecimalId callText(result.getCallId()); - const log::ContextScope context({.component = "jsFunction", .webLinkId = idText.view(), .direction = log::CallDirection::CppToJs, .callId = callText.view()}); + const DecimalId callText(result.getCallId()); + const log::ContextScope context( + {.component = "jsFunction", .webLinkId = idText.view(), .direction = log::CallDirection::CppToJs, .callId = callText.view()}); if (!pending->complete(result)) log::error("Received a return for unknown call {}", result.getCallId()); } @@ -479,13 +526,15 @@ class WritesAtMost { }; struct OnStop { Operation* operation; - void operator()() noexcept { operation->stopped(); } + void operator()() noexcept { + operation->stopped(); + } }; - Receiver receiver; - std::weak_ptr link; - std::size_t limit; - std::shared_ptr state; + Receiver receiver; + std::weak_ptr link; + std::size_t limit; + std::shared_ptr state; std::optional> stopCallback; void stopped() noexcept { @@ -506,7 +555,7 @@ class WritesAtMost { Operation(Operation&&) = delete; void start() noexcept { - auto token = networking::ex::get_stop_token(networking::ex::get_env(receiver)); + auto token = networking::ex::get_stop_token(networking::ex::get_env(receiver)); auto waited = link.lock(); if (token.stop_requested()) { state->done = true; @@ -523,12 +572,12 @@ class WritesAtMost { try { waiter = waited->whenWritesAtMost(limit, [shared] { if (shared->done.exchange(true) || shared->record(Completion::value)) - return; // stopped first, or start() delivers it + return; // stopped first, or start() delivers it auto* operation = shared->operation; operation->stopCallback.reset(); // waits for a stop callback running on another thread networking::ex::set_value(std::move(operation->receiver)); }); - } catch (...) { } // registering failed: there is nothing to wait for + } catch (...) {} // registering failed: there is nothing to wait for } shared->waiter = waiter; Completion completion; @@ -540,7 +589,7 @@ class WritesAtMost { if (completion == Completion::none && waiter == 0 && !shared->done.exchange(true)) completion = Completion::value; // already at most `limit` frames queued if (completion == Completion::none) - return; // the waiter or the stop callback completes it + return; // the waiter or the stop callback completes it if (waiter != 0) waited->cancelWrites(waiter); stopCallback.reset(); @@ -562,4 +611,4 @@ class WritesAtMost { }; } // namespace detail -} // namespace webfront +} // namespace webfront diff --git a/test/cmake/bdd-consumer/main.cpp b/test/cmake/bdd-consumer/main.cpp index a885ca4c..1637c822 100644 --- a/test/cmake/bdd-consumer/main.cpp +++ b/test/cmake/bdd-consumer/main.cpp @@ -5,20 +5,26 @@ using namespace webfront::bdd; const Scenario addition{"Addition", [] { - int sum = 0; - given("two numbers", [&] { - when("they are added", [&] { - sum = 2 + 3; - then("the sum is five", [&] { require(sum == 5); }); - }); - }); -}}; + int sum = 0; + given("two numbers", [&] { + when("they are added", [&] { + sum = 2 + 3; + then("the sum is five", [&] { + require(sum == 5); + }); + }); + }); + }}; const Scenario text{"A [bracketed; title] stays whole", [] { - given("a string", [] { then("it has a length", [] { check(std::string{"abc"}.size() == 3); }); }); -}}; + given("a string", [] { + then("it has a length", [] { + check(std::string{"abc"}.size() == 3); + }); + }); + }}; -const Scenario third{"Third", [] { }}; +const Scenario third{"Third", [] {}}; int main(int argc, char** argv) { return run(argc, argv); diff --git a/test/cmake/consumer/main.cpp b/test/cmake/consumer/main.cpp index f7f388f8..846aa232 100644 --- a/test/cmake/consumer/main.cpp +++ b/test/cmake/consumer/main.cpp @@ -1,21 +1,21 @@ // Check before standard headers can supply their vendor defaults. #if defined(_GLIBCXX_ASSERTIONS) || defined(_LIBCPP_HARDENING_MODE) || defined(_MSVC_STL_HARDENING) -#error WebFront must not impose standard library hardening on consumers + #error WebFront must not impose standard library hardening on consumers #endif #if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) #error WebFront must not impose sanitizers on consumers #endif #if defined(__has_feature) -#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(undefined_behavior_sanitizer) -#error WebFront must not impose sanitizers on consumers -#endif + #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(undefined_behavior_sanitizer) + #error WebFront must not impose sanitizers on consumers + #endif #endif -#include #include +#include #if defined(WEBFRONT_CONSUMER_EXPECT_NATIVE) && !defined(WEBFRONT_NATIVE_WINDOW) -#error The native consumer must compile the native frontend branch + #error The native consumer must compile the native frontend branch #endif #if defined(WEBFRONT_NATIVE_WINDOW) using ConsumerApp = webfront::WebFrontWithFrontend; @@ -25,7 +25,7 @@ using ConsumerApp = webfront::WebFront; int main(int argc, char**) { if (argc > 1) { // never taken by the smoke test: it only proves that the library compiles and links - ConsumerApp app; + ConsumerApp app; webfront::testing::JasmineTest tests{app}; app.show(); } diff --git a/test/driver/RequestLog.hpp b/test/driver/RequestLog.hpp index 289d2da0..33f7ae4e 100644 --- a/test/driver/RequestLog.hpp +++ b/test/driver/RequestLog.hpp @@ -12,8 +12,11 @@ namespace webfront::testdriver { // Markers of the lines the HTTP layer logs for a request (HTTPServer.hpp). Rename a message there and update this // list: LoggerTests checks the filter against the server's current wording. -inline constexpr std::array requestMarkers{ - "Received request ", "responding http ", "HTTP asset request ", "ended its response early", "Route "}; +inline constexpr std::array requestMarkers{"Received request ", + "responding http ", + "HTTP asset request ", + "ended its response early", + "Route "}; inline bool isRequestLine(std::string_view line) { // An allow-list: a tagged warning or error is kept, and an Info line only when it describes a request. A line with no diff --git a/test/driver/TestFrontend.hpp b/test/driver/TestFrontend.hpp index 23f6dfd0..01f0fd57 100644 --- a/test/driver/TestFrontend.hpp +++ b/test/driver/TestFrontend.hpp @@ -23,8 +23,12 @@ struct TestFrontend : Frontend { open(address, port, page, policy, window, ViewLaunch{}); } // The launch proof reaches the engine as it does in an application: the suite runs the same association. - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { + static void open(std::string_view address, + std::string_view port, + std::string_view page, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch) { // Rendering stays visible where the frontend can hide its window; the Linux engines use one Xvfb display around a // complete suite and their native windows stay real. if constexpr (requires { Frontend::startingOptions(); }) { diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 4a7b7985..f3cd51b6 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -71,16 +71,18 @@ struct DriverCEFFrontend : frontend::CEFFrontend { static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy = {}) { open(address, port, page, policy, {}, {}); } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, - const WindowOptions& window, const ViewLaunch& launch) { + static void open(std::string_view address, + std::string_view port, + std::string_view page, + const ContentPolicy& policy, + const WindowOptions& window, + const ViewLaunch& launch) { #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) const auto* profile = std::getenv("WEBFRONT_TEST_CEF_PROFILE"); if (!profile || !*profile) throw std::runtime_error("CEF test driver requires an isolated WEBFRONT_TEST_CEF_PROFILE"); const auto url = frontend::detail::applicationUrl(address, port, page, launch.origin); - cef::detail::openWindow(url, webfront::detail::BoundContentPolicy{url, policy}, - nullptr, - std::filesystem::path(profile), window, false, launch); + cef::detail::openWindow(url, webfront::detail::BoundContentPolicy{url, policy}, nullptr, std::filesystem::path(profile), window, false, launch); #else frontend::CEFFrontend::open(address, port, page, policy, window, launch); #endif @@ -407,7 +409,7 @@ struct PlainSetup { template int run(const Options& options, Setup&& setup = {}) { using Configuration = std::remove_reference_t; - using App = typename decltype([] { + using App = typename decltype([] { if constexpr (requires { typename Configuration::Application; }) return std::type_identity{}; else @@ -427,16 +429,16 @@ int run(const Options& options, Setup&& setup = {}) { sources().registry = std::filesystem::canonical(*sources().registry); const auto started = std::chrono::steady_clock::now(); - const auto phase = [&](std::string_view name) { + const auto phase = [&](std::string_view name) { std::cout << "driver " << std::chrono::duration(std::chrono::steady_clock::now() - started).count() << "ms " << name << std::endl; }; - DriverDeadline deadlines{options.timeout}; - Outcome outcome; + DriverDeadline deadlines{options.timeout}; + Outcome outcome; webfront::WebFrontConfig config{.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested}; if constexpr (requires { setup.configureApplication(config); }) setup.configureApplication(config); - App app{options.project, std::move(config)}; - bool commandStarted = false; + App app{options.project, std::move(config)}; + bool commandStarted = false; app.cppFunction("wf.commandStarted", [&] { if (std::exchange(commandStarted, true)) throw std::runtime_error("Unexpected single-command start"); diff --git a/test/fuzz/MessagesFuzz.cpp b/test/fuzz/MessagesFuzz.cpp index 694f6281..360d04b7 100644 --- a/test/fuzz/MessagesFuzz.cpp +++ b/test/fuzz/MessagesFuzz.cpp @@ -40,7 +40,7 @@ extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size break; } } - } catch (const std::runtime_error&) { } + } catch (const std::runtime_error&) {} // Try every owning result family, including mismatches; no recursive untrusted types. decode(bytes); decode(bytes); diff --git a/test/unit/AcceptEncodingTests.cpp b/test/unit/AcceptEncodingTests.cpp index f1c2c0fb..05406d8c 100644 --- a/test/unit/AcceptEncodingTests.cpp +++ b/test/unit/AcceptEncodingTests.cpp @@ -1,200 +1,200 @@ -#include #include +#include using namespace webfront::bdd; using webfront::http::Headers; const Scenario acceptEncodingDefaults{"Accept-Encoding defaults to the identity fallback", [] { - for (const auto includeEmptyField : {false, true}) { - given("an absent or empty field: ", includeEmptyField, [&] { - Headers headers; - if (includeEmptyField) - headers.headers.emplace_back("Accept-Encoding", ""); - then("identity is available and gzip is not advertised", [&] { - require(headers.acceptsEncoding("identity")); - require(!headers.acceptsEncoding("gzip")); - }); - }); - } -}}; + for (const auto includeEmptyField : {false, true}) { + given("an absent or empty field: ", includeEmptyField, [&] { + Headers headers; + if (includeEmptyField) + headers.headers.emplace_back("Accept-Encoding", ""); + then("identity is available and gzip is not advertised", [&] { + require(headers.acceptsEncoding("identity")); + require(!headers.acceptsEncoding("gzip")); + }); + }); + } + }}; const Scenario acceptEncodingMatches{"Accept-Encoding matches complete case-insensitive tokens with HTTP whitespace", [] { - for (const auto value : {"gzip", "GZIP", " GZIP \t", "br,\tgzip ; q = 0.5 ", "gzip;q=1.000", ", gzip,,"}) { - given(value, [&] { - Headers headers; - headers.headers.emplace_back("accept-ENCODING", value); - then("gzip is accepted", [&] { - require(headers.acceptsEncoding("gzip")); - }); - }); - } - for (const auto value : {"xgzip", "gzip2", "br, deflate"}) { - given(value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", value); - then("substrings do not advertise gzip", [&] { - require(!headers.acceptsEncoding("gzip")); - }); - }); - } -}}; + for (const auto value : {"gzip", "GZIP", " GZIP \t", "br,\tgzip ; q = 0.5 ", "gzip;q=1.000", ", gzip,,"}) { + given(value, [&] { + Headers headers; + headers.headers.emplace_back("accept-ENCODING", value); + then("gzip is accepted", [&] { + require(headers.acceptsEncoding("gzip")); + }); + }); + } + for (const auto value : {"xgzip", "gzip2", "br, deflate"}) { + given(value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", value); + then("substrings do not advertise gzip", [&] { + require(!headers.acceptsEncoding("gzip")); + }); + }); + } + }}; const Scenario acceptEncodingRespects{"Accept-Encoding respects explicit and wildcard exclusions", [] { - struct Preference { - const char* value; - bool gzip; - bool identity; - }; - for (const auto& preference : { - Preference{ "gzip;q=0", false, true}, - { "*;q=0", false, false}, - { "identity;q=0", false, false}, - { "gzip;q=0, *;q=1", false, true}, - { "*;q=0, gzip;q=1", true, false}, - {"*;q=0, identity;q=0.5", false, true}, - { "gzip, identity;q=0", true, false} - }) { - given(preference.value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", preference.value); - then("explicit tokens override the wildcard", [&] { - require(headers.acceptsEncoding("gzip") == preference.gzip); - require(headers.acceptsEncoding("identity") == preference.identity); - }); - }); - } -}}; + struct Preference { + const char* value; + bool gzip; + bool identity; + }; + for (const auto& preference : { + Preference{ "gzip;q=0", false, true}, + { "*;q=0", false, false}, + { "identity;q=0", false, false}, + { "gzip;q=0, *;q=1", false, true}, + { "*;q=0, gzip;q=1", true, false}, + {"*;q=0, identity;q=0.5", false, true}, + { "gzip, identity;q=0", true, false} + }) { + given(preference.value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", preference.value); + then("explicit tokens override the wildcard", [&] { + require(headers.acceptsEncoding("gzip") == preference.gzip); + require(headers.acceptsEncoding("identity") == preference.identity); + }); + }); + } + }}; const Scenario acceptEncodingRejects{"Accept-Encoding rejects malformed qvalues", [] { - for (const auto value : {"1.5", "", "invalid", "-1", "01", "0.0001", "1.001", ".5"}) { - given("q=", value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", std::string("gzip;q=") + value); - then("the malformed preference does not accept gzip", [&] { - require(!headers.acceptsEncoding("gzip")); - }); - }); - } -}}; + for (const auto value : {"1.5", "", "invalid", "-1", "01", "0.0001", "1.001", ".5"}) { + given("q=", value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", std::string("gzip;q=") + value); + then("the malformed preference does not accept gzip", [&] { + require(!headers.acceptsEncoding("gzip")); + }); + }); + } + }}; const Scenario acceptEncodingIgnores{"Accept-Encoding ignores unknown parameters while preserving q exclusions", [] { - for (const auto value : {"gzip;level=1", "gzip;level=1;q=0.5", "gzip; q=1; level=1", "gzip;extension"}) { - given(value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", value); - then("extension parameters do not disable gzip", [&] { - require(headers.acceptsEncoding("gzip")); - }); - }); - } - for (const auto value : {"gzip;level=1;q=0", "gzip;q=0;level=1", "gzip;level=1;q=1.5"}) { - given(value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", value); - then("extensions cannot override a rejected qvalue", [&] { - require(!headers.acceptsEncoding("gzip")); - }); - }); - } -}}; + for (const auto value : {"gzip;level=1", "gzip;level=1;q=0.5", "gzip; q=1; level=1", "gzip;extension"}) { + given(value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", value); + then("extension parameters do not disable gzip", [&] { + require(headers.acceptsEncoding("gzip")); + }); + }); + } + for (const auto value : {"gzip;level=1;q=0", "gzip;q=0;level=1", "gzip;level=1;q=1.5"}) { + given(value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", value); + then("extensions cannot override a rejected qvalue", [&] { + require(!headers.acceptsEncoding("gzip")); + }); + }); + } + }}; const Scenario acceptEncodingCombines{"Accept-Encoding combines multiple fields before applying wildcard precedence", [] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", "*;q=0"); - headers.headers.emplace_back("accept-encoding", "GZIP;q=0.5"); - headers.headers.emplace_back("ACCEPT-ENCODING", "identity;q=1"); - then("an explicit preference in any field overrides the wildcard", [&] { - require(headers.acceptsEncoding("gzip")); - require(headers.acceptsEncoding("identity")); - require(!headers.acceptsEncoding("br")); - }); - given("a wildcard acceptance and an explicit gzip exclusion in separate fields", [&] { - headers.headers.clear(); - headers.headers.emplace_back("Accept-Encoding", "*;q=1"); - headers.headers.emplace_back("accept-encoding", "gzip;q=0"); - then("the explicit exclusion still wins", [&] { - require(!headers.acceptsEncoding("gzip")); - require(headers.acceptsEncoding("br")); - }); - }); -}}; + Headers headers; + headers.headers.emplace_back("Accept-Encoding", "*;q=0"); + headers.headers.emplace_back("accept-encoding", "GZIP;q=0.5"); + headers.headers.emplace_back("ACCEPT-ENCODING", "identity;q=1"); + then("an explicit preference in any field overrides the wildcard", [&] { + require(headers.acceptsEncoding("gzip")); + require(headers.acceptsEncoding("identity")); + require(!headers.acceptsEncoding("br")); + }); + given("a wildcard acceptance and an explicit gzip exclusion in separate fields", [&] { + headers.headers.clear(); + headers.headers.emplace_back("Accept-Encoding", "*;q=1"); + headers.headers.emplace_back("accept-encoding", "gzip;q=0"); + then("the explicit exclusion still wins", [&] { + require(!headers.acceptsEncoding("gzip")); + require(headers.acceptsEncoding("br")); + }); + }); + }}; const Scenario acceptEncodingAccepts{"Accept-Encoding accepts any positive duplicate regardless of order", [] { - for (const auto value : {"gzip;q=0, gzip", "gzip, gzip;q=0", "gzip;q=.5, gzip", "gzip, gzip;q=.5"}) { - given(value, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", value); - then("a valid accepting mention wins over the rejected mention", [&] { - require(headers.acceptsEncoding("gzip")); - }); - }); - } - for (const auto first : {"gzip", "gzip;q=0"}) { - given("first field: ", first, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", first); - headers.headers.emplace_back("Accept-Encoding", first == std::string_view("gzip") ? "gzip;q=0" : "gzip"); - then("duplicate mentions across fields follow the same rule", [&] { - require(headers.acceptsEncoding("gzip")); - }); - }); - } -}}; + for (const auto value : {"gzip;q=0, gzip", "gzip, gzip;q=0", "gzip;q=.5, gzip", "gzip, gzip;q=.5"}) { + given(value, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", value); + then("a valid accepting mention wins over the rejected mention", [&] { + require(headers.acceptsEncoding("gzip")); + }); + }); + } + for (const auto first : {"gzip", "gzip;q=0"}) { + given("first field: ", first, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", first); + headers.headers.emplace_back("Accept-Encoding", first == std::string_view("gzip") ? "gzip;q=0" : "gzip"); + then("duplicate mentions across fields follow the same rule", [&] { + require(headers.acceptsEncoding("gzip")); + }); + }); + } + }}; static_assert(webfront::http::encoding::tokenEquals("GZIP", "gzip")); static_assert(!webfront::http::encoding::tokenEquals("\xc0", "\xe0")); const Scenario hTTPEncoding{"HTTP encoding token comparison folds ASCII letters only", [] { - given("ASCII punctuation", [&] { - then("case folding does not conflate punctuation pairs", [&] { - require(!webfront::http::encoding::tokenEquals("@", "`")); - require(!webfront::http::encoding::tokenEquals("[", "{")); - }); - }); - given("every non-ASCII byte", [&] { - then("each byte compares equal only to itself among its bit-5 pair", [&] { - for (unsigned value = 128; value < 256; ++value) { - const std::string original(1, static_cast(value)); - const std::string other(1, static_cast(value ^ 0x20)); - require(webfront::http::encoding::tokenEquals(original, original)); - require(!webfront::http::encoding::tokenEquals(original, other)); - } - }); - }); -}}; + given("ASCII punctuation", [&] { + then("case folding does not conflate punctuation pairs", [&] { + require(!webfront::http::encoding::tokenEquals("@", "`")); + require(!webfront::http::encoding::tokenEquals("[", "{")); + }); + }); + given("every non-ASCII byte", [&] { + then("each byte compares equal only to itself among its bit-5 pair", [&] { + for (unsigned value = 128; value < 256; ++value) { + const std::string original(1, static_cast(value)); + const std::string other(1, static_cast(value ^ 0x20)); + require(webfront::http::encoding::tokenEquals(original, original)); + require(!webfront::http::encoding::tokenEquals(original, other)); + } + }); + }); + }}; const Scenario acceptEncodingTreats{"Accept-Encoding treats x-gzip as the gzip alias", [] { - struct Preference { - const char* field; - bool accepted; - }; - for (const auto& preference : { - Preference{ "x-gzip", true}, - { "X-GZIP;q=0.5", true}, - { "x-gzip;q=0", false}, - {"*;q=1, x-gzip;q=0", false}, - { "*;q=0, x-gzip", true}, - { "gzip;q=0, x-gzip", true}, - { "x-gzip;q=0, gzip", true}, - { "x-gzip;q=.5", false}, - { "x-gzip2", false} - }) { - given(preference.field, [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", preference.field); - then("both names share the explicit preference and wildcard precedence", [&] { - require(headers.acceptsEncoding("gzip") == preference.accepted); - require(headers.acceptsEncoding("x-gzip") == preference.accepted); - }); - }); - } - given("the aliases in separate fields", [&] { - Headers headers; - headers.headers.emplace_back("Accept-Encoding", "gzip;q=0"); - headers.headers.emplace_back("Accept-Encoding", "x-gzip"); - then("accepting duplicates merge across aliases and fields", [&] { - require(headers.acceptsEncoding("gzip")); - }); - }); -}}; + struct Preference { + const char* field; + bool accepted; + }; + for (const auto& preference : { + Preference{ "x-gzip", true}, + { "X-GZIP;q=0.5", true}, + { "x-gzip;q=0", false}, + {"*;q=1, x-gzip;q=0", false}, + { "*;q=0, x-gzip", true}, + { "gzip;q=0, x-gzip", true}, + { "x-gzip;q=0, gzip", true}, + { "x-gzip;q=.5", false}, + { "x-gzip2", false} + }) { + given(preference.field, [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", preference.field); + then("both names share the explicit preference and wildcard precedence", [&] { + require(headers.acceptsEncoding("gzip") == preference.accepted); + require(headers.acceptsEncoding("x-gzip") == preference.accepted); + }); + }); + } + given("the aliases in separate fields", [&] { + Headers headers; + headers.headers.emplace_back("Accept-Encoding", "gzip;q=0"); + headers.headers.emplace_back("Accept-Encoding", "x-gzip"); + then("accepting duplicates merge across aliases and fields", [&] { + require(headers.acceptsEncoding("gzip")); + }); + }); + }}; diff --git a/test/unit/ApplicationTaskTests.cpp b/test/unit/ApplicationTaskTests.cpp index 32c32cd7..ae904af7 100644 --- a/test/unit/ApplicationTaskTests.cpp +++ b/test/unit/ApplicationTaskTests.cpp @@ -26,7 +26,7 @@ webfront::Task finishedTask(bool& ran) { webfront::Task pendingTask(std::shared_ptr lifetime) { static_cast(lifetime); - co_await webfront::testing::ManualSender([](auto) { }); + co_await webfront::testing::ManualSender([](auto) {}); } struct ExternalSender { @@ -80,124 +80,140 @@ struct PausedStartSender { } // namespace const Scenario scopeDrain{"Scope drain waits for a concurrent spawn to finish starting", [] { - webfront::networking::TaskScope scope; - webfront::networking::IoContextMock context; - std::latch started(1), release(1); - given("a task associated with the scope but paused inside start", [&] { - std::atomic accepted{false}; - std::jthread caller([&] { - accepted = scope.spawn(PausedStartSender{started, release}); - }); - started.wait(); - std::latch stopping(1); - auto onStop = [&] { - stopping.count_down(); - }; - ex::stop_callback_for_t callback(scope.stopToken(), onStop); - std::promise result; - auto finished = result.get_future(); - std::jthread drainer([&] { - try { - scope.drain(context); - result.set_value(); - } catch (...) { - result.set_exception(std::current_exception()); - } - }); - stopping.wait(); - const auto status = finished.wait_for(std::chrono::milliseconds(100)); - release.count_down(); - caller.join(); - drainer.join(); - then("the empty context is not mistaken for a stalled task", [&] { - check(accepted.load()); - check(status == std::future_status::timeout); - checkNothrow([&] { finished.get(); }); - checkNothrow([&] { scope.drain(context); }); - }); - }); - given("a sender that throws while connecting", [&] { - checkThrows([&] { scope.spawn(PausedStartSender{started, release, true}); }); - then("draining does not wait for the failed spawn", [&] { - checkNothrow([&] { scope.drain(context); }); - }); - }); -}}; + webfront::networking::TaskScope scope; + webfront::networking::IoContextMock context; + std::latch started(1), release(1); + given("a task associated with the scope but paused inside start", [&] { + std::atomic accepted{false}; + std::jthread caller([&] { + accepted = scope.spawn(PausedStartSender{started, release}); + }); + started.wait(); + std::latch stopping(1); + auto onStop = [&] { + stopping.count_down(); + }; + ex::stop_callback_for_t callback(scope.stopToken(), onStop); + std::promise result; + auto finished = result.get_future(); + std::jthread drainer([&] { + try { + scope.drain(context); + result.set_value(); + } catch (...) { + result.set_exception(std::current_exception()); + } + }); + stopping.wait(); + const auto status = finished.wait_for(std::chrono::milliseconds(100)); + release.count_down(); + caller.join(); + drainer.join(); + then("the empty context is not mistaken for a stalled task", [&] { + check(accepted.load()); + check(status == std::future_status::timeout); + checkNothrow([&] { + finished.get(); + }); + checkNothrow([&] { + scope.drain(context); + }); + }); + }); + given("a sender that throws while connecting", [&] { + checkThrows([&] { + scope.spawn(PausedStartSender{started, release, true}); + }); + then("draining does not wait for the failed spawn", [&] { + checkNothrow([&] { + scope.drain(context); + }); + }); + }); + }}; const Scenario applicationsOwn{"Applications own spawned coroutines and expose individual cancellation", [] { - given("two application coroutines suspended on cancellable operations", [&] { - App app(webfront::WebFrontConfig{.port = "0"}); - auto first = std::make_shared(1); - auto second = std::make_shared(2); - std::weak_ptr firstFrame = first; - std::weak_ptr secondFrame = second; - auto handle = app.spawn(pendingTask(std::move(first))); - App::UI ui(app, 0, 1); - ui.spawn(pendingTask(std::move(second))); - require(!firstFrame.expired()); - require(!secondFrame.expired()); - when("one task is cancelled through its handle", [&] { - handle.requestStop(); - then("only that coroutine unwinds", [&] { - check(firstFrame.expired()); - check(!secondFrame.expired()); - check(handle.stopRequested()); - }); - }); - when("the application shuts down", [&] { - app.shutdown(); - then("both frames are destroyed before it returns", [&] { - check(firstFrame.expired()); - check(secondFrame.expired()); - checkNothrow([&] { app.shutdown(); }); - bool ran = false; - auto rejected = app.spawn(finishedTask(ran)); - check(rejected.stopRequested()); - check(!ran); - }); - }); - }); - given("a coroutine that completes normally", [&] { - App app(webfront::WebFrontConfig{.port = "0"}); - bool ran = false; - auto handle = app.spawn(finishedTask(ran)); - then("it runs without an explicit scope or context", [&] { - check(ran); - check(!handle.stopRequested()); - }); - }); - given("a handle retained beyond its application", [&] { - webfront::TaskHandle handle; - std::weak_ptr frame; - { - App app(webfront::WebFrontConfig{.port = "0"}); - auto lifetime = std::make_shared(42); - frame = lifetime; - handle = app.spawn(pendingTask(std::move(lifetime))); - } - then("destruction drained its task and the handle remains safe", [&] { - check(frame.expired()); - checkNothrow([&] { handle.requestStop(); }); - }); - }); -}}; + given("two application coroutines suspended on cancellable operations", [&] { + App app(webfront::WebFrontConfig{.port = "0"}); + auto first = std::make_shared(1); + auto second = std::make_shared(2); + std::weak_ptr firstFrame = first; + std::weak_ptr secondFrame = second; + auto handle = app.spawn(pendingTask(std::move(first))); + App::UI ui(app, 0, 1); + ui.spawn(pendingTask(std::move(second))); + require(!firstFrame.expired()); + require(!secondFrame.expired()); + when("one task is cancelled through its handle", [&] { + handle.requestStop(); + then("only that coroutine unwinds", [&] { + check(firstFrame.expired()); + check(!secondFrame.expired()); + check(handle.stopRequested()); + }); + }); + when("the application shuts down", [&] { + app.shutdown(); + then("both frames are destroyed before it returns", [&] { + check(firstFrame.expired()); + check(secondFrame.expired()); + checkNothrow([&] { + app.shutdown(); + }); + bool ran = false; + auto rejected = app.spawn(finishedTask(ran)); + check(rejected.stopRequested()); + check(!ran); + }); + }); + }); + given("a coroutine that completes normally", [&] { + App app(webfront::WebFrontConfig{.port = "0"}); + bool ran = false; + auto handle = app.spawn(finishedTask(ran)); + then("it runs without an explicit scope or context", [&] { + check(ran); + check(!handle.stopRequested()); + }); + }); + given("a handle retained beyond its application", [&] { + webfront::TaskHandle handle; + std::weak_ptr frame; + { + App app(webfront::WebFrontConfig{.port = "0"}); + auto lifetime = std::make_shared(42); + frame = lifetime; + handle = app.spawn(pendingTask(std::move(lifetime))); + } + then("destruction drained its task and the handle remains safe", [&] { + check(frame.expired()); + checkNothrow([&] { + handle.requestStop(); + }); + }); + }); + }}; const Scenario stalledScope{"A stalled scope reports absent context work without abandoning its join", [] { - given("a task suspended on an external operation that ignores cancellation", [&] { - std::function complete; - webfront::testing::InlineTaskScope scope; - webfront::networking::IoContextMock context; - webfront::networking::Spawn(scope, ex::inline_scheduler{}, externalTask(complete)); - when("drain finds no context completion capable of advancing the task", [&] { - checkThrows([&] { scope.drain(context); }); - then("the join remains alive and can finish after external completion", [&] { - require(complete); - complete(); - checkNothrow([&] { scope.drain(context); }); - }); - }); - }); -}}; + given("a task suspended on an external operation that ignores cancellation", [&] { + std::function complete; + webfront::testing::InlineTaskScope scope; + webfront::networking::IoContextMock context; + webfront::networking::Spawn(scope, ex::inline_scheduler{}, externalTask(complete)); + when("drain finds no context completion capable of advancing the task", [&] { + checkThrows([&] { + scope.drain(context); + }); + then("the join remains alive and can finish after external completion", [&] { + require(complete); + complete(); + checkNothrow([&] { + scope.drain(context); + }); + }); + }); + }); + }}; namespace { struct SpawnOnExit { @@ -210,82 +226,88 @@ struct SpawnOnExit { }; webfront::Task spawnDuringCleanup(App& app, bool& ran, std::optional& handle) { SpawnOnExit guard{app, ran, handle}; - co_await webfront::testing::ManualSender([](auto) { }); + co_await webfront::testing::ManualSender([](auto) {}); } } // namespace const Scenario spawningDuring{"Spawning during shutdown is rejected with a stopped handle", [] { - given("a coroutine whose cleanup tries to start another task", [&] { - bool ran = false; - std::optional handle; - App app(webfront::WebFrontConfig{.port = "0"}); - app.spawn(spawnDuringCleanup(app, ran, handle)); - when("the application stops its existing tasks", [&] { - checkNothrow([&] { app.shutdown(); }); - then("the nested spawn does not throw or start its body", [&] { - require(handle); - check(handle->stopRequested()); - check(!ran); - }); - }); - }); -}}; + given("a coroutine whose cleanup tries to start another task", [&] { + bool ran = false; + std::optional handle; + App app(webfront::WebFrontConfig{.port = "0"}); + app.spawn(spawnDuringCleanup(app, ran, handle)); + when("the application stops its existing tasks", [&] { + checkNothrow([&] { + app.shutdown(); + }); + then("the nested spawn does not throw or start its body", [&] { + require(handle); + check(handle->stopRequested()); + check(!ran); + }); + }); + }); + }}; const Scenario spawnScope{"Spawn and scope close agree on whether work was accepted", [] { - given("a scope closed before any stop request", [&] { - bool ran = false; - webfront::testing::InlineTaskScope scope; - scope.close(); - require(!scope.stopRequested()); - when("a cold task is offered to it", [&] { - auto accepted = webfront::networking::Spawn(scope, ex::inline_scheduler{}, finishedTask(ran)); - then("association rejection is reported without executing the task", [&] { - check(!accepted); - check(!ran); - }); - }); - }); + given("a scope closed before any stop request", [&] { + bool ran = false; + webfront::testing::InlineTaskScope scope; + scope.close(); + require(!scope.stopRequested()); + when("a cold task is offered to it", [&] { + auto accepted = webfront::networking::Spawn(scope, ex::inline_scheduler{}, finishedTask(ran)); + then("association rejection is reported without executing the task", [&] { + check(!accepted); + check(!ran); + }); + }); + }); - given("a caller starting tasks while another thread shuts the application down", [&] { - App app(webfront::WebFrontConfig{.port = "0"}); - std::atomic go{false}; - std::atomic invalid{false}; - std::jthread caller([&] { - go.wait(false); - for (int i = 0; i != 100; ++i) { - bool ran = false; - auto handle = app.spawn(finishedTask(ran)); - if (!ran && !handle.stopRequested()) - invalid = true; - } - }); - go = true; - go.notify_one(); - checkNothrow([&] { app.shutdown(); }); - caller.join(); - then("every rejected task returns a stopped handle", [&] { - check(!invalid.load()); - }); - }); -}}; + given("a caller starting tasks while another thread shuts the application down", [&] { + App app(webfront::WebFrontConfig{.port = "0"}); + std::atomic go{false}; + std::atomic invalid{false}; + std::jthread caller([&] { + go.wait(false); + for (int i = 0; i != 100; ++i) { + bool ran = false; + auto handle = app.spawn(finishedTask(ran)); + if (!ran && !handle.stopRequested()) + invalid = true; + } + }); + go = true; + go.notify_one(); + checkNothrow([&] { + app.shutdown(); + }); + caller.join(); + then("every rejected task returns a stopped handle", [&] { + check(!invalid.load()); + }); + }); + }}; const Scenario destructionWaits{"Destruction waits safely after an explicit shutdown reports a pending external task", [] { - given("a task that cannot finish until an external operation completes", [&] { - std::function complete; - auto app = std::make_unique(webfront::WebFrontConfig{.port = "0"}); - app->spawn(externalTask(complete)); - checkThrows([&] { app->shutdown(); }); - require(complete); - std::jthread finishing([complete] { - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - complete(); - }); - when("the application is destroyed before that completion arrives", [&] { - app.reset(); - finishing.join(); - then("its destructor joins instead of allowing a drain exception to escape", [&] { - check(!app); - }); - }); - }); -}}; + given("a task that cannot finish until an external operation completes", [&] { + std::function complete; + auto app = std::make_unique(webfront::WebFrontConfig{.port = "0"}); + app->spawn(externalTask(complete)); + checkThrows([&] { + app->shutdown(); + }); + require(complete); + std::jthread finishing([complete] { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + complete(); + }); + when("the application is destroyed before that completion arrives", [&] { + app.reset(); + finishing.join(); + then("its destructor joins instead of allowing a drain exception to escape", [&] { + check(!app); + }); + }); + }); + }}; diff --git a/test/unit/ApplicationUrlTests.cpp b/test/unit/ApplicationUrlTests.cpp index 34091c98..2bda120f 100644 --- a/test/unit/ApplicationUrlTests.cpp +++ b/test/unit/ApplicationUrlTests.cpp @@ -1,35 +1,43 @@ -#include #include +#include using namespace webfront::bdd; const Scenario frontendURLs{"Frontend URLs use the configured listening address", [] { - using webfront::frontend::detail::applicationUrl; - then("IPv4 and IPv6 addresses are preserved and wildcard binds open loopback", [&] { - require(applicationUrl("127.0.0.2", "9010", "index.html") == "http://127.0.0.2:9010/index.html"); - require(applicationUrl("::1", "9010", "index.html") == "http://[::1]:9010/index.html"); - require(applicationUrl("[::1]", "9010", "index.html") == "http://[::1]:9010/index.html"); - require(applicationUrl("0.0.0.0", "9010", "index.html") == "http://127.0.0.1:9010/index.html"); - require(applicationUrl("::", "9010", "index.html") == "http://[::1]:9010/index.html"); - require(applicationUrl("localhost", "9010", "index.html") == "http://localhost:9010/index.html"); - }); - then("addresses and ports cannot inject URL authority or shell syntax", [&] { - requireThrows([&] { applicationUrl("", "9010", "index.html"); }); - requireThrows([&] { applicationUrl("127.0.0.1/evil", "9010", "index.html"); }); - requireThrows([&] { applicationUrl("127.0.0.1", "", "index.html"); }); - requireThrows([&] { applicationUrl("127.0.0.1", "90'10", "index.html"); }); - }); -}}; + using webfront::frontend::detail::applicationUrl; + then("IPv4 and IPv6 addresses are preserved and wildcard binds open loopback", [&] { + require(applicationUrl("127.0.0.2", "9010", "index.html") == "http://127.0.0.2:9010/index.html"); + require(applicationUrl("::1", "9010", "index.html") == "http://[::1]:9010/index.html"); + require(applicationUrl("[::1]", "9010", "index.html") == "http://[::1]:9010/index.html"); + require(applicationUrl("0.0.0.0", "9010", "index.html") == "http://127.0.0.1:9010/index.html"); + require(applicationUrl("::", "9010", "index.html") == "http://[::1]:9010/index.html"); + require(applicationUrl("localhost", "9010", "index.html") == "http://localhost:9010/index.html"); + }); + then("addresses and ports cannot inject URL authority or shell syntax", [&] { + requireThrows([&] { + applicationUrl("", "9010", "index.html"); + }); + requireThrows([&] { + applicationUrl("127.0.0.1/evil", "9010", "index.html"); + }); + requireThrows([&] { + applicationUrl("127.0.0.1", "", "index.html"); + }); + requireThrows([&] { + applicationUrl("127.0.0.1", "90'10", "index.html"); + }); + }); + }}; const Scenario frontendURLsPreserve{"Frontend URLs preserve query and fragment syntax consistently", [] { - using webfront::frontend::detail::applicationUrl; - then("spaces and UTF-8 bytes are encoded without escaping URI delimiters", [&] { - require(applicationUrl("127.0.0.1", "9002", "folder/a b.html?x=1&name=Ren\xc3\xa9#result") - == "http://127.0.0.1:9002/folder/a%20b.html?x=1&name=Ren%C3%A9#result"); - }); - then("literal delimiters use percent escapes which are not encoded twice", [&] { - require(applicationUrl("127.0.0.1", "9002", "a%23b%3Fc%25.html") == "http://127.0.0.1:9002/a%23b%3Fc%25.html"); - require(applicationUrl("127.0.0.1", "9002", "bad%xy%.html") == "http://127.0.0.1:9002/bad%25xy%25.html"); - require(applicationUrl("127.0.0.1", "9002", "a'b.html") == "http://127.0.0.1:9002/a%27b.html"); - }); -}}; + using webfront::frontend::detail::applicationUrl; + then("spaces and UTF-8 bytes are encoded without escaping URI delimiters", [&] { + require(applicationUrl("127.0.0.1", "9002", "folder/a b.html?x=1&name=Ren\xc3\xa9#result") + == "http://127.0.0.1:9002/folder/a%20b.html?x=1&name=Ren%C3%A9#result"); + }); + then("literal delimiters use percent escapes which are not encoded twice", [&] { + require(applicationUrl("127.0.0.1", "9002", "a%23b%3Fc%25.html") == "http://127.0.0.1:9002/a%23b%3Fc%25.html"); + require(applicationUrl("127.0.0.1", "9002", "bad%xy%.html") == "http://127.0.0.1:9002/bad%25xy%25.html"); + require(applicationUrl("127.0.0.1", "9002", "a'b.html") == "http://127.0.0.1:9002/a%27b.html"); + }); + }}; diff --git a/test/unit/AutomationChannelTests.cpp b/test/unit/AutomationChannelTests.cpp index 3ebcf894..24c74376 100644 --- a/test/unit/AutomationChannelTests.cpp +++ b/test/unit/AutomationChannelTests.cpp @@ -1,6 +1,6 @@ #include "TemporaryDirectory.hpp" -#include #include +#include #include @@ -13,28 +13,28 @@ extern char** environ; #ifndef _WIN32 const Scenario privateAutomation{"Private automation directories are born owner-only under a permissive umask", [] { - webfront::test::TemporaryDirectory root; - struct RestoreMask { - mode_t previous = ::umask(0); - ~RestoreMask() { - ::umask(previous); - } - } restore; - webfront::automation::channel::PrivateDirectory directory{root.path() / "profile"}; - struct stat info{}; - require(::stat(directory.path.c_str(), &info) == 0); - require((info.st_mode & 0777) == 0700); -}}; + webfront::test::TemporaryDirectory root; + struct RestoreMask { + mode_t previous = ::umask(0); + ~RestoreMask() { + ::umask(previous); + } + } restore; + webfront::automation::channel::PrivateDirectory directory{root.path() / "profile"}; + struct stat info{}; + require(::stat(directory.path.c_str(), &info) == 0); + require((info.st_mode & 0777) == 0700); + }}; #endif const Scenario nativeAttachment{"Automation sockets cannot be inherited by renderer executables", [] { - using namespace webfront::automation; - [[maybe_unused]] channel::Runtime runtime; - const auto check = [](channel::Handle socket) { + using namespace webfront::automation; + [[maybe_unused]] channel::Runtime runtime; + const auto check = [](channel::Handle socket) { #ifdef _WIN32 - DWORD flags = HANDLE_FLAG_INHERIT; - require(GetHandleInformation(reinterpret_cast(socket), &flags)); - require((flags & HANDLE_FLAG_INHERIT) == 0); + DWORD flags = HANDLE_FLAG_INHERIT; + require(GetHandleInformation(reinterpret_cast(socket), &flags)); + require((flags & HANDLE_FLAG_INHERIT) == 0); #else require((::fcntl(socket, F_GETFD) & FD_CLOEXEC) != 0); // An actual exec must not expose a socket via the inherited descriptor table. @@ -47,122 +47,131 @@ const Scenario nativeAttachment{"Automation sockets cannot be inherited by rende require(WIFEXITED(status)); require(WEXITSTATUS(status) == 0); #endif - }; - given("a listener, its client, an accepted peer, and an adopted socket", [&] { - channel::Socket listener{channel::createSocket()}; - auto address = channel::address(0); - require(::bind(listener.value, reinterpret_cast(&address), sizeof address) == 0); - require(::listen(listener.value, 1) == 0); + }; + given("a listener, its client, an accepted peer, and an adopted socket", [&] { + channel::Socket listener{channel::createSocket()}; + auto address = channel::address(0); + require(::bind(listener.value, reinterpret_cast(&address), sizeof address) == 0); + require(::listen(listener.value, 1) == 0); #ifdef _WIN32 - int size = sizeof address; + int size = sizeof address; #else socklen_t size = sizeof address; #endif - require(::getsockname(listener.value, reinterpret_cast(&address), &size) == 0); - channel::Socket client{channel::createSocket()}; - require(::connect(client.value, reinterpret_cast(&address), sizeof address) == 0); - channel::Socket accepted{channel::acceptSocket(listener.value)}; - channel::Socket adopted{::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)}; - for (const auto socket : {listener.value, client.value, accepted.value, adopted.value}) - check(socket); - const auto transient = [](int index) { + require(::getsockname(listener.value, reinterpret_cast(&address), &size) == 0); + channel::Socket client{channel::createSocket()}; + require(::connect(client.value, reinterpret_cast(&address), sizeof address) == 0); + channel::Socket accepted{channel::acceptSocket(listener.value)}; + channel::Socket adopted{::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)}; + for (const auto socket : {listener.value, client.value, accepted.value, adopted.value}) + check(socket); + const auto transient = [](int index) { #ifdef _WIN32 - WSASetLastError(index == 0 ? WSAEINTR : WSAEWOULDBLOCK); + WSASetLastError(index == 0 ? WSAEINTR : WSAEWOULDBLOCK); #else static constexpr std::array errors{EINTR, EAGAIN, EWOULDBLOCK}; errno = errors[static_cast(index)]; #endif - }; - int writes = 0, reads = 0; - const auto until = std::chrono::steady_clock::now() + std::chrono::seconds{1}; - channel::send(client.value, "hello\n", until, [&](channel::Handle socket, std::string_view bytes) -> std::ptrdiff_t { - if (writes++ < 3) { - transient(writes - 1); - return -1; - } - return channel::SocketWrite{}(socket, bytes.substr(0, 2)); - }); - require(channel::receive(accepted.value, - 100, - until, - [&](channel::Handle socket, char* bytes, std::size_t capacity) -> std::ptrdiff_t { - if (reads++ < 3) { - transient(reads - 1); - return -1; - } - return channel::SocketRead{}(socket, bytes, std::min(capacity, std::size_t{2})); - }) - == "hello"); - require(writes >= 6); - require(reads >= 6); - requireThrows([&] { channel::send(client.value, - "never", - std::chrono::steady_clock::now() + std::chrono::milliseconds{2}, - [&](channel::Handle, std::string_view) -> int { - transient(0); - return -1; - }); }); - accepted.reset(); - requireThrows([&] { channel::receive(client.value, 100); }); - }); -}}; + }; + int writes = 0, reads = 0; + const auto until = std::chrono::steady_clock::now() + std::chrono::seconds{1}; + channel::send(client.value, "hello\n", until, [&](channel::Handle socket, std::string_view bytes) -> std::ptrdiff_t { + if (writes++ < 3) { + transient(writes - 1); + return -1; + } + return channel::SocketWrite{}(socket, bytes.substr(0, 2)); + }); + require(channel::receive(accepted.value, + 100, + until, + [&](channel::Handle socket, char* bytes, std::size_t capacity) -> std::ptrdiff_t { + if (reads++ < 3) { + transient(reads - 1); + return -1; + } + return channel::SocketRead{}(socket, bytes, std::min(capacity, std::size_t{2})); + }) + == "hello"); + require(writes >= 6); + require(reads >= 6); + requireThrows([&] { + channel::send(client.value, + "never", + std::chrono::steady_clock::now() + std::chrono::milliseconds{2}, + [&](channel::Handle, std::string_view) -> int { + transient(0); + return -1; + }); + }); + accepted.reset(); + requireThrows([&] { + channel::receive(client.value, 100); + }); + }); + }}; const Scenario nativeAttachmentCapabilities{"Automation tokens are generated by the OS and never inferred from a session ID", [] { - using namespace webfront::automation; - const auto first = channel::nonce(); - const auto second = channel::nonce(); - require(first.size() == 64); - require(first != second); - require(channel::sameToken(first, first)); - require(!channel::sameToken(first, second)); - require(!channel::sameToken(first, first.substr(1))); -}}; + using namespace webfront::automation; + const auto first = channel::nonce(); + const auto second = channel::nonce(); + require(first.size() == 64); + require(first != second); + require(channel::sameToken(first, first)); + require(!channel::sameToken(first, second)); + require(!channel::sameToken(first, first.substr(1))); + }}; const Scenario privateDirectoryRelease{"A cleaned private directory no longer removes the files of the instance that recreated it", [] { - using namespace webfront::automation; - webfront::test::TemporaryDirectory root; - const auto path = root.path() / "automation"; - { - std::optional closed{std::in_place, path}; - channel::writeEndpoint(path / "mcp.json", "closed"); - closed->cleanup(); - require(!std::filesystem::exists(path)); - channel::PrivateDirectory successor{path}; - channel::writeEndpoint(path / "mcp.json", "successor"); - closed->cleanup(); - closed.reset(); - require(std::filesystem::exists(path / "mcp.json")); - } - require(!std::filesystem::exists(path)); - { - // Without an explicit cleanup (an activation that failed after creating the directory), the destructor still removes it. - channel::PrivateDirectory failed{path}; - channel::writeEndpoint(path / "mcp.json", "failed"); - } - require(!std::filesystem::exists(path)); -}}; + using namespace webfront::automation; + webfront::test::TemporaryDirectory root; + const auto path = root.path() / "automation"; + { + std::optional closed{std::in_place, path}; + channel::writeEndpoint(path / "mcp.json", "closed"); + closed->cleanup(); + require(!std::filesystem::exists(path)); + channel::PrivateDirectory successor{path}; + channel::writeEndpoint(path / "mcp.json", "successor"); + closed->cleanup(); + closed.reset(); + require(std::filesystem::exists(path / "mcp.json")); + } + require(!std::filesystem::exists(path)); + { + // Without an explicit cleanup (an activation that failed after creating the directory), the destructor still + // removes it. + channel::PrivateDirectory failed{path}; + channel::writeEndpoint(path / "mcp.json", "failed"); + } + require(!std::filesystem::exists(path)); + }}; #ifndef _WIN32 const Scenario endpointReads{"Private file reads stay anchored to the private directory after a pathname swap", [] { - using namespace webfront::automation; - webfront::test::TemporaryDirectory root; - const auto path = root.path() / "endpoint"; - channel::PrivateDirectory original{path}; - channel::writeEndpoint(path / "endpoint.json", "original"); - channel::Descriptor pinned{::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)}; - require(pinned.value >= 0); - const auto moved = root.path() / "moved"; - std::filesystem::rename(path, moved); - channel::PrivateDirectory replacement{path}; - channel::writeEndpoint(path / "endpoint.json", "replacement"); - require(channel::readEndpointFile(pinned.value) == "original"); - require(channel::readEndpoint(path) == "replacement"); - std::filesystem::permissions(path, std::filesystem::perms::others_read, std::filesystem::perm_options::add); - requireThrows([&] { channel::readEndpoint(path); }); - std::filesystem::permissions(path, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace); - replacement.cleanup(); - std::filesystem::create_directory_symlink(moved, path); - requireThrows([&] { channel::readEndpoint(path); }); - std::filesystem::remove(path); -}}; + using namespace webfront::automation; + webfront::test::TemporaryDirectory root; + const auto path = root.path() / "endpoint"; + channel::PrivateDirectory original{path}; + channel::writeEndpoint(path / "endpoint.json", "original"); + channel::Descriptor pinned{::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)}; + require(pinned.value >= 0); + const auto moved = root.path() / "moved"; + std::filesystem::rename(path, moved); + channel::PrivateDirectory replacement{path}; + channel::writeEndpoint(path / "endpoint.json", "replacement"); + require(channel::readEndpointFile(pinned.value) == "original"); + require(channel::readEndpoint(path) == "replacement"); + std::filesystem::permissions(path, std::filesystem::perms::others_read, std::filesystem::perm_options::add); + requireThrows([&] { + channel::readEndpoint(path); + }); + std::filesystem::permissions(path, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace); + replacement.cleanup(); + std::filesystem::create_directory_symlink(moved, path); + requireThrows([&] { + channel::readEndpoint(path); + }); + std::filesystem::remove(path); + }}; #endif diff --git a/test/unit/AutomationDiscoveryTests.cpp b/test/unit/AutomationDiscoveryTests.cpp index 0c2a89e4..8d9f163e 100644 --- a/test/unit/AutomationDiscoveryTests.cpp +++ b/test/unit/AutomationDiscoveryTests.cpp @@ -1,18 +1,18 @@ #include "TemporaryDirectory.hpp" -#include #include #include +#include #include #ifndef _WIN32 -#include + #include #endif #include #include #include #include -#include #include +#include using namespace webfront::bdd; @@ -33,7 +33,7 @@ struct ConsumerApp { return a.value == b.value; } }; - std::filesystem::path project; + std::filesystem::path project; std::vector registered{}; template void cppFunction(std::string_view name, Handler) { @@ -51,8 +51,8 @@ struct ConsumerApp { }; std::string read(const std::filesystem::path& path) { - std::ifstream input(path, std::ios::binary); - std::ostringstream text; + std::ifstream input(path, std::ios::binary); + std::ostringstream text; text << input.rdbuf(); return text.str(); } @@ -70,234 +70,257 @@ constexpr long deadProcess = 2147483000L; } // namespace const Scenario recordReader{"A record that a reader holds open is still withdrawn", [] { - webfront::test::TemporaryDirectory root; - given("a registration whose record is open in a reader, as `list` reads it", [&] { - const auto directory = root.path() / "sessions"; - discovery::Registration registration{directory, entry("alpha")}; - const auto record = directory / "alpha.json"; - auto reader = std::make_unique(record, std::ios::binary); - require(reader->is_open()); - // Windows refuses to delete a file that is open without shared deletion: the withdrawal waits for the reader. - std::thread release{[&reader] { - std::this_thread::sleep_for(std::chrono::milliseconds{100}); - reader.reset(); - }}; - when("the session is withdrawn while the reader still holds it", [&] { - registration.remove(); - release.join(); - then("the record is gone and no session is listed", [&] { - require(!std::filesystem::exists(record)); - require(discovery::list(directory).empty()); - }); - }); - }); -}}; + webfront::test::TemporaryDirectory root; + given("a registration whose record is open in a reader, as `list` reads it", [&] { + const auto directory = root.path() / "sessions"; + discovery::Registration registration{directory, entry("alpha")}; + const auto record = directory / "alpha.json"; + auto reader = std::make_unique(record, std::ios::binary); + require(reader->is_open()); + // Windows refuses to delete a file that is open without shared deletion: the withdrawal waits for the reader. + std::thread release{[&reader] { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + reader.reset(); + }}; + when("the session is withdrawn while the reader still holds it", [&] { + registration.remove(); + release.join(); + then("the record is gone and no session is listed", [&] { + require(!std::filesystem::exists(record)); + require(discovery::list(directory).empty()); + }); + }); + }); + }}; const Scenario sharedSession{"A shared session is listed with its grants and never with its capability", [] { - webfront::test::TemporaryDirectory root; - given("a registration in a discovery directory", [&] { - const auto directory = root.path() / "sessions"; - { - discovery::Registration registration{directory, entry("alpha")}; - when("the sessions are listed", [&] { - const auto listed = discovery::list(directory); - then("the session carries its project, grants, process and endpoint", [&] { - require(listed.size() == 1); - require(listed[0].session == "alpha"); - require(listed[0].project == "/work/project"); - require(listed[0].endpoint == "/work/endpoint"); - require(listed[0].allow == "[\"check\",\"build\"]"); - require(listed[0].pid == discovery::currentProcess()); - }); - then("the record has the contract's members and no secret", [&] { - const Object printed{listed[0].json(), 64000}; - require(printed.raw("version") == "1"); - require(printed.string("state") == "running"); - require(listed[0].json().find("token") == std::string::npos); - require(listed[0].json().find("capability") == std::string::npos); - }); - }); - } - then("closing the registration withdraws the record", [&] { - require(discovery::list(directory).empty()); - require(std::filesystem::is_empty(directory)); - }); - }); - given("no discovery directory", [&] { - then("nothing is listed and nothing is created", [&] { - require(discovery::list(root.path() / "absent").empty()); - require(!std::filesystem::exists(root.path() / "absent")); - }); - }); + webfront::test::TemporaryDirectory root; + given("a registration in a discovery directory", [&] { + const auto directory = root.path() / "sessions"; + { + discovery::Registration registration{directory, entry("alpha")}; + when("the sessions are listed", [&] { + const auto listed = discovery::list(directory); + then("the session carries its project, grants, process and endpoint", [&] { + require(listed.size() == 1); + require(listed[0].session == "alpha"); + require(listed[0].project == "/work/project"); + require(listed[0].endpoint == "/work/endpoint"); + require(listed[0].allow == "[\"check\",\"build\"]"); + require(listed[0].pid == discovery::currentProcess()); + }); + then("the record has the contract's members and no secret", [&] { + const Object printed{listed[0].json(), 64000}; + require(printed.raw("version") == "1"); + require(printed.string("state") == "running"); + require(listed[0].json().find("token") == std::string::npos); + require(listed[0].json().find("capability") == std::string::npos); + }); + }); + } + then("closing the registration withdraws the record", [&] { + require(discovery::list(directory).empty()); + require(std::filesystem::is_empty(directory)); + }); + }); + given("no discovery directory", [&] { + then("nothing is listed and nothing is created", [&] { + require(discovery::list(root.path() / "absent").empty()); + require(!std::filesystem::exists(root.path() / "absent")); + }); + }); #ifndef _WIN32 - given("a new discovery directory", [&] { - const auto directory = root.path() / "sessions"; - discovery::Registration registration{directory, entry("alpha")}; - then("it is created private to the user", [&] { - struct stat info{}; - require(::stat(directory.c_str(), &info) == 0); - require((info.st_mode & 0777) == 0700); - }); - }); - given("a new discovery directory written with a trailing separator", [&] { - const auto directory = root.path() / "slash"; - discovery::Registration registration{std::filesystem::path{directory.string() + "/"}, entry("alpha")}; - then("it is still new, hence private, and not refused as an existing shared one", [&] { - struct stat info{}; - require(::stat(directory.c_str(), &info) == 0); - require((info.st_mode & 0777) == 0700); - }); - }); - given("an existing directory that other users can read", [&] { - const auto directory = root.path() / "shared"; - std::filesystem::create_directory(directory); - require(::chmod(directory.c_str(), 0755) == 0); - std::ofstream{directory / "previous.txt"} << "dropped earlier"; - then("it is refused, with its permissions and files left as they were", [&] { - requireThrows([&] { discovery::Registration(directory, entry("alpha")); }); - struct stat info{}; - require(::stat(directory.c_str(), &info) == 0); - require((info.st_mode & 0777) == 0755); - require(std::filesystem::exists(directory / "previous.txt")); - require(!std::filesystem::exists(directory / "alpha.json")); - }); - }); - given("an existing directory that is already private", [&] { - const auto directory = root.path() / "private"; - std::filesystem::create_directory(directory); - require(::chmod(directory.c_str(), 0700) == 0); - then("it is used", [&] { - discovery::Registration registration{directory, entry("alpha")}; - require(discovery::list(directory).size() == 1); - }); - }); + given("a new discovery directory", [&] { + const auto directory = root.path() / "sessions"; + discovery::Registration registration{directory, entry("alpha")}; + then("it is created private to the user", [&] { + struct stat info{}; + require(::stat(directory.c_str(), &info) == 0); + require((info.st_mode & 0777) == 0700); + }); + }); + given("a new discovery directory written with a trailing separator", [&] { + const auto directory = root.path() / "slash"; + discovery::Registration registration{std::filesystem::path{directory.string() + "/"}, entry("alpha")}; + then("it is still new, hence private, and not refused as an existing shared one", [&] { + struct stat info{}; + require(::stat(directory.c_str(), &info) == 0); + require((info.st_mode & 0777) == 0700); + }); + }); + given("an existing directory that other users can read", [&] { + const auto directory = root.path() / "shared"; + std::filesystem::create_directory(directory); + require(::chmod(directory.c_str(), 0755) == 0); + std::ofstream{directory / "previous.txt"} << "dropped earlier"; + then("it is refused, with its permissions and files left as they were", [&] { + requireThrows([&] { + discovery::Registration(directory, entry("alpha")); + }); + struct stat info{}; + require(::stat(directory.c_str(), &info) == 0); + require((info.st_mode & 0777) == 0755); + require(std::filesystem::exists(directory / "previous.txt")); + require(!std::filesystem::exists(directory / "alpha.json")); + }); + }); + given("an existing directory that is already private", [&] { + const auto directory = root.path() / "private"; + std::filesystem::create_directory(directory); + require(::chmod(directory.c_str(), 0700) == 0); + then("it is used", [&] { + discovery::Registration registration{directory, entry("alpha")}; + require(discovery::list(directory).size() == 1); + }); + }); #endif -}}; + }}; const Scenario discoveryDirectory{"A discovery directory only lists live, well-formed records", [] { - webfront::test::TemporaryDirectory root; - const auto directory = root.path() / "sessions"; - discovery::Registration live{directory, entry("live")}; - given("a record whose process is gone", [&] { - discovery::Registration stale{directory, entry("stale", deadProcess)}; - when("the sessions are listed", [&] { - const auto listed = discovery::list(directory, false); - then("it is not listed, and `prune` decides whether it is removed", [&] { - require(listed.size() == 1); - require(listed[0].session == "live"); - require(std::filesystem::exists(directory / "stale.json")); - require(discovery::list(directory).size() == 1); - require(!std::filesystem::exists(directory / "stale.json")); + webfront::test::TemporaryDirectory root; + const auto directory = root.path() / "sessions"; + discovery::Registration live{directory, entry("live")}; + given("a record whose process is gone", [&] { + discovery::Registration stale{directory, entry("stale", deadProcess)}; + when("the sessions are listed", [&] { + const auto listed = discovery::list(directory, false); + then("it is not listed, and `prune` decides whether it is removed", [&] { + require(listed.size() == 1); + require(listed[0].session == "live"); + require(std::filesystem::exists(directory / "stale.json")); + require(discovery::list(directory).size() == 1); + require(!std::filesystem::exists(directory / "stale.json")); + }); + }); + }); + given("malformed, foreign and mismatched files", [&] { + write(directory / "garbage.json", "{not json"); + write(directory / "notes.txt", "{}"); + write(directory / "bad name.json", entry("bad").json()); + write(directory / "other.json", entry("someone-else").json()); // the file name must be the session + write(directory / "huge.json", std::string(discovery::recordLimit + 1, ' ')); + write(directory / "noPid.json", + "{\"version\":1,\"session\":\"noPid\",\"project\":\"p\",\"endpoint\":\"e\",\"allow\":[]}"); + when("the sessions are listed", [&] { + const auto listed = discovery::list(directory); + then("only the real session appears, and the files are left alone", [&] { + require(listed.size() == 1); + require(listed[0].session == "live"); + for (const auto name : + {"garbage.json", "notes.txt", "bad name.json", "other.json", "huge.json", "noPid.json"}) { + auto scope = info(name); + require(std::filesystem::exists(directory / name)); + } + }); + }); + }); + given("an identifier that is not a plain name", [&] { + then("it is refused before any path is built", [&] { + for (const auto* id : {"", "../escape", "a/b", "a.b", "with space"}) + requireThrows([&] { + discovery::Registration(directory, entry(id)); + }); + require(!std::filesystem::exists(root.path() / "escape.json")); + }); + }); + }}; + +const Scenario consumerEnables{ + "A consumer enables automation explicitly, with fixed grants and a visible endpoint", + [] { + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + ConsumerApp app{.project = root.path() / "project"}; + const auto sessions = root.path() / "sessions"; + given("an application that never enables automation", [&] { + then("no automation callback is registered", [&] { + require(app.registered.empty()); }); }); - }); - given("malformed, foreign and mismatched files", [&] { - write(directory / "garbage.json", "{not json"); - write(directory / "notes.txt", "{}"); - write(directory / "bad name.json", entry("bad").json()); - write(directory / "other.json", entry("someone-else").json()); // the file name must be the session - write(directory / "huge.json", std::string(discovery::recordLimit + 1, ' ')); - write(directory / "noPid.json", "{\"version\":1,\"session\":\"noPid\",\"project\":\"p\",\"endpoint\":\"e\",\"allow\":[]}"); - when("the sessions are listed", [&] { - const auto listed = discovery::list(directory); - then("only the real session appears, and the files are left alone", [&] { - require(listed.size() == 1); - require(listed[0].session == "live"); - for (const auto name : {"garbage.json", "notes.txt", "bad name.json", "other.json", "huge.json", "noPid.json"}) { - auto scope = info(name); - require(std::filesystem::exists(directory / name)); - } + given("a refused configuration", [&] { + then("an unknown grant and a private directory inside the project are both refused", [&] { + requireThrows([&] { + enableAutomation(app, {.grants = {"shell"}, .directory = root.path() / "endpoint", .discovery = sessions, .announce = false}); + }); + requireThrows([&] { + enableAutomation(app, {.grants = {"check"}, .directory = root.path() / "project" / "endpoint", .discovery = sessions, .announce = false}); + }); + require(!std::filesystem::exists(root.path() / "endpoint")); + require(discovery::list(sessions).empty()); + // A refused activation leaves nothing behind in the application: no callback without an object to close them. + require(app.registered.empty()); }); - }); - }); - given("an identifier that is not a plain name", [&] { - then("it is refused before any path is built", [&] { - for (const auto* id : {"", "../escape", "a/b", "a.b", "with space"}) - requireThrows([&] { discovery::Registration(directory, entry(id)); }); - require(!std::filesystem::exists(root.path() / "escape.json")); - }); - }); -}}; - -const Scenario consumerEnables{"A consumer enables automation explicitly, with fixed grants and a visible endpoint", [] { - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - ConsumerApp app{.project = root.path() / "project"}; - const auto sessions = root.path() / "sessions"; - given("an application that never enables automation", [&] { - then("no automation callback is registered", [&] { - require(app.registered.empty()); - }); - }); - given("a refused configuration", [&] { - then("an unknown grant and a private directory inside the project are both refused", [&] { - requireThrows([&] { enableAutomation(app, {.grants = {"shell"}, .directory = root.path() / "endpoint", .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.grants = {"check"}, .directory = root.path() / "project" / "endpoint", .discovery = sessions, .announce = false}); }); - require(!std::filesystem::exists(root.path() / "endpoint")); - require(discovery::list(sessions).empty()); - // A refused activation leaves nothing behind in the application: no callback without an object to close them. - require(app.registered.empty()); - }); - then("a discovery directory that is refused after the private directory was accepted registers nothing either", [&] { + then("a discovery directory that is refused after the private directory was accepted registers nothing either", [&] { #ifndef _WIN32 - const auto shared = root.path() / "shared"; - std::filesystem::create_directory(shared); - require(::chmod(shared.c_str(), 0755) == 0); - requireThrows([&] { enableAutomation(app, {.grants = {"check"}, .directory = root.path() / "endpoint2", .discovery = shared, .announce = false}); }); - require(app.registered.empty()); + const auto shared = root.path() / "shared"; + std::filesystem::create_directory(shared); + require(::chmod(shared.c_str(), 0755) == 0); + requireThrows([&] { + enableAutomation(app, {.grants = {"check"}, .directory = root.path() / "endpoint2", .discovery = shared, .announce = false}); + }); + require(app.registered.empty()); #endif + }); }); - }); - given("automation enabled with check and inspect", [&] { - const auto endpoint = root.path() / "endpoint"; - auto automation = enableAutomation(app, {.grants = {"check", "inspect"}, .directory = endpoint, .discovery = sessions, .announce = false}); - then("the application's own callbacks stay and the automation ones are added", [&] { - require(std::ranges::find(app.registered, "webfront.automation.claim") != app.registered.end()); - require(std::ranges::find(app.registered, "webfront.automation.poll") != app.registered.end()); - }); - then("the session is discoverable and names its directory, its URL and the grants", [&] { - const auto listed = discovery::list(sessions); - require(listed.size() == 1); - require(listed[0].allow == "[\"check\",\"inspect\"]"); - require(std::filesystem::equivalent(listed[0].endpoint, endpoint)); - require(listed[0].mcp == automation->mcpUrl()); - require(std::filesystem::exists(endpoint / "mcp.json")); - const Object configuration{read(endpoint / "mcp.json")}; - const auto authorization = Object(Object(Object(configuration.raw("mcpServers")).raw("webfront")).raw("headers")).string("Authorization"); - require(authorization.starts_with("Bearer ")); - const auto token = authorization.substr(7); - require(token.size() == 64); - require(std::ranges::all_of(token, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); })); - require(read(sessions / (listed[0].session + ".json")).find(token) == std::string::npos); - }); - then("the launch page carries the single-use claim and the banner states the grants without a secret", [&] { - const auto page = automation->launchPage(); - require(page.starts_with("webfront-bootstrap.html#webfront-automation=")); - const auto banner = automation->banner(); - require(banner.find("check, inspect") != std::string::npos); - require(banner.find(automation->mcpUrl()) != std::string::npos); - require(banner.find(page.substr(page.find('=') + 1)) == std::string::npos); - require(automation->windowTitle("Board").find("automation") != std::string::npos); - }); - then("an operation that was not granted is refused and audited", [&] { - const auto id = Object(automation->controller()->describe()).string("session"); - const Object request{objectJson({ - { "session", webfront::json::quote(id)}, - {"operation", webfront::json::quote("build")}, - {"arguments", "{}"} - })}; - requireThrows([&] { automation->controller()->start(request); }); - require(automation->controller()->describe().find("\"denied\"") != std::string::npos); - }); - then("closing revokes the session and withdraws the record and the private directory, once or repeatedly", [&] { - automation->close(); - automation->close(); - require(automation->controller()->isClosed()); - require(discovery::list(sessions).empty()); - require(!std::filesystem::exists(endpoint)); + given("automation enabled with check and inspect", [&] { + const auto endpoint = root.path() / "endpoint"; + auto automation = enableAutomation(app, + { + .grants = {"check", "inspect"}, + .directory = endpoint, + .discovery = sessions, + .announce = false + }); + then("the application's own callbacks stay and the automation ones are added", [&] { + require(std::ranges::find(app.registered, "webfront.automation.claim") != app.registered.end()); + require(std::ranges::find(app.registered, "webfront.automation.poll") != app.registered.end()); + }); + then("the session is discoverable and names its directory, its URL and the grants", [&] { + const auto listed = discovery::list(sessions); + require(listed.size() == 1); + require(listed[0].allow == "[\"check\",\"inspect\"]"); + require(std::filesystem::equivalent(listed[0].endpoint, endpoint)); + require(listed[0].mcp == automation->mcpUrl()); + require(std::filesystem::exists(endpoint / "mcp.json")); + const Object configuration{read(endpoint / "mcp.json")}; + const auto authorization = Object(Object(Object(configuration.raw("mcpServers")).raw("webfront")).raw("headers")).string("Authorization"); + require(authorization.starts_with("Bearer ")); + const auto token = authorization.substr(7); + require(token.size() == 64); + require(std::ranges::all_of(token, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + })); + require(read(sessions / (listed[0].session + ".json")).find(token) == std::string::npos); + }); + then("the launch page carries the single-use claim and the banner states the grants without a secret", [&] { + const auto page = automation->launchPage(); + require(page.starts_with("webfront-bootstrap.html#webfront-automation=")); + const auto banner = automation->banner(); + require(banner.find("check, inspect") != std::string::npos); + require(banner.find(automation->mcpUrl()) != std::string::npos); + require(banner.find(page.substr(page.find('=') + 1)) == std::string::npos); + require(automation->windowTitle("Board").find("automation") != std::string::npos); + }); + then("an operation that was not granted is refused and audited", [&] { + const auto id = Object(automation->controller()->describe()).string("session"); + const Object request{ + objectJson({{"session", webfront::json::quote(id)}, {"operation", webfront::json::quote("build")}, {"arguments", "{}"}} + ) + }; + requireThrows([&] { + automation->controller()->start(request); + }); + require(automation->controller()->describe().find("\"denied\"") != std::string::npos); + }); + then("closing revokes the session and withdraws the record and the private directory, once or repeatedly", [&] { + automation->close(); + automation->close(); + require(automation->controller()->isClosed()); + require(discovery::list(sessions).empty()); + require(!std::filesystem::exists(endpoint)); + }); }); - }); -}}; + }}; namespace { // A renderer running `while (true) {}` never executes the window.close() the supervisor injects: the page never polls @@ -305,8 +328,8 @@ namespace { Object checkRequest(const Session& session) { return Object(objectJson({ { "session", webfront::json::quote(Object(session.describe()).string("session"))}, - {"operation", webfront::json::quote("check")}, - {"arguments", "{}"} + {"operation", webfront::json::quote("check")}, + {"arguments", "{}"} })); } @@ -352,241 +375,245 @@ void awaitCloseGrace(const auto& automation) { } // namespace const Scenario windowIgnores{"A window that ignores the deadline's close request is declared unresponsive by the consumer's automation", [] { - SupervisorClock::reset(); - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - ConsumerApp app{.project = root.path() / "project"}; - const auto sessions = root.path() / "sessions"; - std::atomic unresponsive{0}; - const auto enable = [&](std::chrono::milliseconds grace, std::chrono::seconds startup = std::chrono::seconds{120}) { - return std::make_unique>( - app, - AutomationOptions{.grants = {"check"}, - .directory = root.path() / ("endpoint" + std::to_string(grace.count())), - .discovery = sessions, - .timeout = std::chrono::seconds{1}, - .startupTimeout = startup, - .closeGrace = grace, - .onUnresponsive = - [&] { - ++unresponsive; - }, - .announce = false}); - }; - given("an operation that never completes and a window that never closes", [&] { - auto automation = enable(std::chrono::milliseconds{100}); - automation->controller()->poll(); // the page is ready, then stops polling - automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); - then("past the deadline and the grace, the record and endpoint are withdrawn and the owner is told", [&] { - advanceSupervisor(std::chrono::milliseconds{999}); - require(!automation->controller()->isClosed()); - advanceSupervisor(std::chrono::milliseconds{1}); - awaitCloseGrace(automation); - advanceSupervisor(std::chrono::milliseconds{99}); - require(unresponsive.load() == 0); - advanceSupervisor(std::chrono::milliseconds{1}); - requireEventually([&] { - return unresponsive.load() == 1; - }); - require(automation->controller()->isClosed()); - require(discovery::list(sessions).empty()); - require(!std::filesystem::exists(automation->directory() / "mcp.json")); - }); - }); - given("a window that does close within the grace after the deadline", [&] { - auto automation = enable(std::chrono::seconds{30}); - automation->controller()->poll(); - automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); - advanceSupervisor(std::chrono::seconds{1}); - awaitCloseGrace(automation); - when("the application ends show() and closes the automation", [&] { - automation->close(); - then("it is never declared unresponsive", [&] { - // close() joined the supervisor: a later callback is impossible, without a timed observation. - require(unresponsive.load() == 0); - }); - }); - }); - given("an attached client's explicit shutdown that a stuck renderer ignores", [&] { - auto automation = enable(std::chrono::milliseconds{100}); - automation->controller()->poll(); - automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); - // --shutdown closes the session and clears the active operation: its deadline can no longer expire. - automation->controller()->close("Shutdown requested by an attached client"); - then("the window is still declared unresponsive after the grace", [&] { - awaitCloseGrace(automation); - advanceSupervisor(std::chrono::milliseconds{100}); - requireEventually([&] { - return unresponsive.load() == 1; - }); - require(discovery::list(sessions).empty()); - }); - }); - given("a renderer blocked before its first poll, so that no operation can expire", [&] { - auto automation = enable(std::chrono::milliseconds{100}, std::chrono::seconds{1}); - then("the startup deadline revokes the session and the unresponsive window is declared after the grace", [&] { - advanceSupervisor(std::chrono::milliseconds{999}); - require(!automation->controller()->isClosed()); - advanceSupervisor(std::chrono::milliseconds{1}); - awaitCloseGrace(automation); - advanceSupervisor(std::chrono::milliseconds{99}); - require(unresponsive.load() == 0); - advanceSupervisor(std::chrono::milliseconds{1}); - requireEventually([&] { - return unresponsive.load() == 1; - }); - require(automation->controller()->isClosed()); - require(discovery::list(sessions).empty()); - require(!std::filesystem::exists(automation->directory() / "mcp.json")); - }); - }); - given("a window that claims the session before the startup deadline", [&] { - auto automation = enable(std::chrono::milliseconds{100}, std::chrono::seconds{1}); - automation->controller()->poll(); - then("an idle session is not revoked by the startup deadline", [&] { - advanceSupervisor(std::chrono::milliseconds{1500}); - require(!automation->controller()->isClosed()); - require(unresponsive.load() == 0); - }); - }); - given("the window closing: its connection is lost and show() returns within the grace", [&] { - auto automation = enable(std::chrono::seconds{30}); - automation->controller()->close("Developer window disconnected"); - then("the record and the endpoint are withdrawn at once, and closing the automation confirms the window is gone", [&] { - requireEventually([&] { - return discovery::list(sessions).empty(); - }); - // Windows refuses to look at a file whose removal is pending: that is the withdrawal under way, not a failure. - requireEventually([&] { - std::error_code pending; - return !std::filesystem::exists(automation->directory() / "mcp.json", pending); - }); - automation->close(); - require(unresponsive.load() == 0); - }); - }); - given("a lost connection that leaves the native window open", [&] { - auto automation = enable(std::chrono::milliseconds{100}); - // A navigation or a broken WebSocket: window.close() cannot reach the page, and show() does not return. - automation->controller()->close("Developer window disconnected"); - then("the withdrawal is immediate and the window is still declared unresponsive after the grace", [&] { - awaitCloseGrace(automation); - requireEventually([&] { - return discovery::list(sessions).empty(); - }); - advanceSupervisor(std::chrono::milliseconds{100}); - requireEventually([&] { - return unresponsive.load() == 1; - }); - }); - }); -}}; + SupervisorClock::reset(); + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + ConsumerApp app{.project = root.path() / "project"}; + const auto sessions = root.path() / "sessions"; + std::atomic unresponsive{0}; + const auto enable = [&](std::chrono::milliseconds grace, std::chrono::seconds startup = std::chrono::seconds{120}) { + return std::make_unique>( + app, + AutomationOptions{.grants = {"check"}, + .directory = root.path() / ("endpoint" + std::to_string(grace.count())), + .discovery = sessions, + .timeout = std::chrono::seconds{1}, + .startupTimeout = startup, + .closeGrace = grace, + .onUnresponsive = + [&] { + ++unresponsive; + }, + .announce = false}); + }; + given("an operation that never completes and a window that never closes", [&] { + auto automation = enable(std::chrono::milliseconds{100}); + automation->controller()->poll(); // the page is ready, then stops polling + automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); + then("past the deadline and the grace, the record and endpoint are withdrawn and the owner is told", [&] { + advanceSupervisor(std::chrono::milliseconds{999}); + require(!automation->controller()->isClosed()); + advanceSupervisor(std::chrono::milliseconds{1}); + awaitCloseGrace(automation); + advanceSupervisor(std::chrono::milliseconds{99}); + require(unresponsive.load() == 0); + advanceSupervisor(std::chrono::milliseconds{1}); + requireEventually([&] { + return unresponsive.load() == 1; + }); + require(automation->controller()->isClosed()); + require(discovery::list(sessions).empty()); + require(!std::filesystem::exists(automation->directory() / "mcp.json")); + }); + }); + given("a window that does close within the grace after the deadline", [&] { + auto automation = enable(std::chrono::seconds{30}); + automation->controller()->poll(); + automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); + advanceSupervisor(std::chrono::seconds{1}); + awaitCloseGrace(automation); + when("the application ends show() and closes the automation", [&] { + automation->close(); + then("it is never declared unresponsive", [&] { + // close() joined the supervisor: a later callback is impossible, without a timed observation. + require(unresponsive.load() == 0); + }); + }); + }); + given("an attached client's explicit shutdown that a stuck renderer ignores", [&] { + auto automation = enable(std::chrono::milliseconds{100}); + automation->controller()->poll(); + automation->controller()->start(checkRequest(*automation->controller()), SupervisorClock::value()); + // --shutdown closes the session and clears the active operation: its deadline can no longer expire. + automation->controller()->close("Shutdown requested by an attached client"); + then("the window is still declared unresponsive after the grace", [&] { + awaitCloseGrace(automation); + advanceSupervisor(std::chrono::milliseconds{100}); + requireEventually([&] { + return unresponsive.load() == 1; + }); + require(discovery::list(sessions).empty()); + }); + }); + given("a renderer blocked before its first poll, so that no operation can expire", [&] { + auto automation = enable(std::chrono::milliseconds{100}, std::chrono::seconds{1}); + then("the startup deadline revokes the session and the unresponsive window is declared after the grace", [&] { + advanceSupervisor(std::chrono::milliseconds{999}); + require(!automation->controller()->isClosed()); + advanceSupervisor(std::chrono::milliseconds{1}); + awaitCloseGrace(automation); + advanceSupervisor(std::chrono::milliseconds{99}); + require(unresponsive.load() == 0); + advanceSupervisor(std::chrono::milliseconds{1}); + requireEventually([&] { + return unresponsive.load() == 1; + }); + require(automation->controller()->isClosed()); + require(discovery::list(sessions).empty()); + require(!std::filesystem::exists(automation->directory() / "mcp.json")); + }); + }); + given("a window that claims the session before the startup deadline", [&] { + auto automation = enable(std::chrono::milliseconds{100}, std::chrono::seconds{1}); + automation->controller()->poll(); + then("an idle session is not revoked by the startup deadline", [&] { + advanceSupervisor(std::chrono::milliseconds{1500}); + require(!automation->controller()->isClosed()); + require(unresponsive.load() == 0); + }); + }); + given("the window closing: its connection is lost and show() returns within the grace", [&] { + auto automation = enable(std::chrono::seconds{30}); + automation->controller()->close("Developer window disconnected"); + then("the record and the endpoint are withdrawn at once, and closing the automation confirms the window is gone", [&] { + requireEventually([&] { + return discovery::list(sessions).empty(); + }); + // Windows refuses to look at a file whose removal is pending: that is the withdrawal under way, not a failure. + requireEventually([&] { + std::error_code pending; + return !std::filesystem::exists(automation->directory() / "mcp.json", pending); + }); + automation->close(); + require(unresponsive.load() == 0); + }); + }); + given("a lost connection that leaves the native window open", [&] { + auto automation = enable(std::chrono::milliseconds{100}); + // A navigation or a broken WebSocket: window.close() cannot reach the page, and show() does not return. + automation->controller()->close("Developer window disconnected"); + then("the withdrawal is immediate and the window is still declared unresponsive after the grace", [&] { + awaitCloseGrace(automation); + requireEventually([&] { + return discovery::list(sessions).empty(); + }); + advanceSupervisor(std::chrono::milliseconds{100}); + requireEventually([&] { + return unresponsive.load() == 1; + }); + }); + }); + }}; const Scenario defaultAutomation{"The default automation clock supervises a renderer that never becomes ready", [] { - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - ConsumerApp app{.project = root.path() / "project"}; - std::atomic unresponsive{false}; - auto automation = enableAutomation(app, - {.directory = root.path() / "endpoint", - .discovery = root.path() / "sessions", - .startupTimeout = std::chrono::seconds{1}, - .closeGrace = std::chrono::milliseconds{10}, - .onUnresponsive = - [&] { - unresponsive = true; - }, - .announce = false}); - requireEventually([&] { - return unresponsive.load(); - }); - require(automation->controller()->isClosed()); - require(discovery::list(root.path() / "sessions").empty()); -}}; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + ConsumerApp app{.project = root.path() / "project"}; + std::atomic unresponsive{false}; + auto automation = enableAutomation(app, + {.directory = root.path() / "endpoint", + .discovery = root.path() / "sessions", + .startupTimeout = std::chrono::seconds{1}, + .closeGrace = std::chrono::milliseconds{10}, + .onUnresponsive = + [&] { + unresponsive = true; + }, + .announce = false}); + requireEventually([&] { + return unresponsive.load(); + }); + require(automation->controller()->isClosed()); + require(discovery::list(root.path() / "sessions").empty()); + }}; const Scenario startupDeadlineSaturates{"A delay too large for the clock never expires, whatever the clock origin", [] { - using namespace std::chrono; - const auto now = steady_clock::now(); - const auto negative = steady_clock::time_point{steady_clock::duration{-1'000'000'000'000}}; - const auto limit = steady_clock::time_point::max(); - given("an ordinary timeout", [&] { - then("the deadline is the origin plus the timeout, for a positive or a negative origin", [&] { - check(startupDeadline(now, seconds{30}) == now + seconds{30}); - check(startupDeadline(negative, seconds{30}) == negative + seconds{30}); - check(deadlineAfter(now, milliseconds{100}) == now + milliseconds{100}); - }); - }); - given("a zero or negative delay", [&] { - then("the deadline is the origin itself", [&] { - check(startupDeadline(negative, seconds{0}) == negative); - check(startupDeadline(now, seconds{-5}) == now); - check(deadlineAfter(negative, milliseconds{-1}) == negative); - }); - }); - given("the largest representable delay", [&] { - then("the deadline saturates instead of overflowing into the past", [&] { - check(startupDeadline(now, seconds::max()) == limit); - check(startupDeadline(negative, seconds::max()) == limit); - check(startupDeadline(steady_clock::time_point::min(), seconds::max()) == limit); - check(deadlineAfter(now, milliseconds::max()) == limit); - check(deadlineAfter(negative, milliseconds::max()) == limit); - }); - }); - given("a delay beyond the clock's tick range from an origin that makes the deadline representable", [&] { - then("the deadline is exact instead of overflowing in the conversion", [&] { - if constexpr (std::is_same_v && sizeof(steady_clock::rep) == 8) { - const auto from = steady_clock::time_point::min(); - // min() + 1e10 s = -9223372036854775808 + 1e19 ticks - check(deadlineAfter(from, seconds{10'000'000'000}) == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}}); - check(deadlineAfter(from, milliseconds{10'000'000'000'000}) == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}}); - } - }); - }); -}}; + using namespace std::chrono; + const auto now = steady_clock::now(); + const auto negative = steady_clock::time_point{steady_clock::duration{-1'000'000'000'000}}; + const auto limit = steady_clock::time_point::max(); + given("an ordinary timeout", [&] { + then("the deadline is the origin plus the timeout, for a positive or a negative origin", [&] { + check(startupDeadline(now, seconds{30}) == now + seconds{30}); + check(startupDeadline(negative, seconds{30}) == negative + seconds{30}); + check(deadlineAfter(now, milliseconds{100}) == now + milliseconds{100}); + }); + }); + given("a zero or negative delay", [&] { + then("the deadline is the origin itself", [&] { + check(startupDeadline(negative, seconds{0}) == negative); + check(startupDeadline(now, seconds{-5}) == now); + check(deadlineAfter(negative, milliseconds{-1}) == negative); + }); + }); + given("the largest representable delay", [&] { + then("the deadline saturates instead of overflowing into the past", [&] { + check(startupDeadline(now, seconds::max()) == limit); + check(startupDeadline(negative, seconds::max()) == limit); + check(startupDeadline(steady_clock::time_point::min(), seconds::max()) == limit); + check(deadlineAfter(now, milliseconds::max()) == limit); + check(deadlineAfter(negative, milliseconds::max()) == limit); + }); + }); + given("a delay beyond the clock's tick range from an origin that makes the deadline representable", [&] { + then("the deadline is exact instead of overflowing in the conversion", [&] { + if constexpr (std::is_same_v && sizeof(steady_clock::rep) == 8) { + const auto from = steady_clock::time_point::min(); + // min() + 1e10 s = -9223372036854775808 + 1e19 ticks + check(deadlineAfter(from, seconds{10'000'000'000}) + == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}}); + check(deadlineAfter(from, milliseconds{10'000'000'000'000}) + == steady_clock::time_point{nanoseconds{776'627'963'145'224'192LL}}); + } + }); + }); + }}; -const Scenario unboundedDelaysKeepTheSession{"Unbounded startup and grace options neither revoke the session nor end the window", [] { - SupervisorClock::reset(); - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - ConsumerApp app{.project = root.path() / "project"}; - std::atomic unresponsive{0}; - const auto options = [&](std::chrono::seconds startup, std::chrono::milliseconds grace) { - return AutomationOptions{.grants = {"check"}, - .directory = root.path() / "endpoint", - .discovery = root.path() / "sessions", - .startupTimeout = startup, - .closeGrace = grace, - .onUnresponsive = - [&] { - ++unresponsive; - }, - .announce = false}; - }; - given("a startup timeout of seconds::max()", [&] { - Automation automation{app, options(std::chrono::seconds::max(), std::chrono::milliseconds{100})}; - then("a window that never claims the session is not revoked", [&] { - advanceSupervisor(std::chrono::hours{24}); - require(!automation.controller()->isClosed()); - require(unresponsive.load() == 0); - }); - }); - given("a close grace of milliseconds::max()", [&] { - Automation automation{app, options(std::chrono::seconds{120}, std::chrono::milliseconds::max())}; - automation.controller()->close("Developer window disconnected"); - awaitCloseGrace(&automation); - then("the window is never declared unresponsive", [&] { - advanceSupervisor(std::chrono::hours{24}); - require(unresponsive.load() == 0); +const Scenario unboundedDelaysKeepTheSession{ + "Unbounded startup and grace options neither revoke the session nor end the window", + [] { + SupervisorClock::reset(); + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + ConsumerApp app{.project = root.path() / "project"}; + std::atomic unresponsive{0}; + const auto options = [&](std::chrono::seconds startup, std::chrono::milliseconds grace) { + return AutomationOptions{.grants = {"check"}, + .directory = root.path() / "endpoint", + .discovery = root.path() / "sessions", + .startupTimeout = startup, + .closeGrace = grace, + .onUnresponsive = + [&] { + ++unresponsive; + }, + .announce = false}; + }; + given("a startup timeout of seconds::max()", [&] { + Automation automation{app, options(std::chrono::seconds::max(), std::chrono::milliseconds{100})}; + then("a window that never claims the session is not revoked", [&] { + advanceSupervisor(std::chrono::hours{24}); + require(!automation.controller()->isClosed()); + require(unresponsive.load() == 0); + }); }); - }); - given("a non-positive startup timeout or a negative grace", [&] { - then("the activation is refused before anything is registered", [&] { - requireThrows([&] { - Automation{app, options(std::chrono::seconds{0}, std::chrono::milliseconds{100})}; + given("a close grace of milliseconds::max()", [&] { + Automation automation{app, options(std::chrono::seconds{120}, std::chrono::milliseconds::max())}; + automation.controller()->close("Developer window disconnected"); + awaitCloseGrace(&automation); + then("the window is never declared unresponsive", [&] { + advanceSupervisor(std::chrono::hours{24}); + require(unresponsive.load() == 0); }); - requireThrows([&] { - Automation{app, options(std::chrono::seconds{120}, std::chrono::milliseconds{-1})}; + }); + given("a non-positive startup timeout or a negative grace", [&] { + then("the activation is refused before anything is registered", [&] { + requireThrows([&] { + Automation{app, options(std::chrono::seconds{0}, std::chrono::milliseconds{100})}; + }); + requireThrows([&] { + Automation{app, options(std::chrono::seconds{120}, std::chrono::milliseconds{-1})}; + }); }); }); - }); -}}; + }}; diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index 0fcefaad..71c6ab60 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -1,9 +1,9 @@ // MCP over Streamable HTTP served by the application (ADR-025): header screening, MCP sessions, the loopback listener // on real sockets and its activation through enableAutomation. #include "TemporaryDirectory.hpp" -#include #include #include +#include #include #include @@ -28,8 +28,8 @@ const std::string token(64, 'a'); std::string post(unsigned short port, std::string_view body, std::string_view extra = {}, std::string_view bearer = token) { return "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:" + std::to_string(port) + "\r\nAuthorization: Bearer " + std::string(bearer) - + "\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: " + std::to_string(body.size()) - + "\r\n" + std::string(extra) + "\r\n" + std::string(body); + + "\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: " + std::to_string(body.size()) + "\r\n" + + std::string(extra) + "\r\n" + std::string(body); } int status(const mcphttp::Screening& screening) { @@ -47,9 +47,13 @@ struct Reply { if (colon == std::string::npos) continue; std::string key = line.substr(0, colon); - std::ranges::transform(key, key.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(key, key.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); std::string wanted{name}; - std::ranges::transform(wanted, wanted.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + std::ranges::transform(wanted, wanted.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); if (key == wanted) { auto value = line.substr(colon + 1); while (!value.empty() && (value.front() == ' ')) @@ -83,7 +87,7 @@ std::string drain(channel::Handle socket, std::string text = {}, std::string_vie Reply reply(std::string text) { while (text.starts_with("HTTP/1.1 100")) text.erase(0, text.find("\r\n\r\n") + 4); - Reply result; + Reply result; const auto end = text.find("\r\n\r\n"); require(end != std::string::npos); result.head = text.substr(0, end); @@ -126,10 +130,14 @@ constexpr std::string_view listTools = R"({"jsonrpc":"2.0","id":2,"method":"to struct HttpConsumerApp { struct UI { - int value; - int id() const { return value; } - void addScript(std::string) const { } - friend bool operator==(const UI& a, const UI& b) { return a.value == b.value; } + int value; + int id() const { + return value; + } + void addScript(std::string) const {} + friend bool operator==(const UI& a, const UI& b) { + return a.value == b.value; + } }; std::filesystem::path project; std::vector registered{}; @@ -138,605 +146,687 @@ struct HttpConsumerApp { void cppFunction(std::string_view name, Handler) { registered.emplace_back(name); } - webfront::UISubscription subscribeUIStarted(std::function) { return {}; } - webfront::UISubscription subscribeUIClosed(std::function) { return {}; } - const std::filesystem::path& projectDirectory() const { ++projectReads; return project; } + webfront::UISubscription subscribeUIStarted(std::function) { + return {}; + } + webfront::UISubscription subscribeUIClosed(std::function) { + return {}; + } + const std::filesystem::path& projectDirectory() const { + ++projectReads; + return project; + } }; } // namespace mcphttptests -const Scenario mcpHttpScreening{"MCP HTTP requests are screened on their headers before any body is read", [] { - using namespace mcphttptests; - constexpr unsigned short port = 4321; - const auto screened = [&](std::string_view text) { return mcphttp::screen(parsed(text), port, token, true); }; - given("a well-formed authenticated POST", [&] { - then("it is accepted with its announced length", [&] { - const auto accepted = screened(post(port, "{}")); - require(!accepted.refusal); - require(accepted.length == 2); - require(!accepted.expectsContinue); - require(!mcphttp::screen(parsed(post(port, "{}")), port, token).refusal); - const Object defaults{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token)}; - require(Object(Object(defaults.raw("mcpServers")).raw("webfront")).has("headers")); - const auto ordered = mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token); - require(ordered.find("\"type\"") < ordered.find("\"url\"")); - require(ordered.find("\"url\"") < ordered.find("\"headers\"")); - const Object escaped{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", "a\"b", "custom")}; - const Object server{Object(escaped.raw("mcpServers")).raw("custom")}; - require(Object(server.raw("headers")).string("Authorization") == "Bearer a\"b"); - require(screened(post(port, "{}", "Expect: 100-continue\r\n")).expectsContinue); - }); - then("localhost is the other accepted spelling, and the Bearer scheme is case-insensitive", [&] { - auto text = post(port, "{}"); - text.replace(text.find("127.0.0.1"), 9, "LocalHost"); - require(!screened(text).refusal); - text.replace(text.find("Bearer"), 6, "bearer"); - require(!screened(text).refusal); - }); - }); - given("requests a web page could send", [&] { - then("a foreign Host, as DNS rebinding produces, is refused with 421, even with the token", [&] { - auto text = post(port, "{}"); - text.replace(text.find("127.0.0.1"), 9, "attacker.example"); - require(status(screened(text)) == 421); - auto other = post(port, "{}"); - other.replace(other.find(":4321"), 5, ":4322"); - require(status(screened(other)) == 421); - require(status(screened("POST /mcp HTTP/1.1\r\nAuthorization: Bearer " + token + "\r\n\r\n")) == 421); - require(status(screened(post(port, "{}", "Host: 127.0.0.1:4321\r\n"))) == 421); // repeated - }); - then("any Origin, the application's own included, and any Sec-Fetch header are refused with 403, even with the token", [&] { - require(status(screened(post(port, "{}", "Origin: http://127.0.0.1:9002\r\n"))) == 403); - require(status(screened(post(port, "{}", "Origin: null\r\n"))) == 403); - require(status(screened(post(port, "{}", "Sec-Fetch-Site: same-origin\r\n"))) == 403); - require(status(screened(post(port, "{}", "Sec-Fetch-Dest: document\r\n"))) == 403); - require(status(screened(post(port, "{}", "Sec-Fetch-Mode: no-cors\r\n"))) == 403); - }); - then("a CORS preflight and a GET get 405 and no Access-Control header", [&] { - const auto preflight = screened("OPTIONS /mcp HTTP/1.1\r\nHost: 127.0.0.1:4321\r\n\r\n"); - require(status(preflight) == 405); - const auto serialized = preflight.refusal->serialize(); - require(serialized.find("Access-Control") == std::string::npos); - require(serialized.find("Allow: POST, DELETE") != std::string::npos); - require(status(screened("GET /mcp HTTP/1.1\r\nHost: 127.0.0.1:4321\r\nAuthorization: Bearer " + token + "\r\n\r\n")) == 405); - }); - then("a form-like body type is refused with 415", [&] { - auto text = post(port, "{}"); - text.replace(text.find("application/json\r\n"), 16, "text/plain"); - require(status(screened(text)) == 415); - auto charset = post(port, "{}"); - charset.replace(charset.find("application/json\r\n"), 16, "Application/JSON; charset=utf-8"); - require(!screened(charset).refusal); - }); - }); - given("other paths", [&] { - then("only /mcp is served: the page's files and the OAuth discovery paths are 404", [&] { - for (const auto* path : {"/WebFront.js", "/", "/mcp/", "/mcp?x=1", "/.well-known/oauth-protected-resource", "/.well-known/oauth-authorization-server"}) { +const Scenario mcpHttpScreening{ + "MCP HTTP requests are screened on their headers before any body is read", + [] { + using namespace mcphttptests; + constexpr unsigned short port = 4321; + const auto screened = [&](std::string_view text) { + return mcphttp::screen(parsed(text), port, token, true); + }; + given("a well-formed authenticated POST", [&] { + then("it is accepted with its announced length", [&] { + const auto accepted = screened(post(port, "{}")); + require(!accepted.refusal); + require(accepted.length == 2); + require(!accepted.expectsContinue); + require(!mcphttp::screen(parsed(post(port, "{}")), port, token).refusal); + const Object defaults{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token)}; + require(Object(Object(defaults.raw("mcpServers")).raw("webfront")).has("headers")); + const auto ordered = mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token); + require(ordered.find("\"type\"") < ordered.find("\"url\"")); + require(ordered.find("\"url\"") < ordered.find("\"headers\"")); + const Object escaped{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", "a\"b", "custom")}; + const Object server{Object(escaped.raw("mcpServers")).raw("custom")}; + require(Object(server.raw("headers")).string("Authorization") == "Bearer a\"b"); + require(screened(post(port, "{}", "Expect: 100-continue\r\n")).expectsContinue); + }); + then("localhost is the other accepted spelling, and the Bearer scheme is case-insensitive", [&] { auto text = post(port, "{}"); - text.replace(text.find("/mcp"), 4, path); - require(status(screened(text)) == 404); - } - }); - }); - given("requests of a native client", [&] { - then("a missing, malformed or wrong token is refused with 401 and WWW-Authenticate: Bearer", [&] { - auto missing = post(port, "{}"); - missing.erase(missing.find("Authorization"), missing.find("\r\n", missing.find("Authorization")) + 2 - missing.find("Authorization")); - const auto refused = screened(missing); - require(status(refused) == 401); - require(refused.refusal->serialize().find("WWW-Authenticate: Bearer\r\n") != std::string::npos); - require(status(screened(post(port, "{}", {}, std::string(64, 'b')))) == 401); - require(status(screened(post(port, "{}", {}, token.substr(1)))) == 401); - auto basic = post(port, "{}"); - basic.replace(basic.find("Bearer"), 6, "Basic"); - require(status(screened(basic)) == 401); - require(status(screened(post(port, "{}", "Authorization: Bearer " + token + "\r\n"))) == 401); // repeated - }); - then("an Accept without application/json is 406, a look-alike or a zero quality included", [&] { - const auto accepting = [&](std::string_view accept) { + text.replace(text.find("127.0.0.1"), 9, "LocalHost"); + require(!screened(text).refusal); + text.replace(text.find("Bearer"), 6, "bearer"); + require(!screened(text).refusal); + }); + }); + given("requests a web page could send", [&] { + then("a foreign Host, as DNS rebinding produces, is refused with 421, even with the token", [&] { auto text = post(port, "{}"); - text.replace(text.find("application/json, text/event-stream"), 35, accept); - return status(screened(text)); - }; - require(accepting("text/event-stream") == 406); - require(accepting("application/jsonp") == 406); - require(accepting("application/json;q=0") == 406); - require(accepting("application/json; q=0.000, text/event-stream") == 406); - require(accepting("text/event-stream, Application/JSON;q=0.5") == 0); - require(accepting("application/*") == 0); - require(accepting("*/*;q=1") == 0); - // The most specific matching range decides, whatever the order: an explicit refusal of JSON is not overridden. - require(accepting("application/json;q=0, */*;q=1") == 406); - require(accepting("*/*, application/json;q=0") == 406); - require(accepting("application/json;q=0, application/*") == 406); - require(accepting("application/*;q=0, application/json") == 0); - require(accepting("*/*;q=0, application/*;q=0.1") == 0); - }); - then("chunked, unannounced, malformed and oversized bodies are refused before they are read", [&] { - require(status(screened(post(port, "{}", "Transfer-Encoding: chunked\r\n"))) == 501); - auto unannounced = post(port, ""); - unannounced.erase(unannounced.find("Content-Length"), std::string_view("Content-Length: 0\r\n").size()); - require(status(screened(unannounced)) == 411); - auto malformed = post(port, "{}"); - malformed.replace(malformed.find("Content-Length: 2"), 17, "Content-Length: x2"); - require(status(screened(malformed)) == 400); - auto oversized = post(port, "{}"); - oversized.replace(oversized.find("Content-Length: 2"), 17, "Content-Length: " + std::to_string(messageLimit + 1)); - require(status(screened(oversized)) == 413); - }); - then("refusals quote nothing of the request", [&] { - const auto refused = screened(post(port, "{}", {}, "secret-not-the-token")); - require(refused.refusal->serialize().find("secret") == std::string::npos); - }); - }); -}}; + text.replace(text.find("127.0.0.1"), 9, "attacker.example"); + require(status(screened(text)) == 421); + auto other = post(port, "{}"); + other.replace(other.find(":4321"), 5, ":4322"); + require(status(screened(other)) == 421); + require(status(screened("POST /mcp HTTP/1.1\r\nAuthorization: Bearer " + token + "\r\n\r\n")) == 421); + require(status(screened(post(port, "{}", "Host: 127.0.0.1:4321\r\n"))) == 421); // repeated + }); + then("any Origin, the application's own included, and any Sec-Fetch header are refused with 403, even with the token", [&] { + require(status(screened(post(port, "{}", "Origin: http://127.0.0.1:9002\r\n"))) == 403); + require(status(screened(post(port, "{}", "Origin: null\r\n"))) == 403); + require(status(screened(post(port, "{}", "Sec-Fetch-Site: same-origin\r\n"))) == 403); + require(status(screened(post(port, "{}", "Sec-Fetch-Dest: document\r\n"))) == 403); + require(status(screened(post(port, "{}", "Sec-Fetch-Mode: no-cors\r\n"))) == 403); + }); + then("a CORS preflight and a GET get 405 and no Access-Control header", [&] { + const auto preflight = screened("OPTIONS /mcp HTTP/1.1\r\nHost: 127.0.0.1:4321\r\n\r\n"); + require(status(preflight) == 405); + const auto serialized = preflight.refusal->serialize(); + require(serialized.find("Access-Control") == std::string::npos); + require(serialized.find("Allow: POST, DELETE") != std::string::npos); + require(status(screened("GET /mcp HTTP/1.1\r\nHost: 127.0.0.1:4321\r\nAuthorization: Bearer " + token + "\r\n\r\n")) == 405); + }); + then("a form-like body type is refused with 415", [&] { + auto text = post(port, "{}"); + text.replace(text.find("application/json\r\n"), 16, "text/plain"); + require(status(screened(text)) == 415); + auto charset = post(port, "{}"); + charset.replace(charset.find("application/json\r\n"), 16, "Application/JSON; charset=utf-8"); + require(!screened(charset).refusal); + }); + }); + given("other paths", [&] { + then("only /mcp is served: the page's files and the OAuth discovery paths are 404", [&] { + for (const auto* path : + {"/WebFront.js", "/", "/mcp/", "/mcp?x=1", "/.well-known/oauth-protected-resource", "/.well-known/oauth-authorization-server"}) { + auto text = post(port, "{}"); + text.replace(text.find("/mcp"), 4, path); + require(status(screened(text)) == 404); + } + }); + }); + given("requests of a native client", [&] { + then("a missing, malformed or wrong token is refused with 401 and WWW-Authenticate: Bearer", [&] { + auto missing = post(port, "{}"); + missing.erase(missing.find("Authorization"), missing.find("\r\n", missing.find("Authorization")) + 2 - missing.find("Authorization")); + const auto refused = screened(missing); + require(status(refused) == 401); + require(refused.refusal->serialize().find("WWW-Authenticate: Bearer\r\n") != std::string::npos); + require(status(screened(post(port, "{}", {}, std::string(64, 'b')))) == 401); + require(status(screened(post(port, "{}", {}, token.substr(1)))) == 401); + auto basic = post(port, "{}"); + basic.replace(basic.find("Bearer"), 6, "Basic"); + require(status(screened(basic)) == 401); + require(status(screened(post(port, "{}", "Authorization: Bearer " + token + "\r\n"))) == 401); // repeated + }); + then("an Accept without application/json is 406, a look-alike or a zero quality included", [&] { + const auto accepting = [&](std::string_view accept) { + auto text = post(port, "{}"); + text.replace(text.find("application/json, text/event-stream"), 35, accept); + return status(screened(text)); + }; + require(accepting("text/event-stream") == 406); + require(accepting("application/jsonp") == 406); + require(accepting("application/json;q=0") == 406); + require(accepting("application/json; q=0.000, text/event-stream") == 406); + require(accepting("text/event-stream, Application/JSON;q=0.5") == 0); + require(accepting("application/*") == 0); + require(accepting("*/*;q=1") == 0); + // The most specific matching range decides, whatever the order: an explicit refusal of JSON is not overridden. + require(accepting("application/json;q=0, */*;q=1") == 406); + require(accepting("*/*, application/json;q=0") == 406); + require(accepting("application/json;q=0, application/*") == 406); + require(accepting("application/*;q=0, application/json") == 0); + require(accepting("*/*;q=0, application/*;q=0.1") == 0); + }); + then("chunked, unannounced, malformed and oversized bodies are refused before they are read", [&] { + require(status(screened(post(port, "{}", "Transfer-Encoding: chunked\r\n"))) == 501); + auto unannounced = post(port, ""); + unannounced.erase(unannounced.find("Content-Length"), std::string_view("Content-Length: 0\r\n").size()); + require(status(screened(unannounced)) == 411); + auto malformed = post(port, "{}"); + malformed.replace(malformed.find("Content-Length: 2"), 17, "Content-Length: x2"); + require(status(screened(malformed)) == 400); + auto oversized = post(port, "{}"); + oversized.replace(oversized.find("Content-Length: 2"), 17, "Content-Length: " + std::to_string(messageLimit + 1)); + require(status(screened(oversized)) == 413); + }); + then("refusals quote nothing of the request", [&] { + const auto refused = screened(post(port, "{}", {}, "secret-not-the-token")); + require(refused.refusal->serialize().find("secret") == std::string::npos); + }); + }); + }}; -const Scenario mcpHttpSessions{"MCP HTTP sessions follow the Streamable HTTP rules over the shared MCP profile", [] { - using namespace mcphttptests; - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - auto controller = std::make_shared(SessionOptions{root.path() / "project", {"build"}}); - controller->poll(); - mcphttp::Endpoint endpoint{*controller}; - constexpr unsigned short port = 4321; - const auto handle = [&](std::string_view body, std::string_view extra = {}) { - return endpoint.handle(parsed(post(port, body, extra)), body); - }; - given("a request without a session", [&] { - then("anything but initialize is refused with 400", [&] { - require(handle(listTools).status == 400); - require(handle(initialized).status == 400); - require(endpoint.sessions() == 0); - }); - then("a batch and a malformed body are refused with 400", [&] { - require(handle(std::string("[") + std::string(initialize) + "]").status == 400); - const auto broken = handle("{\"jsonrpc\":"); - require(broken.status == 400); - require(Object(Object(broken.body).raw("error")).raw("code") == "-32700"); - }); - }); - given("an initialized session", [&] { - const auto opened = handle(initialize); - require(opened.status == 200); - const auto identifier = [&] { - for (const auto& [name, value] : opened.headers) - if (name == "Mcp-Session-Id") - return value; - return std::string{}; - }(); - const auto withSession = "Mcp-Session-Id: " + identifier + "\r\n"; - then("the answer names the session, the negotiated revision and instructions", [&] { - require(identifier.size() == 32); - const Object result{Object(opened.body).raw("result")}; - require(result.string("protocolVersion") == "2025-11-25"); - require(result.string("instructions").find("webfront.session") != std::string::npos); - }); - then("a notification is accepted with 202 and no body, and the tools are listed", [&] { - const auto notified = handle(initialized, withSession); - require(notified.status == 202); - require(notified.body.empty()); - const auto tools = handle(listTools, withSession + "MCP-Protocol-Version: 2025-11-25\r\n"); - require(tools.status == 200); - for (const auto* name : {"webfront.session", "webfront.start", "webfront.result", "webfront.cancel"}) - require(tools.body.find(name) != std::string::npos); - const auto described = handle(R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", withSession); - require(described.body.find(Object(controller->describe()).string("session")) != std::string::npos); - }); - then("a client response is accepted with 202, and anything else without a method is refused with 400", [&] { - require(handle(R"({"jsonrpc":"2.0","id":7,"result":{}})", withSession).status == 202); - require(handle(R"({"jsonrpc":"2.0","id":7,"error":{"code":1,"message":"no"}})", withSession).status == 202); - require(handle("{}", withSession).status == 400); - require(handle(R"({"jsonrpc":"2.0","id":7})", withSession).status == 400); - require(handle(R"({"jsonrpc":"2.0","result":{}})", withSession).status == 400); - require(handle(R"({"jsonrpc":"2.0","id":7,"result":{},"error":{}})", withSession).status == 400); - require(handle(R"({"jsonrpc":"1.0","id":7,"result":{}})", withSession).status == 400); - }); - then("an unsupported MCP-Protocol-Version is refused with 400, for a response and a termination too", [&] { - const auto old = withSession + "MCP-Protocol-Version: 2024-11-05\r\n"; - require(handle(listTools, old).status == 400); - require(handle(R"({"jsonrpc":"2.0","id":7,"result":{}})", old).status == 400); - auto removal = post(port, ""); - removal.replace(0, 4, "DELETE"); - removal.insert(removal.find("\r\n\r\n") + 2, old); - require(endpoint.handle(parsed(removal), {}).status == 400); - require(handle(listTools, withSession).status == 200); - }); - then("an unknown session is 404, and DELETE terminates the session only", [&] { - require(handle(listTools, "Mcp-Session-Id: " + std::string(32, '0') + "\r\n").status == 404); - auto removal = post(port, ""); - removal.replace(0, 4, "DELETE"); - removal.insert(removal.find("\r\n\r\n") + 2, withSession); - const auto terminated = endpoint.handle(parsed(removal), {}); - require(terminated.status == 204); - require(terminated.serialize().find("Content-Length") == std::string::npos); // forbidden on 204 - require(handle(listTools, withSession).status == 404); - require(endpoint.handle(parsed(removal), {}).status == 404); - require(!controller->isClosed()); - }); - }); - given("an initialize request whose id makes the answer larger than the request limit", [&] { - const auto id = std::string(messageLimit - 300, 'i'); - const auto body = R"({"jsonrpc":"2.0","id":")" + id + R"(","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}})"; - then("the session is still created", [&] { - require(body.size() <= messageLimit); - const auto opened = handle(body); - require(opened.status == 200); - require(opened.body.size() > messageLimit); - require(endpoint.sessions() == 1); - }); - }); - given("more sessions than the bound", [&] { - std::vector identifiers; - for (std::size_t index = 0; index < mcphttp::maxSessions; ++index) { +const Scenario mcpHttpSessions{ + "MCP HTTP sessions follow the Streamable HTTP rules over the shared MCP profile", + [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + auto controller = std::make_shared(SessionOptions{root.path() / "project", {"build"}}); + controller->poll(); + mcphttp::Endpoint endpoint{*controller}; + constexpr unsigned short port = 4321; + const auto handle = [&](std::string_view body, std::string_view extra = {}) { + return endpoint.handle(parsed(post(port, body, extra)), body); + }; + given("a request without a session", [&] { + then("anything but initialize is refused with 400", [&] { + require(handle(listTools).status == 400); + require(handle(initialized).status == 400); + require(endpoint.sessions() == 0); + }); + then("a batch and a malformed body are refused with 400", [&] { + require(handle(std::string("[") + std::string(initialize) + "]").status == 400); + const auto broken = handle("{\"jsonrpc\":"); + require(broken.status == 400); + require(Object(Object(broken.body).raw("error")).raw("code") == "-32700"); + }); + }); + given("an initialized session", [&] { const auto opened = handle(initialize); require(opened.status == 200); - identifiers.push_back(opened.headers.front().second); - std::this_thread::sleep_for(std::chrono::milliseconds{2}); - } - then("the least recently used are evicted, and a refused message does not count as activity", [&] { - const auto oldest = "Mcp-Session-Id: " + identifiers.front() + "\r\n"; - require(handle(listTools, oldest + "MCP-Protocol-Version: 2024-11-05\r\n").status == 400); - require(handle(initialize).status == 200); - require(endpoint.sessions() == mcphttp::maxSessions); - require(handle(listTools, oldest).status == 404); - // Neither does a message with a supported revision but an invalid JSON-RPC envelope. - const auto next = "Mcp-Session-Id: " + identifiers[1] + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; - require(handle(R"({"jsonrpc":"1.0","id":2,"method":"tools/list"})", next).status == 200); - require(handle(initialize).status == 200); - require(handle(listTools, next).status == 404); - for (std::size_t index = 0; index < 4; ++index) + const auto identifier = [&] { + for (const auto& [name, value] : opened.headers) + if (name == "Mcp-Session-Id") + return value; + return std::string{}; + }(); + const auto withSession = "Mcp-Session-Id: " + identifier + "\r\n"; + then("the answer names the session, the negotiated revision and instructions", [&] { + require(identifier.size() == 32); + const Object result{Object(opened.body).raw("result")}; + require(result.string("protocolVersion") == "2025-11-25"); + require(result.string("instructions").find("webfront.session") != std::string::npos); + }); + then("a notification is accepted with 202 and no body, and the tools are listed", [&] { + const auto notified = handle(initialized, withSession); + require(notified.status == 202); + require(notified.body.empty()); + const auto tools = handle(listTools, withSession + "MCP-Protocol-Version: 2025-11-25\r\n"); + require(tools.status == 200); + for (const auto* name : {"webfront.session", "webfront.start", "webfront.result", "webfront.cancel"}) + require(tools.body.find(name) != std::string::npos); + const auto described = handle(R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", + withSession); + require(described.body.find(Object(controller->describe()).string("session")) != std::string::npos); + }); + then("a client response is accepted with 202, and anything else without a method is refused with 400", [&] { + require(handle(R"({"jsonrpc":"2.0","id":7,"result":{}})", withSession).status == 202); + require(handle(R"({"jsonrpc":"2.0","id":7,"error":{"code":1,"message":"no"}})", withSession).status == 202); + require(handle("{}", withSession).status == 400); + require(handle(R"({"jsonrpc":"2.0","id":7})", withSession).status == 400); + require(handle(R"({"jsonrpc":"2.0","result":{}})", withSession).status == 400); + require(handle(R"({"jsonrpc":"2.0","id":7,"result":{},"error":{}})", withSession).status == 400); + require(handle(R"({"jsonrpc":"1.0","id":7,"result":{}})", withSession).status == 400); + }); + then("an unsupported MCP-Protocol-Version is refused with 400, for a response and a termination too", [&] { + const auto old = withSession + "MCP-Protocol-Version: 2024-11-05\r\n"; + require(handle(listTools, old).status == 400); + require(handle(R"({"jsonrpc":"2.0","id":7,"result":{}})", old).status == 400); + auto removal = post(port, ""); + removal.replace(0, 4, "DELETE"); + removal.insert(removal.find("\r\n\r\n") + 2, old); + require(endpoint.handle(parsed(removal), {}).status == 400); + require(handle(listTools, withSession).status == 200); + }); + then("an unknown session is 404, and DELETE terminates the session only", [&] { + require(handle(listTools, "Mcp-Session-Id: " + std::string(32, '0') + "\r\n").status == 404); + auto removal = post(port, ""); + removal.replace(0, 4, "DELETE"); + removal.insert(removal.find("\r\n\r\n") + 2, withSession); + const auto terminated = endpoint.handle(parsed(removal), {}); + require(terminated.status == 204); + require(terminated.serialize().find("Content-Length") == std::string::npos); // forbidden on 204 + require(handle(listTools, withSession).status == 404); + require(endpoint.handle(parsed(removal), {}).status == 404); + require(!controller->isClosed()); + }); + }); + given("an initialize request whose id makes the answer larger than the request limit", [&] { + const auto id = std::string(messageLimit - 300, 'i'); + const auto body = + R"({"jsonrpc":"2.0","id":")" + id + + R"(","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}})"; + then("the session is still created", [&] { + require(body.size() <= messageLimit); + const auto opened = handle(body); + require(opened.status == 200); + require(opened.body.size() > messageLimit); + require(endpoint.sessions() == 1); + }); + }); + given("more sessions than the bound", [&] { + std::vector identifiers; + for (std::size_t index = 0; index < mcphttp::maxSessions; ++index) { + const auto opened = handle(initialize); + require(opened.status == 200); + identifiers.push_back(opened.headers.front().second); + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + then("the least recently used are evicted, and a refused message does not count as activity", [&] { + const auto oldest = "Mcp-Session-Id: " + identifiers.front() + "\r\n"; + require(handle(listTools, oldest + "MCP-Protocol-Version: 2024-11-05\r\n").status == 400); require(handle(initialize).status == 200); - require(endpoint.sessions() == mcphttp::maxSessions); + require(endpoint.sessions() == mcphttp::maxSessions); + require(handle(listTools, oldest).status == 404); + // Neither does a message with a supported revision but an invalid JSON-RPC envelope. + const auto next = "Mcp-Session-Id: " + identifiers[1] + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; + require(handle(R"({"jsonrpc":"1.0","id":2,"method":"tools/list"})", next).status == 200); + require(handle(initialize).status == 200); + require(handle(listTools, next).status == 404); + for (std::size_t index = 0; index < 4; ++index) + require(handle(initialize).status == 200); + require(endpoint.sessions() == mcphttp::maxSessions); + }); }); - }); -}}; + }}; -const Scenario mcpHttpListener{"The MCP listener serves loopback HTTP with a private client configuration", [] { - using namespace mcphttptests; - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - auto controller = std::make_shared(SessionOptions{root.path() / "project", {"build"}}); - controller->poll(); - channel::PrivateDirectory directory{root.path() / "private"}; - mcphttp::Server server{controller, directory.path}; - const auto port = server.port(); - const auto secret = bearer(directory.path); - given("the published client configuration", [&] { - then("it is private, names the loopback URL and holds a 256-bit token that no other file shows", [&] { - require(server.url() == "http://127.0.0.1:" + std::to_string(port) + "/mcp"); - require(url(directory.path) == server.url()); - require(secret.size() == 64); +const Scenario mcpHttpListener{ + "The MCP listener serves loopback HTTP with a private client configuration", + [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + auto controller = std::make_shared(SessionOptions{root.path() / "project", {"build"}}); + controller->poll(); + channel::PrivateDirectory directory{root.path() / "private"}; + mcphttp::Server server{controller, directory.path}; + const auto port = server.port(); + const auto secret = bearer(directory.path); + given("the published client configuration", [&] { + then("it is private, names the loopback URL and holds a 256-bit token that no other file shows", [&] { + require(server.url() == "http://127.0.0.1:" + std::to_string(port) + "/mcp"); + require(url(directory.path) == server.url()); + require(secret.size() == 64); #ifndef _WIN32 - struct stat info{}; - require(::stat(server.configuration().c_str(), &info) == 0); - require((info.st_mode & 0777) == 0600); + struct stat info{}; + require(::stat(server.configuration().c_str(), &info) == 0); + require((info.st_mode & 0777) == 0600); #endif - }); - }); - given("an unauthenticated client that sends its body at once", [&] { - then("it reads its 401 instead of a reset", [&] { - const auto refused = roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))); - require(refused.status == 401); - require(refused.header("WWW-Authenticate") == "Bearer"); - require(refused.header("Connection") == "close"); - }); - then("a page's request is refused even with the token", [&] { - require(roundTrip(port, post(port, initialize, "Origin: http://127.0.0.1:9002\r\n", secret)).status == 403); - }); - }); - given("an authenticated client", [&] { - then("it initializes, lists the tools and starts an operation through its session", [&] { - const auto opened = roundTrip(port, post(port, initialize, {}, secret)); - require(opened.status == 200); - require(opened.header("Content-Type") == "application/json"); - const auto session = "Mcp-Session-Id: " + opened.header("Mcp-Session-Id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; - require(roundTrip(port, post(port, initialized, session, secret)).status == 202); - require(roundTrip(port, post(port, listTools, session, secret)).body.find("webfront.start") != std::string::npos); - const auto id = Object(controller->describe()).string("session"); - const auto started = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":")" + id + R"(","operation":"build"}}})", session, secret)); - require(started.status == 200); - const Object result{Object(started.body).raw("result")}; - require(result.raw("isError") == "false"); - require(!Object(result.raw("structuredContent")).string("runId").empty()); - const auto refused = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":")" + id + R"(","operation":"test"}}})", session, secret)); - require(Object(Object(refused.body).raw("result")).raw("isError") == "true"); - }); - then("Expect: 100-continue receives the interim answer before the body is sent", [&] { - [[maybe_unused]] channel::Runtime runtime; - const auto text = post(port, initialize, "Expect: 100-continue\r\n", secret); - const auto head = text.substr(0, text.find("\r\n\r\n") + 4); - channel::Socket peer{channel::createSocket()}; - connectTo(peer, port); - channel::send(peer.value, head); - const auto interim = drain(peer.value, {}, "\r\n\r\n"); - require(interim.starts_with("HTTP/1.1 100 Continue\r\n\r\n")); - channel::send(peer.value, text.substr(head.size())); - require(reply(drain(peer.value, interim)).status == 200); - }); - then("an unauthenticated client never receives 100 Continue: its refusal comes first", [&] { + }); + }); + given("an unauthenticated client that sends its body at once", [&] { + then("it reads its 401 instead of a reset", [&] { + const auto refused = roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))); + require(refused.status == 401); + require(refused.header("WWW-Authenticate") == "Bearer"); + require(refused.header("Connection") == "close"); + }); + then("a page's request is refused even with the token", [&] { + require(roundTrip(port, post(port, initialize, "Origin: http://127.0.0.1:9002\r\n", secret)).status == 403); + }); + }); + given("an authenticated client", [&] { + then("it initializes, lists the tools and starts an operation through its session", [&] { + const auto opened = roundTrip(port, post(port, initialize, {}, secret)); + require(opened.status == 200); + require(opened.header("Content-Type") == "application/json"); + const auto session = "Mcp-Session-Id: " + opened.header("Mcp-Session-Id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; + require(roundTrip(port, post(port, initialized, session, secret)).status == 202); + require(roundTrip(port, post(port, listTools, session, secret)).body.find("webfront.start") != std::string::npos); + const auto id = Object(controller->describe()).string("session"); + const auto started = roundTrip( + port, + post(port, + R"({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":")" + id + + R"(","operation":"build"}}})", + session, + secret)); + require(started.status == 200); + const Object result{Object(started.body).raw("result")}; + require(result.raw("isError") == "false"); + require(!Object(result.raw("structuredContent")).string("runId").empty()); + const auto refused = roundTrip( + port, + post(port, + R"({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":")" + id + + R"(","operation":"test"}}})", + session, + secret)); + require(Object(Object(refused.body).raw("result")).raw("isError") == "true"); + }); + then("Expect: 100-continue receives the interim answer before the body is sent", [&] { + [[maybe_unused]] channel::Runtime runtime; + const auto text = post(port, initialize, "Expect: 100-continue\r\n", secret); + const auto head = text.substr(0, text.find("\r\n\r\n") + 4); + channel::Socket peer{channel::createSocket()}; + connectTo(peer, port); + channel::send(peer.value, head); + const auto interim = drain(peer.value, {}, "\r\n\r\n"); + require(interim.starts_with("HTTP/1.1 100 Continue\r\n\r\n")); + channel::send(peer.value, text.substr(head.size())); + require(reply(drain(peer.value, interim)).status == 200); + }); + then("an unauthenticated client never receives 100 Continue: its refusal comes first", [&] { + [[maybe_unused]] channel::Runtime runtime; + const auto text = post(port, initialize, "Expect: 100-continue\r\n", std::string(64, 'c')); + channel::Socket peer{channel::createSocket()}; + connectTo(peer, port); + channel::send(peer.value, text.substr(0, text.find("\r\n\r\n") + 4)); + require(reply(drain(peer.value)).status == 401); + }); + }); + given("silent peers that connect and send nothing", [&] { [[maybe_unused]] channel::Runtime runtime; - const auto text = post(port, initialize, "Expect: 100-continue\r\n", std::string(64, 'c')); - channel::Socket peer{channel::createSocket()}; - connectTo(peer, port); - channel::send(peer.value, text.substr(0, text.find("\r\n\r\n") + 4)); - require(reply(drain(peer.value)).status == 401); - }); - }); - given("silent peers that connect and send nothing", [&] { - [[maybe_unused]] channel::Runtime runtime; - std::deque connected; // Socket is neither copyable nor movable - for (int index = 0; index < 80; ++index) { - connected.emplace_back(channel::createSocket()); - const auto address = channel::address(port); - require(::connect(connected.back().value, reinterpret_cast(&address), sizeof address) == 0); - } - then("an authenticated request is answered well before their two-second deadline", [&] { - const auto started = std::chrono::steady_clock::now(); - require(roundTrip(port, post(port, initialize, {}, secret)).status == 200); - require(std::chrono::steady_clock::now() - started < std::chrono::milliseconds{1500}); - }); - }); - given("a chosen port that is taken", [&] { - then("the activation fails and names the address, the port and the cause", [&] { - channel::PrivateDirectory other{root.path() / "other"}; - try { - mcphttp::Server second{controller, other.path, port}; - require(false); - } catch (const mcphttp::BindError& error) { - require(std::string(error.what()).find("127.0.0.1:" + std::to_string(port)) != std::string::npos); + std::deque connected; // Socket is neither copyable nor movable + for (int index = 0; index < 80; ++index) { + connected.emplace_back(channel::createSocket()); + const auto address = channel::address(port); + require(::connect(connected.back().value, reinterpret_cast(&address), sizeof address) == 0); } - require(!std::filesystem::exists(other.path / mcphttp::configurationFile)); - }); - }); - given("the session closes", [&] { - controller->close("Developer window closed"); - then("the listener closes and the configuration with its token is removed", [&] { - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; - std::error_code error; - bool present = true; - do { - present = std::filesystem::exists(server.configuration(), error); - if (!error && !present) - break; - if (error && !channel::transientRemovalFailure(error)) - break; - std::this_thread::sleep_for(std::chrono::milliseconds{10}); - } while (std::chrono::steady_clock::now() < deadline); - require(!error); - require(!present); - [[maybe_unused]] channel::Runtime runtime; - channel::Socket peer{channel::createSocket()}; - const auto address = channel::address(port); - require(::connect(peer.value, reinterpret_cast(&address), sizeof address) != 0); - }); - }); -}}; + then("an authenticated request is answered well before their two-second deadline", [&] { + const auto started = std::chrono::steady_clock::now(); + require(roundTrip(port, post(port, initialize, {}, secret)).status == 200); + require(std::chrono::steady_clock::now() - started < std::chrono::milliseconds{1500}); + }); + }); + given("a chosen port that is taken", [&] { + then("the activation fails and names the address, the port and the cause", [&] { + channel::PrivateDirectory other{root.path() / "other"}; + try { + mcphttp::Server second{controller, other.path, port}; + require(false); + } catch (const mcphttp::BindError& error) { + require(std::string(error.what()).find("127.0.0.1:" + std::to_string(port)) != std::string::npos); + } + require(!std::filesystem::exists(other.path / mcphttp::configurationFile)); + }); + }); + given("the session closes", [&] { + controller->close("Developer window closed"); + then("the listener closes and the configuration with its token is removed", [&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; + std::error_code error; + bool present = true; + do { + present = std::filesystem::exists(server.configuration(), error); + if (!error && !present) + break; + if (error && !channel::transientRemovalFailure(error)) + break; + std::this_thread::sleep_for(std::chrono::milliseconds{10}); + } while (std::chrono::steady_clock::now() < deadline); + require(!error); + require(!present); + [[maybe_unused]] channel::Runtime runtime; + channel::Socket peer{channel::createSocket()}; + const auto address = channel::address(port); + require(::connect(peer.value, reinterpret_cast(&address), sizeof address) != 0); + }); + }); + }}; const Scenario mcpHttpActivation{"An application that enables automation serves its own MCP URL", [] { - using namespace mcphttptests; - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - std::filesystem::create_directory(root.path() / "project2"); - HttpConsumerApp first{.project = root.path() / "project"}, second{.project = root.path() / "project2"}; - const auto sessions = root.path() / "sessions"; - given("two instances enabled with no private directory chosen", [&] { - auto one = enableAutomation(first, {.grants = {"check"}, .discovery = sessions, .announce = false}); - auto two = enableAutomation(second, {.grants = {"build"}, .discovery = sessions, .announce = false}); - then("each has its own URL and private configuration, under a directory named after its session", [&] { - require(one->mcpUrl() != two->mcpUrl()); - require(one->mcpUrl().starts_with("http://127.0.0.1:")); - require(one->clientConfiguration().parent_path() == one->directory()); - require(one->directory().filename() == Object(one->controller()->describe()).string("session")); - require(bearer(one->directory()) != bearer(two->directory())); - }); - then("the records list both instances with their URLs, never their tokens", [&] { - const auto listed = discovery::list(sessions); - require(listed.size() == 2); - for (const auto& entry : listed) { - require(!entry.mcp.empty()); - require(std::filesystem::exists(entry.configuration)); - std::ifstream input(sessions / (entry.session + ".json")); - std::ostringstream text; - text << input.rdbuf(); - require(text.str().find(bearer(entry.endpoint)) == std::string::npos); + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + std::filesystem::create_directory(root.path() / "project2"); + HttpConsumerApp first{.project = root.path() / "project"}, second{.project = root.path() / "project2"}; + const auto sessions = root.path() / "sessions"; + given("two instances enabled with no private directory chosen", [&] { + auto one = enableAutomation(first, {.grants = {"check"}, .discovery = sessions, .announce = false}); + auto two = enableAutomation(second, {.grants = {"build"}, .discovery = sessions, .announce = false}); + then("each has its own URL and private configuration, under a directory named after its session", [&] { + require(one->mcpUrl() != two->mcpUrl()); + require(one->mcpUrl().starts_with("http://127.0.0.1:")); + require(one->clientConfiguration().parent_path() == one->directory()); + require(one->directory().filename() == Object(one->controller()->describe()).string("session")); + require(bearer(one->directory()) != bearer(two->directory())); + }); + then("the records list both instances with their URLs, never their tokens", [&] { + const auto listed = discovery::list(sessions); + require(listed.size() == 2); + for (const auto& entry : listed) { + require(!entry.mcp.empty()); + require(std::filesystem::exists(entry.configuration)); + std::ifstream input(sessions / (entry.session + ".json")); + std::ostringstream text; + text << input.rdbuf(); + require(text.str().find(bearer(entry.endpoint)) == std::string::npos); + } + }); + then("the banner gives the URL and the configuration path, not the token", [&] { + const auto banner = one->banner(); + require(banner.find(one->mcpUrl()) != std::string::npos); + require(banner.find("mcp.json") != std::string::npos); + require(banner.find(bearer(one->directory())) == std::string::npos); + }); + then("each URL answers with its own session only", [&] { + const auto port = static_cast(std::stoi(one->mcpUrl().substr(one->mcpUrl().rfind(':') + 1))); + const auto opened = roundTrip(port, post(port, initialize, {}, bearer(one->directory()))); + require(opened.status == 200); + require(roundTrip(port, post(port, initialize, {}, bearer(two->directory()))).status == 401); + }); + then("closing withdraws the record, the configuration and the private directory", [&] { + const auto directory = one->directory(); + one->close(); + require(!std::filesystem::exists(directory)); + require(discovery::list(sessions).size() == 1); + }); + }); + given("a record of a vanished instance", [&] { + const auto dead = std::string(64, 'd'); + discovery::preparePrivateDirectory(sessions); + std::filesystem::create_directory(sessions / dead); + // The record holds the resolved path, as channel::outsideProject gives it (the temporary root may be a link, as on + // macOS). + const auto own = std::filesystem::weakly_canonical(sessions / dead); + discovery::Entry entry{.session = dead, + .project = "/work/project", + .endpoint = own.generic_string(), + .allow = "[]", + .pid = 2147483000L, + .mcp = "http://127.0.0.1:1/mcp", + .configuration = (own / "mcp.json").generic_string()}; + std::ofstream(sessions / dead / "mcp.json") << "{}"; + channel::writeEndpoint(sessions / (dead + ".json"), entry.json()); + then("listing removes the record with its own directory and known files", [&] { + require(discovery::list(sessions).empty()); + require(!std::filesystem::exists(sessions / (dead + ".json"))); + require(!std::filesystem::exists(sessions / dead)); + }); + then("the next activation removes them too, before it publishes its own", [&] { + auto next = enableAutomation(first, {.grants = {"check"}, .discovery = sessions, .announce = false}); + require(!std::filesystem::exists(sessions / (dead + ".json"))); + require(!std::filesystem::exists(sessions / dead)); + require(discovery::list(sessions).size() == 1); + }); + }); +#ifndef _WIN32 + given("a vanished instance whose discovery directory is reached through a link", [&] { + const auto dead = std::string(64, 'e'); + const auto real = root.path() / "real"; + const auto alias = root.path() / "alias"; + std::filesystem::create_directory(real); + std::filesystem::create_directory_symlink(real, alias); + const auto linked = alias / "sessions"; + discovery::preparePrivateDirectory(linked); + std::filesystem::create_directory(linked / dead); + std::ofstream(linked / dead / "mcp.json") << "{}"; + const auto own = std::filesystem::weakly_canonical(linked / dead); + discovery::Entry entry{.session = dead, + .project = "/work/project", + .endpoint = own.generic_string(), + .allow = "[]", + .pid = 2147483000L, + .mcp = "http://127.0.0.1:1/mcp", + .configuration = (own / "mcp.json").generic_string()}; + channel::writeEndpoint(linked / (dead + ".json"), entry.json()); + then("listing through the alias still removes its private directory", [&] { + require(discovery::list(linked).empty()); + require(!std::filesystem::exists(real / "sessions" / dead)); + }); + then("a session directory replaced by a link is left alone", [&] { + const auto elsewhere = root.path() / "elsewhere"; + std::filesystem::create_directory(elsewhere); + std::ofstream(elsewhere / "mcp.json") << "{}"; + std::filesystem::remove_all(linked / dead); + std::filesystem::create_directory_symlink(elsewhere, linked / dead); + require(discovery::list(linked).empty()); + require(std::filesystem::exists(elsewhere / "mcp.json")); + std::filesystem::remove(linked / dead); + }); + }); +#endif + given("paths so long that the record would exceed its limit", [&] { + then("the record is refused before anything is published", [&] { + const auto session = std::string(64, 'f'); + const auto distant = "/" + std::string(discovery::recordLimit / 2, 'p'); // not "far", a Windows macro + discovery::Entry entry{.session = session, + .project = distant, + .endpoint = distant, + .allow = "[]", + .pid = discovery::currentProcess(), + .mcp = "http://127.0.0.1:1/mcp", + .configuration = distant + "/mcp.json"}; + require(entry.json().size() > discovery::recordLimit); + requireThrows([&] { + discovery::Registration refused{sessions, entry}; + }); + require(!std::filesystem::exists(sessions / (session + ".json"))); + }); + }); + }}; + +const Scenario stableMcp{ + "A fixed MCP token and port survive activation and authentication can be explicitly disabled", + [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + HttpConsumerApp app{.project = root.path() / "project"}; + const auto sessions = root.path() / "sessions"; + const std::string fixed(64, 'a'); + // A port selected by the OS can be claimed between launches. Retry only that bind error, keeping each + // successful pair on the same port and token; any other failure still fails the scenario. + for (int attempt = 0;; ++attempt) { + try { + auto first = enableAutomation(app, {.mcpToken = fixed, .discovery = sessions, .announce = false}); + require(first->banner().find("WARNING") == std::string::npos); + const auto port = static_cast(std::stoi(first->mcpUrl().substr(first->mcpUrl().rfind(':') + 1))); + const auto config = channel::readEndpoint(first->directory(), "mcp.json"); + first->close(); + for (int run = 0; run < 2; ++run) { + auto instance = enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); + require(channel::readEndpoint(instance->directory(), "mcp.json") == config); + for (const auto& entry : discovery::list(sessions)) { + std::ifstream input(sessions / (entry.session + ".json")); + std::ostringstream record; + record << input.rdbuf(); + require(record.str().find(fixed) == std::string::npos); + } + const auto opened = roundTrip(port, post(port, initialize, {}, fixed)); + require(opened.status == 200); + require(roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))).status == 401); + const auto extra = "MCP-Session-Id: " + opened.header("mcp-session-id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; + require(roundTrip(port, post(port, initialized, extra, fixed)).status == 202); + const auto result = roundTrip( + port, + post(port, R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", extra, fixed)); + require(result.status == 200); + require(result.body.find("result") != std::string::npos); + requireThrows([&] { + enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); + }); + auto side = enableAutomation(app, {.discovery = sessions, .announce = false}); + require(side->mcpUrl() != instance->mcpUrl()); + side->close(); + instance->close(); + } + auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); + require(open->banner().find("WARNING: MCP authentication disabled") != std::string::npos); + require(open->banner().find("local processes can use granted operations") != std::string::npos); + require(open->banner().find("WARNING") < open->banner().find("grants:")); + require(open->banner().ends_with(open->clientConfiguration().generic_string())); + const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; + require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); + require(channel::readEndpoint(open->directory(), "mcp.json").find(fixed) == std::string::npos); + auto request = post(port, initialize); + request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); + require(roundTrip(port, request).status == 200); + require(roundTrip(port, post(port, initialize, {}, "wrong-token")).status == 200); + require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); + auto hostile = request; + hostile.replace(hostile.find("127.0.0.1"), 9, "evil.test"); + require(roundTrip(port, hostile).status == 421); + open->close(); + break; + } catch (const mcphttp::BindError& error) { + if (!error.addressInUse() || attempt == 4) + throw; } + } + requireThrows([&] { + enableAutomation(app, {.mcpToken = "", .discovery = sessions, .announce = false}); }); - then("the banner gives the URL and the configuration path, not the token", [&] { - const auto banner = one->banner(); - require(banner.find(one->mcpUrl()) != std::string::npos); - require(banner.find("mcp.json") != std::string::npos); - require(banner.find(bearer(one->directory())) == std::string::npos); - }); - then("each URL answers with its own session only", [&] { - const auto port = static_cast(std::stoi(one->mcpUrl().substr(one->mcpUrl().rfind(':') + 1))); - const auto opened = roundTrip(port, post(port, initialize, {}, bearer(one->directory()))); - require(opened.status == 200); - require(roundTrip(port, post(port, initialize, {}, bearer(two->directory()))).status == 401); + requireThrows([&] { + enableAutomation(app, {.mcpToken = "a", .discovery = sessions, .announce = false}); }); - then("closing withdraws the record, the configuration and the private directory", [&] { - const auto directory = one->directory(); - one->close(); - require(!std::filesystem::exists(directory)); - require(discovery::list(sessions).size() == 1); + requireThrows([&] { + enableAutomation(app, {.mcpToken = std::string(31, 'a'), .discovery = sessions, .announce = false}); }); - }); - given("a record of a vanished instance", [&] { - const auto dead = std::string(64, 'd'); - discovery::preparePrivateDirectory(sessions); - std::filesystem::create_directory(sessions / dead); - // The record holds the resolved path, as channel::outsideProject gives it (the temporary root may be a link, as on macOS). - const auto own = std::filesystem::weakly_canonical(sessions / dead); - discovery::Entry entry{.session = dead, .project = "/work/project", .endpoint = own.generic_string(), .allow = "[]", .pid = 2147483000L, - .mcp = "http://127.0.0.1:1/mcp", .configuration = (own / "mcp.json").generic_string()}; - std::ofstream(sessions / dead / "mcp.json") << "{}"; - channel::writeEndpoint(sessions / (dead + ".json"), entry.json()); - then("listing removes the record with its own directory and known files", [&] { - require(discovery::list(sessions).empty()); - require(!std::filesystem::exists(sessions / (dead + ".json"))); - require(!std::filesystem::exists(sessions / dead)); + requireThrows([&] { + enableAutomation(app, {.mcpToken = std::string(1025, 'a'), .discovery = sessions, .announce = false}); }); - then("the next activation removes them too, before it publishes its own", [&] { - auto next = enableAutomation(first, {.grants = {"check"}, .discovery = sessions, .announce = false}); - require(!std::filesystem::exists(sessions / (dead + ".json"))); - require(!std::filesystem::exists(sessions / dead)); - require(discovery::list(sessions).size() == 1); + requireThrows([&] { + enableAutomation(app, {.mcpToken = std::string(32, 'a') + "\r\nInjected", .discovery = sessions, .announce = false}); }); - }); -#ifndef _WIN32 - given("a vanished instance whose discovery directory is reached through a link", [&] { - const auto dead = std::string(64, 'e'); - const auto real = root.path() / "real"; - const auto alias = root.path() / "alias"; - std::filesystem::create_directory(real); - std::filesystem::create_directory_symlink(real, alias); - const auto linked = alias / "sessions"; - discovery::preparePrivateDirectory(linked); - std::filesystem::create_directory(linked / dead); - std::ofstream(linked / dead / "mcp.json") << "{}"; - const auto own = std::filesystem::weakly_canonical(linked / dead); - discovery::Entry entry{.session = dead, .project = "/work/project", .endpoint = own.generic_string(), .allow = "[]", .pid = 2147483000L, - .mcp = "http://127.0.0.1:1/mcp", .configuration = (own / "mcp.json").generic_string()}; - channel::writeEndpoint(linked / (dead + ".json"), entry.json()); - then("listing through the alias still removes its private directory", [&] { - require(discovery::list(linked).empty()); - require(!std::filesystem::exists(real / "sessions" / dead)); + requireThrows([&] { + enableAutomation(app, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); }); - then("a session directory replaced by a link is left alone", [&] { - const auto elsewhere = root.path() / "elsewhere"; - std::filesystem::create_directory(elsewhere); - std::ofstream(elsewhere / "mcp.json") << "{}"; - std::filesystem::remove_all(linked / dead); - std::filesystem::create_directory_symlink(elsewhere, linked / dead); - require(discovery::list(linked).empty()); - require(std::filesystem::exists(elsewhere / "mcp.json")); - std::filesystem::remove(linked / dead); + HttpConsumerApp untouched{.project = root.path() / "project"}; + const auto absent = root.path() / "never-created"; + requireThrows([&] { + enableAutomation(untouched, {.mcpToken = "short", .discovery = absent, .announce = false}); }); - }); -#endif - given("paths so long that the record would exceed its limit", [&] { - then("the record is refused before anything is published", [&] { - const auto session = std::string(64, 'f'); - const auto distant = "/" + std::string(discovery::recordLimit / 2, 'p'); // not "far", a Windows macro - discovery::Entry entry{.session = session, .project = distant, .endpoint = distant, .allow = "[]", .pid = discovery::currentProcess(), - .mcp = "http://127.0.0.1:1/mcp", .configuration = distant + "/mcp.json"}; - require(entry.json().size() > discovery::recordLimit); - requireThrows([&] { discovery::Registration refused{sessions, entry}; }); - require(!std::filesystem::exists(sessions / (session + ".json"))); + require(untouched.projectReads == 0); + require(untouched.registered.empty()); + require(!std::filesystem::exists(absent)); + requireThrows([&] { + Automation invalid{ + untouched, + {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = absent, .announce = false} + }; }); - }); -}}; - -const Scenario stableMcp{"A fixed MCP token and port survive activation and authentication can be explicitly disabled", [] { - using namespace mcphttptests; - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - HttpConsumerApp app{.project = root.path() / "project"}; - const auto sessions = root.path() / "sessions"; - const std::string fixed(64, 'a'); - // A port selected by the OS can be claimed between launches. Retry only that bind error, keeping each - // successful pair on the same port and token; any other failure still fails the scenario. - for (int attempt = 0; ; ++attempt) { - try { - auto first = enableAutomation(app, {.mcpToken = fixed, .discovery = sessions, .announce = false}); - require(first->banner().find("WARNING") == std::string::npos); - const auto port = static_cast(std::stoi(first->mcpUrl().substr(first->mcpUrl().rfind(':') + 1))); - const auto config = channel::readEndpoint(first->directory(), "mcp.json"); - first->close(); - for (int run = 0; run < 2; ++run) { - auto instance = enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); - require(channel::readEndpoint(instance->directory(), "mcp.json") == config); - for (const auto& entry : discovery::list(sessions)) { - std::ifstream input(sessions / (entry.session + ".json")); - std::ostringstream record; - record << input.rdbuf(); - require(record.str().find(fixed) == std::string::npos); - } - const auto opened = roundTrip(port, post(port, initialize, {}, fixed)); - require(opened.status == 200); - require(roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))).status == 401); - const auto extra = "MCP-Session-Id: " + opened.header("mcp-session-id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; - require(roundTrip(port, post(port, initialized, extra, fixed)).status == 202); - const auto result = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", extra, fixed)); - require(result.status == 200); - require(result.body.find("result") != std::string::npos); - requireThrows([&] { enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); }); - auto side = enableAutomation(app, {.discovery = sessions, .announce = false}); - require(side->mcpUrl() != instance->mcpUrl()); - side->close(); - instance->close(); - } - auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); - require(open->banner().find("WARNING: MCP authentication disabled") != std::string::npos); - require(open->banner().find("local processes can use granted operations") != std::string::npos); - require(open->banner().find("WARNING") < open->banner().find("grants:")); - require(open->banner().ends_with(open->clientConfiguration().generic_string())); - const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; - require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); - require(channel::readEndpoint(open->directory(), "mcp.json").find(fixed) == std::string::npos); - auto request = post(port, initialize); - request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); - require(roundTrip(port, request).status == 200); - require(roundTrip(port, post(port, initialize, {}, "wrong-token")).status == 200); - require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); - require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); - require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); - auto hostile = request; - hostile.replace(hostile.find("127.0.0.1"), 9, "evil.test"); - require(roundTrip(port, hostile).status == 421); - open->close(); - break; - } catch (const mcphttp::BindError& error) { - if (!error.addressInUse() || attempt == 4) - throw; - } - } - requireThrows([&] { enableAutomation(app, {.mcpToken = "", .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = "a", .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(31, 'a'), .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(1025, 'a'), .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(32, 'a') + "\r\nInjected", .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); }); - HttpConsumerApp untouched{.project = root.path() / "project"}; - const auto absent = root.path() / "never-created"; - requireThrows([&] { enableAutomation(untouched, {.mcpToken = "short", .discovery = absent, .announce = false}); }); - require(untouched.projectReads == 0); - require(untouched.registered.empty()); - require(!std::filesystem::exists(absent)); - requireThrows([&] { Automation invalid{untouched, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = absent, .announce = false}}; }); - require(untouched.projectReads == 0); - require(!std::filesystem::exists(absent)); - auto minimum = enableAutomation(app, {.mcpToken = std::string(32, 'a'), .discovery = sessions, .announce = false}); - minimum->close(); -}}; + require(untouched.projectReads == 0); + require(!std::filesystem::exists(absent)); + auto minimum = enableAutomation(app, {.mcpToken = std::string(32, 'a'), .discovery = sessions, .announce = false}); + minimum->close(); + }}; const Scenario unauthenticatedMcpBanner{"An unauthenticated MCP listener warns at startup", [] { - using namespace mcphttptests; - webfront::test::TemporaryDirectory root; - std::filesystem::create_directory(root.path() / "project"); - HttpConsumerApp app{.project = root.path() / "project"}; - std::ostringstream captured; - struct RestoreBuffer { - std::streambuf* previous; - ~RestoreBuffer() { std::cerr.rdbuf(previous); } - } restore{std::cerr.rdbuf(captured.rdbuf())}; - auto automation = enableAutomation(app, {.disableMcpAuthentication = true, .discovery = root.path() / "sessions"}); - require(captured.str().find("WARNING: MCP authentication disabled") != std::string::npos); - require(captured.str().find(automation->mcpUrl()) != std::string::npos); - automation->close(); - captured.str(""); - captured.clear(); - auto silent = enableAutomation(app, {.disableMcpAuthentication = true, .discovery = root.path() / "sessions", .announce = false}); - require(captured.str().empty()); - require(silent->banner().find("WARNING: MCP authentication disabled") != std::string::npos); - silent->close(); -}}; + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + HttpConsumerApp app{.project = root.path() / "project"}; + std::ostringstream captured; + struct RestoreBuffer { + std::streambuf* previous; + ~RestoreBuffer() { + std::cerr.rdbuf(previous); + } + } restore{std::cerr.rdbuf(captured.rdbuf())}; + auto automation = enableAutomation(app, {.disableMcpAuthentication = true, .discovery = root.path() / "sessions"}); + require(captured.str().find("WARNING: MCP authentication disabled") != std::string::npos); + require(captured.str().find(automation->mcpUrl()) != std::string::npos); + automation->close(); + captured.str(""); + captured.clear(); + auto silent = enableAutomation( + app, + {.disableMcpAuthentication = true, .discovery = root.path() / "sessions", .announce = false}); + require(captured.str().empty()); + require(silent->banner().find("WARNING: MCP authentication disabled") != std::string::npos); + silent->close(); + }}; const Scenario mcpBindError{"MCP bind errors identify an occupied address", [] { - using namespace mcphttptests; + using namespace mcphttptests; #ifdef _WIN32 - const int occupied = WSAEADDRINUSE; + const int occupied = WSAEADDRINUSE; #else const int occupied = EADDRINUSE; #endif - require(mcphttp::BindError{std::error_code{occupied, std::system_category()}, 1234}.addressInUse()); - require(!mcphttp::BindError{std::make_error_code(std::errc::permission_denied), 1234}.addressInUse()); -}}; + require(mcphttp::BindError{ + std::error_code{occupied, std::system_category()}, + 1234 + } + .addressInUse()); + require(!mcphttp::BindError{std::make_error_code(std::errc::permission_denied), 1234}.addressInUse()); + }}; diff --git a/test/unit/AutomationTests.cpp b/test/unit/AutomationTests.cpp index dabc616c..9c8d33df 100644 --- a/test/unit/AutomationTests.cpp +++ b/test/unit/AutomationTests.cpp @@ -1,8 +1,8 @@ #include "TemporaryDirectory.hpp" -#include #include #include #include +#include using namespace webfront::bdd; @@ -47,33 +47,41 @@ Object command(const Session& session, std::string operation, std::string args = } const Scenario earlierBrowser{"An earlier browser cannot claim the launched automation window", [] { - webfront::test::TemporaryDirectory directory; - auto session = std::make_shared(SessionOptions{directory.path(), {"build"}}); - BindingApp app; - Binding binding{app, session}; - const auto page = binding.launchPage(); - const auto token = page.substr(page.find('=') + 1); - require(token.size() == 64); - BindingApp::UI earlier{1}, launched{2}; - app.started(earlier); - require(earlier.scripts->size() == 1); - require(earlier.scripts->front().find(token) == std::string::npos); - require(earlier.scripts->front().find("importKey") == std::string::npos); - requireThrows([&] { app.claim(earlier, std::string(64, '0')); }); - app.closed(earlier); - require(!session->isClosed()); - app.started(launched); - requireNothrow([&] { app.claim(launched, token); }); - require(launched.scripts->size() == 2); - require(launched.scripts->back().find("importKey") != std::string::npos); - requireThrows([&] { app.claim(earlier, token); }); - requireThrows([&] { app.claim(launched, token); }); - app.closed(earlier); - require(!session->isClosed()); - app.closed(launched); - require(session->isClosed()); -}}; -Object query(const Session& session, std::string id) { + webfront::test::TemporaryDirectory directory; + auto session = std::make_shared(SessionOptions{directory.path(), {"build"}}); + BindingApp app; + Binding binding{app, session}; + const auto page = binding.launchPage(); + const auto token = page.substr(page.find('=') + 1); + require(token.size() == 64); + BindingApp::UI earlier{1}, launched{2}; + app.started(earlier); + require(earlier.scripts->size() == 1); + require(earlier.scripts->front().find(token) == std::string::npos); + require(earlier.scripts->front().find("importKey") == std::string::npos); + requireThrows([&] { + app.claim(earlier, std::string(64, '0')); + }); + app.closed(earlier); + require(!session->isClosed()); + app.started(launched); + requireNothrow([&] { + app.claim(launched, token); + }); + require(launched.scripts->size() == 2); + require(launched.scripts->back().find("importKey") != std::string::npos); + requireThrows([&] { + app.claim(earlier, token); + }); + requireThrows([&] { + app.claim(launched, token); + }); + app.closed(earlier); + require(!session->isClosed()); + app.closed(launched); + require(session->isClosed()); + }}; +Object query(const Session& session, std::string id) { return Object(objectJson({ {"session", webfront::json::quote(Object(session.describe()).string("session"))}, { "runId", webfront::json::quote(id)} @@ -82,504 +90,639 @@ Object query(const Session& session, std::string id) { } // namespace const Scenario pageCallback{"Page callback authentication matches RFC 4231 and refuses wire replay or forgery", [] { - using namespace webfront::automation::authentication; - require(hmac(std::string(20, '\x0b'), "Hi There") == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); - require(hmac("Jefe", "what do ya want for nothing?") == "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); - require(hmac(std::string(131, static_cast(0xaa)), "Test Using Larger Than Block-Size Key - Hash Key First") - == "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"); - const std::string key(64, 'a'); - PageAuthentication auth{key}; - const auto captured = hmac(key, payload("1", "poll", {"latest output é😀"})); - requireThrows([&] { auth.authorize("1", captured, "failed", {"forged by a frame"}); }); - requireThrows([&] { auth.authorize("1", captured, "poll", {"tampered output"}); }); - requireNothrow([&] { auth.authorize("1", captured, "poll", {"latest output é😀"}); }); - requireThrows([&] { auth.authorize("1", captured, "poll", {"latest output é😀"}); }); - const auto completed = hmac(key, payload("2", "complete", {"run-1", R"({"exitCode":0})"})); - requireThrows([&] { auth.authorize("2", completed, "complete", {"run-2", R"({"exitCode":0})"}); }); - requireNothrow([&] { auth.authorize("2", completed, "complete", {"run-1", R"({"exitCode":0})"}); }); - requireThrows([&] { auth.authorize("3", captured, "poll", {"latest output é😀"}); }); - requireNothrow([&] { auth.authorize("5", hmac(key, payload("5", "poll", {"after dropped messages"})), "poll", {"after dropped messages"}); }); - requireThrows([&] { auth.authorize("4", hmac(key, payload("4", "poll", {"late"})), "poll", {"late"}); }); - requireNothrow([&] { auth.authorize("8", hmac(key, payload("8", "failed", {"transport failure"})), "failed", {"transport failure"}); }); - require(hmac(key, payload("3", "complete", {"a", "bc"})) != hmac(key, payload("3", "complete", {"ab", "c"}))); - require(hmac(key, payload("3", "reply:poll", {"null"})) != hmac(key, payload("3", "poll", {"null"}))); -}}; - -const Scenario automationAuthorization{"Automation authorization stays native and binds requests to a project session", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build", "test", "inspect"}} - }; - Session other{ - {directory.path(), {"build"}} - }; - requireThrows([&] { session.start(command(session, "build")); }); - session.poll(); - given("a ready session and an authorized operation", [&] { - const auto id = Object(session.start(command(session, "build", R"({"entry":"main"})"))).string("runId"); - require(Object(session.poll()).string("operation") == "build"); - requireThrows([&] { session.start(command(session, "test")); }); - requireThrows([&] { session.complete("wrong", R"({"exitCode":0,"output":"","report":null})"); }); - session.complete(id, R"({"exitCode":1,"output":"build error","diagnostics":[{"file":"main.ts","line":2,"text":"failure"}],"report":null})"); - const Object result{session.result(query(session, id))}; - require(result.string("state") == "failed"); - require(Object(result.raw("result")).raw("diagnostics").find("main.ts") != std::string::npos); - }); - given("operations and arguments outside the native grant", [&] { - for (const auto operation : {"run", "exec", "install", "restore", "shell", "eval", "preview", "fill"}) - requireThrows([&] { session.start(command(session, operation)); }); - requireThrows([&] { session.start(command(other, "build")); }); - requireThrows([&] { session.start(command(session, "build", R"({"entry":"../escape"})")); }); - requireThrows([&] { session.start(command(session, "build", R"({"entry":"--help"})")); }); - requireThrows([&] { session.start(command(session, "build", R"({"allow":["exec"]})")); }); - requireThrows([&] { session.start(command(session, "test", R"({"pattern":"--timeout"})")); }); - require(Object(session.describe()).raw("audit").find("denied") != std::string::npos); - }); -}}; + using namespace webfront::automation::authentication; + require(hmac(std::string(20, '\x0b'), "Hi There") == "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); + require(hmac("Jefe", "what do ya want for nothing?") == "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); + require(hmac(std::string(131, static_cast(0xaa)), "Test Using Larger Than Block-Size Key - Hash Key First") + == "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"); + const std::string key(64, 'a'); + PageAuthentication auth{key}; + const auto captured = hmac(key, payload("1", "poll", {"latest output é😀"})); + requireThrows([&] { + auth.authorize("1", captured, "failed", {"forged by a frame"}); + }); + requireThrows([&] { + auth.authorize("1", captured, "poll", {"tampered output"}); + }); + requireNothrow([&] { + auth.authorize("1", captured, "poll", {"latest output é😀"}); + }); + requireThrows([&] { + auth.authorize("1", captured, "poll", {"latest output é😀"}); + }); + const auto completed = hmac(key, payload("2", "complete", {"run-1", R"({"exitCode":0})"})); + requireThrows([&] { + auth.authorize("2", completed, "complete", {"run-2", R"({"exitCode":0})"}); + }); + requireNothrow([&] { + auth.authorize("2", completed, "complete", {"run-1", R"({"exitCode":0})"}); + }); + requireThrows([&] { + auth.authorize("3", captured, "poll", {"latest output é😀"}); + }); + requireNothrow([&] { + auth.authorize("5", hmac(key, payload("5", "poll", {"after dropped messages"})), "poll", {"after dropped messages"}); + }); + requireThrows([&] { + auth.authorize("4", hmac(key, payload("4", "poll", {"late"})), "poll", {"late"}); + }); + requireNothrow([&] { + auth.authorize("8", hmac(key, payload("8", "failed", {"transport failure"})), "failed", {"transport failure"}); + }); + require(hmac(key, payload("3", "complete", {"a", "bc"})) != hmac(key, payload("3", "complete", {"ab", "c"}))); + require(hmac(key, payload("3", "reply:poll", {"null"})) != hmac(key, payload("3", "poll", {"null"}))); + }}; -const Scenario automationEntries{"Automation entries accept manifest labels while refusing unsafe paths", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build", "preview"}} - }; - session.poll(); - given("entry labels and relative paths accepted by wf", [&] { - for (const auto operation : {"build", "preview"}) { - for (const auto entry : {"main", "app:debug", "app..debug", "src/main.tsx"}) { - const auto arguments = objectJson({ - {"entry", webfront::json::quote(entry)} +const Scenario automationAuthorization{ + "Automation authorization stays native and binds requests to a project session", + [] { + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build", "test", "inspect"}} + }; + Session other{ + {directory.path(), {"build"}} + }; + requireThrows([&] { + session.start(command(session, "build")); + }); + session.poll(); + given("a ready session and an authorized operation", [&] { + const auto id = Object(session.start(command(session, "build", R"({"entry":"main"})"))).string("runId"); + require(Object(session.poll()).string("operation") == "build"); + requireThrows([&] { + session.start(command(session, "test")); + }); + requireThrows([&] { + session.complete("wrong", R"({"exitCode":0,"output":"","report":null})"); + }); + session.complete(id, R"({"exitCode":1,"output":"build error","diagnostics":[{"file":"main.ts","line":2,"text":"failure"}],"report":null})"); + const Object result{session.result(query(session, id))}; + require(result.string("state") == "failed"); + require(Object(result.raw("result")).raw("diagnostics").find("main.ts") != std::string::npos); + }); + given("operations and arguments outside the native grant", [&] { + for (const auto operation : {"run", "exec", "install", "restore", "shell", "eval", "preview", "fill"}) + requireThrows([&] { + session.start(command(session, operation)); }); - const auto id = Object(session.start(command(session, operation, arguments))).string("runId"); - const Object dispatched{session.poll()}; - require(Object(dispatched.raw("arguments")).string("entry") == entry); - session.complete(id, R"({"exitCode":0,"output":"","report":null})"); - } - } - }); - given("paths that cannot name manifest entries", [&] { - for (const auto entry : {"../escape", "/absolute", "--help", "C:/escape", "src/../escape", "src\\main.ts", "src/app:debug.ts"}) { - const auto arguments = objectJson({ - {"entry", webfront::json::quote(entry)} + requireThrows([&] { + session.start(command(other, "build")); }); - requireThrows([&] { session.start(command(session, "build", arguments)); }); - } - }); -}}; + requireThrows([&] { + session.start(command(session, "build", R"({"entry":"../escape"})")); + }); + requireThrows([&] { + session.start(command(session, "build", R"({"entry":"--help"})")); + }); + requireThrows([&] { + session.start(command(session, "build", R"({"allow":["exec"]})")); + }); + requireThrows([&] { + session.start(command(session, "test", R"({"pattern":"--timeout"})")); + }); + require(Object(session.describe()).raw("audit").find("denied") != std::string::npos); + }); + }}; + +const Scenario automationEntries{"Automation entries accept manifest labels while refusing unsafe paths", [] { + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build", "preview"}} + }; + session.poll(); + given("entry labels and relative paths accepted by wf", [&] { + for (const auto operation : {"build", "preview"}) { + for (const auto entry : {"main", "app:debug", "app..debug", "src/main.tsx"}) { + const auto arguments = objectJson({ + {"entry", webfront::json::quote(entry)} + }); + const auto id = Object(session.start(command(session, operation, arguments))).string("runId"); + const Object dispatched{session.poll()}; + require(Object(dispatched.raw("arguments")).string("entry") == entry); + session.complete(id, R"({"exitCode":0,"output":"","report":null})"); + } + } + }); + given("paths that cannot name manifest entries", [&] { + for (const auto entry : + {"../escape", "/absolute", "--help", "C:/escape", "src/../escape", "src\\main.ts", "src/app:debug.ts"}) { + const auto arguments = objectJson({ + {"entry", webfront::json::quote(entry)} + }); + requireThrows([&] { + session.start(command(session, "build", arguments)); + }); + } + }); + }}; const Scenario projectSetup{"Project setup operations need their own grants and plain arguments", [] { - webfront::test::TemporaryDirectory directory; - Session denied{ - {directory.path(), {"build"}} - }; - Session session{ - {directory.path(), {"init", "create", "install", "restore", "embed"}} - }; - denied.poll(); - session.poll(); - const auto accepted = [&](const char* operation, const char* arguments) { - const auto id = Object(session.start(command(session, operation, arguments))).string("runId"); - session.poll(); - session.complete(id, R"({"exitCode":0,"output":"","report":null})"); - }; - given("grants that older environments cannot run", [&] { - require(denied.versionedOperations().empty()); - const auto versioned = session.versionedOperations(); - require(versioned.size() == 5); - for (const auto& [operation, since] : versioned) - require(since == "0.6.4"); - require(webfront::automation::connectionScript("secret", versioned).find("[\"embed\",\"0.6.4\"]") != std::string::npos); - }); - given("a session without those grants", [&] { - for (const auto operation : {"init", "create", "install", "restore", "embed"}) - requireThrows([&] { denied.start(command(denied, operation, operation == std::string_view("create") ? R"({"starter":"life"})" : "{}")); }); - }); - given("granted operations with valid arguments", [&] { - accepted("init", R"({"name":"demo"})"); - accepted("create", R"({"starter":"life","directory":"ui"})"); - accepted("install", "{}"); - accepted("install", R"({"package":"react@19.3.1"})"); - accepted("restore", "{}"); - accepted("embed", R"({"provider":"LifeUI"})"); - accepted("embed", R"({"entry":"ui/main.tsx","output":"generated/LifeUI.hpp"})"); - }); - given("options, escapes and incomplete requests", [&] { - requireThrows([&] { session.start(command(session, "create", "{}")); }); - requireThrows([&] { session.start(command(session, "create", R"({"starter":"--help"})")); }); - requireThrows([&] { session.start(command(session, "create", R"({"starter":"life","directory":"../escape"})")); }); - requireThrows([&] { session.start(command(session, "create", R"({"starter":"life","directory":"/absolute"})")); }); - requireThrows([&] { session.start(command(session, "install", R"({"package":"--update"})")); }); - requireThrows([&] { session.start(command(session, "install", R"({"package":"a b"})")); }); - requireThrows([&] { session.start(command(session, "init", R"({"name":"-x"})")); }); - requireThrows([&] { session.start(command(session, "restore", R"({"offline":"true"})")); }); - requireThrows([&] { session.start(command(session, "embed", "{}")); }); - requireThrows([&] { session.start(command(session, "embed", R"({"entry":"ui/main.tsx"})")); }); - requireThrows([&] { session.start(command(session, "embed", R"({"provider":"LifeUI","output":"a.hpp"})")); }); - requireThrows([&] { session.start(command(session, "embed", R"({"entry":"ui/main.tsx","output":"../a.hpp"})")); }); - }); -}}; + webfront::test::TemporaryDirectory directory; + Session denied{ + {directory.path(), {"build"}} + }; + Session session{ + {directory.path(), {"init", "create", "install", "restore", "embed"}} + }; + denied.poll(); + session.poll(); + const auto accepted = [&](const char* operation, const char* arguments) { + const auto id = Object(session.start(command(session, operation, arguments))).string("runId"); + session.poll(); + session.complete(id, R"({"exitCode":0,"output":"","report":null})"); + }; + given("grants that older environments cannot run", [&] { + require(denied.versionedOperations().empty()); + const auto versioned = session.versionedOperations(); + require(versioned.size() == 5); + for (const auto& [operation, since] : versioned) + require(since == "0.6.4"); + require(webfront::automation::connectionScript("secret", versioned).find("[\"embed\",\"0.6.4\"]") != std::string::npos); + }); + given("a session without those grants", [&] { + for (const auto operation : {"init", "create", "install", "restore", "embed"}) + requireThrows([&] { + denied.start(command(denied, operation, operation == std::string_view("create") ? R"({"starter":"life"})" : "{}")); + }); + }); + given("granted operations with valid arguments", [&] { + accepted("init", R"({"name":"demo"})"); + accepted("create", R"({"starter":"life","directory":"ui"})"); + accepted("install", "{}"); + accepted("install", R"({"package":"react@19.3.1"})"); + accepted("restore", "{}"); + accepted("embed", R"({"provider":"LifeUI"})"); + accepted("embed", R"({"entry":"ui/main.tsx","output":"generated/LifeUI.hpp"})"); + }); + given("options, escapes and incomplete requests", [&] { + requireThrows([&] { + session.start(command(session, "create", "{}")); + }); + requireThrows([&] { + session.start(command(session, "create", R"({"starter":"--help"})")); + }); + requireThrows([&] { + session.start(command(session, "create", R"({"starter":"life","directory":"../escape"})")); + }); + requireThrows([&] { + session.start(command(session, "create", R"({"starter":"life","directory":"/absolute"})")); + }); + requireThrows([&] { + session.start(command(session, "install", R"({"package":"--update"})")); + }); + requireThrows([&] { + session.start(command(session, "install", R"({"package":"a b"})")); + }); + requireThrows([&] { + session.start(command(session, "init", R"({"name":"-x"})")); + }); + requireThrows([&] { + session.start(command(session, "restore", R"({"offline":"true"})")); + }); + requireThrows([&] { + session.start(command(session, "embed", "{}")); + }); + requireThrows([&] { + session.start(command(session, "embed", R"({"entry":"ui/main.tsx"})")); + }); + requireThrows([&] { + session.start(command(session, "embed", R"({"provider":"LifeUI","output":"a.hpp"})")); + }); + requireThrows([&] { + session.start(command(session, "embed", R"({"entry":"ui/main.tsx","output":"../a.hpp"})")); + }); + }); + }}; const Scenario authorizationPrecedes{"Authorization precedes operation and argument validation", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - const auto identity = Object(session.describe()).string("session"); - require(identity.size() == 64); - Session other{ - {directory.path(), {"build"}} - }; - require(Object(other.describe()).string("session") != identity); - const auto refuses = [&](const Object& request, std::string_view code) { - try { - session.start(request); - fail("Unauthorized request was accepted"); - } catch (const OperationError& error) { - require(error.code == code); - } - }; - for (const auto operation : {"build", "exec", "unknown"}) { - refuses(Object(objectJson({ - { "session", "\"wrong\""}, - {"operation", webfront::json::quote(operation)}, - {"arguments", "17"} - })), - "wrong_session"); - } - refuses(Object(R"({"session":17,"operation":false,"arguments":17})"), "wrong_session"); - refuses(command(session, "test", "17"), "not_authorized"); - const auto audit = Object(session.describe()).raw("audit"); - require(audit.find("denied") != std::string::npos); - require(audit.find("unknown") != std::string::npos); - require(audit.find("test") != std::string::npos); -}}; + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + const auto identity = Object(session.describe()).string("session"); + require(identity.size() == 64); + Session other{ + {directory.path(), {"build"}} + }; + require(Object(other.describe()).string("session") != identity); + const auto refuses = [&](const Object& request, std::string_view code) { + try { + session.start(request); + fail("Unauthorized request was accepted"); + } catch (const OperationError& error) { + require(error.code == code); + } + }; + for (const auto operation : {"build", "exec", "unknown"}) { + refuses(Object(objectJson({ + { "session", "\"wrong\""}, + {"operation", webfront::json::quote(operation)}, + {"arguments", "17"} + })), + "wrong_session"); + } + refuses(Object(R"({"session":17,"operation":false,"arguments":17})"), "wrong_session"); + refuses(command(session, "test", "17"), "not_authorized"); + const auto audit = Object(session.describe()).raw("audit"); + require(audit.find("denied") != std::string::npos); + require(audit.find("unknown") != std::string::npos); + require(audit.find("test") != std::string::npos); + }}; const Scenario exitCode130{"Exit code 130 needs an actual cancellation request", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - session.poll(); - const auto first = Object(session.start(command(session, "build"))).string("runId"); - session.poll(); - session.complete(first, R"({"exitCode":130,"output":"script exit","report":null})"); - require(Object(session.result(query(session, first))).string("state") == "failed"); - const auto second = Object(session.start(command(session, "build"))).string("runId"); - session.poll(); - session.complete(second, R"({"exitCode":130,"output":"human stop","report":null,"cancelled":true})"); - require(Object(session.result(query(session, second))).string("state") == "cancelled"); -}}; + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + session.poll(); + const auto first = Object(session.start(command(session, "build"))).string("runId"); + session.poll(); + session.complete(first, R"({"exitCode":130,"output":"script exit","report":null})"); + require(Object(session.result(query(session, first))).string("state") == "failed"); + const auto second = Object(session.start(command(session, "build"))).string("runId"); + session.poll(); + session.complete(second, R"({"exitCode":130,"output":"human stop","report":null,"cancelled":true})"); + require(Object(session.result(query(session, second))).string("state") == "cancelled"); + }}; const Scenario automationCancellation{"Automation cancellation and native deadlines cannot reuse a stalled renderer", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}, std::chrono::seconds{1}} - }; - session.poll(); - const auto id = Object(session.start(command(session, "build"))).string("runId"); - given("cancellation before dispatch", [&] { - session.cancel(query(session, id)); - require(session.poll() == "null"); - require(Object(session.result(query(session, id))).string("state") == "cancelled"); - requireNothrow([&] { session.start(command(session, "build")); }); - }); - given("cancellation after dispatch", [&] { - session.poll(); - session.cancel(query(session, id)); - require(Object(session.poll()).string("cancel") == id); - session.complete(id, R"({"exitCode":130,"output":"stopped","report":null})"); - require(Object(session.result(query(session, id))).string("state") == "cancelled"); - }); - given("a native deadline, independent of JS callbacks", [&] { - require(!session.expire()); - require(session.expire(std::chrono::steady_clock::now() + std::chrono::seconds{2})); - require(session.isClosed()); - require(Object(session.result(query(session, id))).string("state") == "timeout"); - requireThrows([&] { session.complete(id, R"({"exitCode":0,"output":"","report":null})"); }); - requireThrows([&] { session.start(command(session, "build")); }); - }); -}}; + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}, std::chrono::seconds{1}} + }; + session.poll(); + const auto id = Object(session.start(command(session, "build"))).string("runId"); + given("cancellation before dispatch", [&] { + session.cancel(query(session, id)); + require(session.poll() == "null"); + require(Object(session.result(query(session, id))).string("state") == "cancelled"); + requireNothrow([&] { + session.start(command(session, "build")); + }); + }); + given("cancellation after dispatch", [&] { + session.poll(); + session.cancel(query(session, id)); + require(Object(session.poll()).string("cancel") == id); + session.complete(id, R"({"exitCode":130,"output":"stopped","report":null})"); + require(Object(session.result(query(session, id))).string("state") == "cancelled"); + }); + given("a native deadline, independent of JS callbacks", [&] { + require(!session.expire()); + require(session.expire(std::chrono::steady_clock::now() + std::chrono::seconds{2})); + require(session.isClosed()); + require(Object(session.result(query(session, id))).string("state") == "timeout"); + requireThrows([&] { + session.complete(id, R"({"exitCode":0,"output":"","report":null})"); + }); + requireThrows([&] { + session.start(command(session, "build")); + }); + }); + }}; const Scenario automationStartup{"Automation startup expiry respects readiness at the deadline", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{1}; - require(!session.expireStartup(deadline, deadline - std::chrono::milliseconds{1})); - given("the renderer has polled before expiry is checked", [&] { - session.poll(); - require(!session.expireStartup(deadline, deadline)); - require(!session.isClosed()); - }); - given("the renderer has not polled at the deadline", [&] { - require(session.expireStartup(deadline, deadline)); - require(session.isClosed()); - requireThrows([&] { session.start(command(session, "build")); }); - require(!session.expireStartup(deadline, deadline)); - }); -}}; + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{1}; + require(!session.expireStartup(deadline, deadline - std::chrono::milliseconds{1})); + given("the renderer has polled before expiry is checked", [&] { + session.poll(); + require(!session.expireStartup(deadline, deadline)); + require(!session.isClosed()); + }); + given("the renderer has not polled at the deadline", [&] { + require(session.expireStartup(deadline, deadline)); + require(session.isClosed()); + requireThrows([&] { + session.start(command(session, "build")); + }); + require(!session.expireStartup(deadline, deadline)); + }); + }}; -const Scenario mCPInitialization{"MCP initialization, tool errors and request identifiers follow the supported profile", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {}} - }; - Mcp mcp{session}; - require(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":1,"method":"tools/list"})")).has("error")); - const Object initialized{*mcp.receive( - R"({"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"test","version":"1"},"capabilities":{}}})")}; - require(initialized.string("id") == "init"); - require(Object(initialized.raw("result")).string("protocolVersion") == "2025-11-25"); - require(!mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/initialized"})")); - require(mcp.receive(R"({"jsonrpc":"2.0","id":41,"method":"tools/list"})")->find('\n') == std::string::npos); - require(Object(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":42,"method":"tools/list"})")).raw("result")).raw("tools").find("webfront.start") - != std::string::npos); - const Object tool{ - Object(*mcp.receive( - R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":"wrong","operation":"exec"}}})")) - .raw("result")}; - require(tool.raw("isError") == "true"); - require(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":null,"method":"ping"})")).has("error")); - for (const auto id : {"1.0", "1e2", "-0.25", "123456789012345678901234567890"}) { - const Object reply{*mcp.receive(std::string{"{\"jsonrpc\":\"2.0\",\"id\":"} + id + ",\"method\":\"ping\"}")}; - require(!reply.has("error")); - require(reply.raw("id") == id); - } - require(Object(*mcp.receive("{bad")).has("error")); - require(!mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":42}})")); - for (const auto notification : {R"({"jsonrpc":"1.0","method":"ping"})", R"({"jsonrpc":"2.0"})", R"({"method":"ping"})", R"({"jsonrpc":"2.0","method":17})"}) - require(!mcp.receive(notification)); - require(Object(*mcp.receive(R"({"jsonrpc":"1.0","id":7,"method":"ping"})")).has("error")); -}}; +const Scenario mCPInitialization{ + "MCP initialization, tool errors and request identifiers follow the supported profile", + [] { + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {}} + }; + Mcp mcp{session}; + require(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":1,"method":"tools/list"})")).has("error")); + const Object initialized{*mcp.receive( + R"({"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"test","version":"1"},"capabilities":{}}})")}; + require(initialized.string("id") == "init"); + require(Object(initialized.raw("result")).string("protocolVersion") == "2025-11-25"); + require(!mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/initialized"})")); + require(mcp.receive(R"({"jsonrpc":"2.0","id":41,"method":"tools/list"})")->find('\n') == std::string::npos); + require(Object(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":42,"method":"tools/list"})")).raw("result")).raw("tools").find("webfront.start") + != std::string::npos); + const Object tool{ + Object( + *mcp.receive( + R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":"wrong","operation":"exec"}}})")) + .raw("result")}; + require(tool.raw("isError") == "true"); + require(Object(*mcp.receive(R"({"jsonrpc":"2.0","id":null,"method":"ping"})")).has("error")); + for (const auto id : {"1.0", "1e2", "-0.25", "123456789012345678901234567890"}) { + const Object reply{*mcp.receive(std::string{"{\"jsonrpc\":\"2.0\",\"id\":"} + id + ",\"method\":\"ping\"}")}; + require(!reply.has("error")); + require(reply.raw("id") == id); + } + require(Object(*mcp.receive("{bad")).has("error")); + require(!mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":42}})")); + for (const auto notification : + {R"({"jsonrpc":"1.0","method":"ping"})", R"({"jsonrpc":"2.0"})", R"({"method":"ping"})", R"({"jsonrpc":"2.0","method":17})"}) + require(!mcp.receive(notification)); + require(Object(*mcp.receive(R"({"jsonrpc":"1.0","id":7,"method":"ping"})")).has("error")); + }}; const Scenario automationAudit{"Automation audit retains authorization decisions through busy and malformed retries", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - requireThrows([&] { session.start(command(session, "build")); }); - require(Object(session.describe()).raw("audit") == "[]"); - session.poll(); - requireThrows([&] { session.start(command(session, "test")); }); - const auto denied = Object(session.describe()).raw("audit"); - require(denied.find("\"operation\":\"test\"") != std::string::npos); - const auto id = Object(session.start(command(session, "build"))).string("runId"); - const auto audit = Object(session.describe()).raw("audit"); - require(audit.find(id) != std::string::npos); - for (int i = 0; i < 100; ++i) { - requireThrows([&] { session.start(command(session, "build")); }); - requireThrows([&] { session.start(command(session, "build", R"({"entry":"../escape"})")); }); - } - require(Object(session.describe()).raw("audit") == audit); - session.poll(); - session.complete(id, R"({"exitCode":0,"output":"","report":null})"); - require(Object(session.describe()).raw("audit") == audit); -}}; + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + requireThrows([&] { + session.start(command(session, "build")); + }); + require(Object(session.describe()).raw("audit") == "[]"); + session.poll(); + requireThrows([&] { + session.start(command(session, "test")); + }); + const auto denied = Object(session.describe()).raw("audit"); + require(denied.find("\"operation\":\"test\"") != std::string::npos); + const auto id = Object(session.start(command(session, "build"))).string("runId"); + const auto audit = Object(session.describe()).raw("audit"); + require(audit.find(id) != std::string::npos); + for (int i = 0; i < 100; ++i) { + requireThrows([&] { + session.start(command(session, "build")); + }); + requireThrows([&] { + session.start(command(session, "build", R"({"entry":"../escape"})")); + }); + } + require(Object(session.describe()).raw("audit") == audit); + session.poll(); + session.complete(id, R"({"exitCode":0,"output":"","report":null})"); + require(Object(session.describe()).raw("audit") == audit); + }}; const Scenario automationJSON{"Automation JSON rejects duplicate keys, non-UTF8 and deeply nested or oversized input", [] { - requireThrows([&] { Object(R"({"operation":"build","operation":"exec"})"); }); - requireThrows([&] { Object(std::string(60001, ' ')); }); - requireThrows([&] { Object(std::string("{\"x\":\"") + std::string("\xC0\xAF", 2) + "\"}"); }); - requireThrows([&] { Object(std::string("{\"x\":") + std::string(33, '[') + "0" + std::string(33, ']') + "}"); }); - requireNothrow([&] { Object(R"({"x":"é😀","nested":[{"number":-1.25e+2}]})"); }); - requireThrows([&] { Object("{} trailing"); }); -}}; + requireThrows([&] { + Object(R"({"operation":"build","operation":"exec"})"); + }); + requireThrows([&] { + Object(std::string(60001, ' ')); + }); + requireThrows([&] { + Object(std::string("{\"x\":\"") + std::string("\xC0\xAF", 2) + "\"}"); + }); + requireThrows([&] { + Object(std::string("{\"x\":") + std::string(33, '[') + "0" + std::string(33, ']') + "}"); + }); + requireNothrow([&] { + Object(R"({"x":"é😀","nested":[{"number":-1.25e+2}]})"); + }); + requireThrows([&] { + Object("{} trailing"); + }); + }}; const Scenario versionedOperation{"The versioned operation schema projects the same fields and permissions to native and MCP clients", [] { - using namespace webfront::automation; - const Object contract{contractSource}; - const Object properties{contract.raw("properties")}; - const auto names = contractStrings(Object(properties.raw("operation")).raw("enum")); - const Object definitions{contract.raw("x-webfront-operations")}; - require(names.size() == definitions.members().size()); - const Object arguments{Object(properties.raw("arguments")).raw("properties")}; - for (const auto& name : names) { - const auto definition = operationContract(name); - require(!definition.string("permission").empty()); - const auto allowed = contractStrings(definition.raw("arguments")); - for (const auto& field : allowed) - require(arguments.has(field)); - for (const auto& field : contractStrings(definition.raw("required"))) - require(std::ranges::find(allowed, field) != allowed.end()); - } - require(Object(startSchema()).has("properties")); - require(&contractObject() == &contractObject()); - require(&operationContract("build") == &operationContract("build")); - require(&startSchema() == &startSchema()); -}}; + using namespace webfront::automation; + const Object contract{contractSource}; + const Object properties{contract.raw("properties")}; + const auto names = contractStrings(Object(properties.raw("operation")).raw("enum")); + const Object definitions{contract.raw("x-webfront-operations")}; + require(names.size() == definitions.members().size()); + const Object arguments{Object(properties.raw("arguments")).raw("properties")}; + for (const auto& name : names) { + const auto definition = operationContract(name); + require(!definition.string("permission").empty()); + const auto allowed = contractStrings(definition.raw("arguments")); + for (const auto& field : allowed) + require(arguments.has(field)); + for (const auto& field : contractStrings(definition.raw("required"))) + require(std::ranges::find(allowed, field) != allowed.end()); + } + require(Object(startSchema()).has("properties")); + require(&contractObject() == &contractObject()); + require(&operationContract("build") == &operationContract("build")); + require(&startSchema() == &startSchema()); + }}; const Scenario completedAutomation{"A completed automation snapshot replaces progress with the final bounded output", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - session.poll(); - const auto id = Object(session.start(command(session, "build"))).string("runId"); - session.poll("last progress tail"); - const auto output = std::string(12000, 'x') + "final summary"; - session.complete(id, - objectJson({ - {"exitCode", "0"}, - { "output", webfront::json::quote(output)}, - { "report", "null"} - })); - const Object result{session.result(query(session, id))}; - require(result.string("output") == output); - require(result.string("output") == Object(result.raw("result")).string("output")); + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + session.poll(); + const auto id = Object(session.start(command(session, "build"))).string("runId"); + session.poll("last progress tail"); + const auto output = std::string(12000, 'x') + "final summary"; + session.complete(id, + objectJson({ + {"exitCode", "0"}, + { "output", webfront::json::quote(output)}, + { "report", "null"} + })); + const Object result{session.result(query(session, id))}; + require(result.string("output") == output); + require(result.string("output") == Object(result.raw("result")).string("output")); - const auto next = Object(session.start(command(session, "build"))).string("runId"); - require(Object(session.result(query(session, next))).string("output").empty()); - require(Object(session.poll("previous runner output")).string("runId") == next); - require(Object(session.result(query(session, next))).string("output").empty()); - session.poll("new run progress"); - require(Object(session.result(query(session, next))).string("output") == "new run progress"); -}}; + const auto next = Object(session.start(command(session, "build"))).string("runId"); + require(Object(session.result(query(session, next))).string("output").empty()); + require(Object(session.poll("previous runner output")).string("runId") == next); + require(Object(session.result(query(session, next))).string("output").empty()); + session.poll("new run progress"); + require(Object(session.result(query(session, next))).string("output") == "new run progress"); + }}; const Scenario completionNative{"A completion the native side cannot validate fails its run instead of wedging the session", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {directory.path(), {"build"}} - }; - session.poll(); - given("a running operation", [&] { - const auto id = Object(session.start(command(session, "build"))).string("runId"); - require(Object(session.poll()).string("operation") == "build"); - when("the page reports a lone surrogate, which no bridge string can carry", [&] { - requireNothrow([&] { session.complete(id, "{\"exitCode\":0,\"output\":\"cut \\ud83d\"}"); }); - then("the run fails with the reason and the session stays usable", [&] { - const Object result{session.result(query(session, id))}; - require(result.string("state") == "failed"); - require(Object(result.raw("result")).string("output").find("Invalid automation completion") != std::string::npos); - require(!session.expire(std::chrono::steady_clock::now() + std::chrono::hours{1})); - require(!session.isClosed()); - requireNothrow([&] { session.start(command(session, "build")); }); + webfront::test::TemporaryDirectory directory; + Session session{ + {directory.path(), {"build"}} + }; + session.poll(); + given("a running operation", [&] { + const auto id = Object(session.start(command(session, "build"))).string("runId"); + require(Object(session.poll()).string("operation") == "build"); + when("the page reports a lone surrogate, which no bridge string can carry", [&] { + requireNothrow([&] { + session.complete(id, "{\"exitCode\":0,\"output\":\"cut \\ud83d\"}"); + }); + then("the run fails with the reason and the session stays usable", [&] { + const Object result{session.result(query(session, id))}; + require(result.string("state") == "failed"); + require(Object(result.raw("result")).string("output").find("Invalid automation completion") + != std::string::npos); + require(!session.expire(std::chrono::steady_clock::now() + std::chrono::hours{1})); + require(!session.isClosed()); + requireNothrow([&] { + session.start(command(session, "build")); + }); + }); + }); + when("the page reports an exit code out of range", [&] { + session.complete(id, R"({"exitCode":999,"output":""})"); + then("the run fails as well", [&] { + require(Object(session.result(query(session, id))).string("state") == "failed"); + }); + }); + when("an invalid completion has a very long unexpected member name", [&] { + session.complete(id, + objectJson({ + {std::string(50000, 'x'), "0"} + })); + const Object result{session.result(query(session, id))}; + require(result.string("state") == "failed"); + require(result.string("output").size() < 1200); + require(result.string("output") == Object(result.raw("result")).string("output")); + requireNothrow([&] { + session.start(command(session, "build")); + }); + }); + }); + }}; + +const Scenario mCPErrors{ + "MCP errors keep the request id and distinguish a lost transport from bad arguments", + [] { + struct LostBackend { + std::string describe() const { + throw TransportError("Native attachment is unavailable"); + } + std::string start(const Object&) const { + throw TransportError("Native attachment receive deadline exceeded"); + } + std::string result(const Object&) const { + return "{}"; + } + std::string cancel(const Object&) const { + return "{}"; + } + } backend; + Mcp mcp{backend}; + mcp.receive( + R"({"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"test","version":"1"},"capabilities":{}}})"); + mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/initialized"})"); + given("a request with a valid id but a wrong version or no method", [&] { + const Object wrongVersion{*mcp.receive(R"({"jsonrpc":"1.0","id":7,"method":"ping"})")}; + then("the error answers that id with the invalid-request code", [&] { + require(wrongVersion.raw("id") == "7"); + require(Object(wrongVersion.raw("error")).raw("code") == "-32600"); + const Object noMethod{*mcp.receive(R"({"jsonrpc":"2.0","id":8})")}; + require(noMethod.raw("id") == "8"); + require(Object(noMethod.raw("error")).raw("code") == "-32600"); + const Object extra{*mcp.receive(R"({"jsonrpc":"2.0","id":9,"method":"ping","other":1})")}; + require(extra.raw("id") == "9"); + require(Object(extra.raw("error")).raw("code") == "-32600"); }); - }); - when("the page reports an exit code out of range", [&] { - session.complete(id, R"({"exitCode":999,"output":""})"); - then("the run fails as well", [&] { - require(Object(session.result(query(session, id))).string("state") == "failed"); + then("only unparseable input is a parse error, without an id", [&] { + const Object broken{*mcp.receive("{bad")}; + require(broken.raw("id") == "null"); + require(Object(broken.raw("error")).raw("code") == "-32700"); }); }); - when("an invalid completion has a very long unexpected member name", [&] { - session.complete(id, - objectJson({ - {std::string(50000, 'x'), "0"} - })); - const Object result{session.result(query(session, id))}; - require(result.string("state") == "failed"); - require(result.string("output").size() < 1200); - require(result.string("output") == Object(result.raw("result")).string("output")); - requireNothrow([&] { session.start(command(session, "build")); }); - }); - }); -}}; - -const Scenario mCPErrors{"MCP errors keep the request id and distinguish a lost transport from bad arguments", [] { - struct LostBackend { - std::string describe() const { - throw TransportError("Native attachment is unavailable"); - } - std::string start(const Object&) const { - throw TransportError("Native attachment receive deadline exceeded"); - } - std::string result(const Object&) const { - return "{}"; - } - std::string cancel(const Object&) const { - return "{}"; - } - } backend; - Mcp mcp{backend}; - mcp.receive( - R"({"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"test","version":"1"},"capabilities":{}}})"); - mcp.receive(R"({"jsonrpc":"2.0","method":"notifications/initialized"})"); - given("a request with a valid id but a wrong version or no method", [&] { - const Object wrongVersion{*mcp.receive(R"({"jsonrpc":"1.0","id":7,"method":"ping"})")}; - then("the error answers that id with the invalid-request code", [&] { - require(wrongVersion.raw("id") == "7"); - require(Object(wrongVersion.raw("error")).raw("code") == "-32600"); - const Object noMethod{*mcp.receive(R"({"jsonrpc":"2.0","id":8})")}; - require(noMethod.raw("id") == "8"); - require(Object(noMethod.raw("error")).raw("code") == "-32600"); - const Object extra{*mcp.receive(R"({"jsonrpc":"2.0","id":9,"method":"ping","other":1})")}; - require(extra.raw("id") == "9"); - require(Object(extra.raw("error")).raw("code") == "-32600"); - }); - then("only unparseable input is a parse error, without an id", [&] { - const Object broken{*mcp.receive("{bad")}; - require(broken.raw("id") == "null"); - require(Object(broken.raw("error")).raw("code") == "-32700"); - }); - }); - given("a backend whose channel to the owner failed", [&] { - const Object tool{ - Object(*mcp.receive( - R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":"s","operation":"build"}}})")) - .raw("result")}; - then("the tool reports disconnected, not invalid arguments, and says the outcome is unknown", [&] { - require(tool.raw("isError") == "true"); - const Object content{tool.raw("structuredContent")}; - require(content.string("code") == "disconnected"); - require(content.string("error").find("outcome") != std::string::npos); + given("a backend whose channel to the owner failed", [&] { + const Object tool{ + Object( + *mcp.receive( + R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.start","arguments":{"session":"s","operation":"build"}}})")) + .raw("result")}; + then("the tool reports disconnected, not invalid arguments, and says the outcome is unknown", [&] { + require(tool.raw("isError") == "true"); + const Object content{tool.raw("structuredContent")}; + require(content.string("code") == "disconnected"); + require(content.string("error").find("outcome") != std::string::npos); + }); }); - }); -}}; + }}; -const Scenario applicationCallback{"An application callback is called only when its name was allow-listed with the call grant", [] { - webfront::test::TemporaryDirectory directory; - Session session{ - {.project = directory.path(), .allow = {"call"}, .callbacks = {"app.render", "app.count"}} - }; - Session withoutList{ - {directory.path(), {"call"}} - }; - Session withoutGrant{ - {directory.path(), {"check"}} - }; - session.poll(); - withoutList.poll(); - withoutGrant.poll(); - given("the names the owner allow-listed", [&] { - const Object described{session.describe()}; - require(described.raw("callbacks") == R"(["app.render","app.count"])"); - require(Object(withoutList.describe()).raw("callbacks") == "[]"); - const auto versioned = session.versionedOperations(); - require(versioned.size() == 1); - require(versioned[0].first == "call"); - require(versioned[0].second == "0.6.6"); - then("a call to one of them, with or without a string argument, is accepted", [&] { - const auto id = Object(session.start(command(session, "call", R"({"callback":"app.render","value":"text"})"))).string("runId"); - require(Object(session.poll()).string("operation") == "call"); - session.complete(id, R"({"exitCode":0,"output":"","report":null,"data":{"callback":"app.render","result":"rendered:text"}})"); - const auto next = Object(session.start(command(session, "call", R"({"callback":"app.count"})"))).string("runId"); - session.poll(); - session.complete(next, R"({"exitCode":0,"output":"","report":null})"); - }); - }); - given("a callback that was not allow-listed", [&] { - then("it is refused and audited, whatever its name", [&] { - for (const auto* name : {"app.secret", "app.render.extra", "app", "APP.RENDER"}) - requireThrows([&] { session.start(command(session, "call", std::string(R"({"callback":")") + name + "\"}")); }); - require(Object(session.describe()).raw("audit").find("\"decision\":\"denied\"") != std::string::npos); +const Scenario applicationCallback{ + "An application callback is called only when its name was allow-listed with the call grant", + [] { + webfront::test::TemporaryDirectory directory; + Session session{ + {.project = directory.path(), .allow = {"call"}, .callbacks = {"app.render", "app.count"}} + }; + Session withoutList{ + {directory.path(), {"call"}} + }; + Session withoutGrant{ + {directory.path(), {"check"}} + }; + session.poll(); + withoutList.poll(); + withoutGrant.poll(); + given("the names the owner allow-listed", [&] { + const Object described{session.describe()}; + require(described.raw("callbacks") == R"(["app.render","app.count"])"); + require(Object(withoutList.describe()).raw("callbacks") == "[]"); + const auto versioned = session.versionedOperations(); + require(versioned.size() == 1); + require(versioned[0].first == "call"); + require(versioned[0].second == "0.6.6"); + then("a call to one of them, with or without a string argument, is accepted", [&] { + const auto id = Object(session.start(command(session, "call", R"({"callback":"app.render","value":"text"})"))).string("runId"); + require(Object(session.poll()).string("operation") == "call"); + session.complete(id, R"({"exitCode":0,"output":"","report":null,"data":{"callback":"app.render","result":"rendered:text"}})"); + const auto next = Object(session.start(command(session, "call", R"({"callback":"app.count"})"))).string("runId"); + session.poll(); + session.complete(next, R"({"exitCode":0,"output":"","report":null})"); + }); }); - then("a session without a list, or without the grant, refuses every call", [&] { - requireThrows([&] { withoutList.start(command(withoutList, "call", R"({"callback":"app.render"})")); }); - requireThrows([&] { withoutGrant.start(command(withoutGrant, "call", R"({"callback":"app.render"})")); }); + given("a callback that was not allow-listed", [&] { + then("it is refused and audited, whatever its name", [&] { + for (const auto* name : {"app.secret", "app.render.extra", "app", "APP.RENDER"}) + requireThrows([&] { + session.start(command(session, "call", std::string(R"({"callback":")") + name + "\"}")); + }); + require(Object(session.describe()).raw("audit").find("\"decision\":\"denied\"") != std::string::npos); + }); + then("a session without a list, or without the grant, refuses every call", [&] { + requireThrows([&] { + withoutList.start(command(withoutList, "call", R"({"callback":"app.render"})")); + }); + requireThrows([&] { + withoutGrant.start(command(withoutGrant, "call", R"({"callback":"app.render"})")); + }); + }); }); - }); - given("names and arguments that could reach internals", [&] { - then("webfront.* names, odd characters and extra arguments are refused before any allow-list lookup", [&] { - const auto make = [&](std::vector allow, std::vector callbacks) { - return Session{webfront::automation::SessionOptions{.project = directory.path(), .allow = std::move(allow), .callbacks = std::move(callbacks)}}; - }; - requireThrows([&] { make({"call"}, {"webfront.developer.read"}); }); - requireThrows([&] { make({"call"}, {"app render"}); }); - requireThrows([&] { make({"call"}, {""}); }); - requireThrows([&] { make({"check"}, {"app.render"}); }); // names need the grant - requireThrows([&] { session.start(command(session, "call", "{}")); }); - requireThrows([&] { session.start(command(session, "call", R"({"callback":"app.render","args":"x"})")); }); - requireThrows([&] { session.start(command(session, "call", R"({"callback":"webfront.automation.poll"})")); }); + given("names and arguments that could reach internals", [&] { + then("webfront.* names, odd characters and extra arguments are refused before any allow-list lookup", [&] { + const auto make = [&](std::vector allow, std::vector callbacks) { + return Session{ + webfront::automation::SessionOptions{.project = directory.path(), .allow = std::move(allow), .callbacks = std::move(callbacks)} + }; + }; + requireThrows([&] { + make({"call"}, {"webfront.developer.read"}); + }); + requireThrows([&] { + make({"call"}, {"app render"}); + }); + requireThrows([&] { + make({"call"}, {""}); + }); + requireThrows([&] { + make({"check"}, {"app.render"}); + }); // names need the grant + requireThrows([&] { + session.start(command(session, "call", "{}")); + }); + requireThrows([&] { + session.start(command(session, "call", R"({"callback":"app.render","args":"x"})")); + }); + requireThrows([&] { + session.start(command(session, "call", R"({"callback":"webfront.automation.poll"})")); + }); + }); }); - }); -}}; + }}; diff --git a/test/unit/BddDiscoveryProbe.cpp b/test/unit/BddDiscoveryProbe.cpp index 7afac253..818b7d74 100644 --- a/test/unit/BddDiscoveryProbe.cpp +++ b/test/unit/BddDiscoveryProbe.cpp @@ -4,10 +4,10 @@ using namespace webfront::bdd; -const Scenario openBracket{"A [b title", [] { }}; -const Scenario semicolon{"Second; one", [] { }}; -const Scenario closeBracket{"Third ]x", [] { }}; -const Scenario pairedBrackets{"Fourth [tag] title", [] { }}; +const Scenario openBracket{"A [b title", [] {}}; +const Scenario semicolon{"Second; one", [] {}}; +const Scenario closeBracket{"Third ]x", [] {}}; +const Scenario pairedBrackets{"Fourth [tag] title", [] {}}; const Scenario literalMarkers{"Literal %5B %25 ", [] {}}; const Scenario endsLikeDelimiter{"Ends like a delimiter ]==", [] {}}; const Scenario trailingBackslash{"Ends with a backslash \\", [] {}}; diff --git a/test/unit/BddSelfTest.cpp b/test/unit/BddSelfTest.cpp index 93807188..877a8740 100644 --- a/test/unit/BddSelfTest.cpp +++ b/test/unit/BddSelfTest.cpp @@ -154,7 +154,7 @@ const Scenario assertionsPass{ requireThrows([] { throw 3; }); - requireNothrow([] { }); + requireNothrow([] {}); std::optional value{1}; require(value); auto scope = info("value ", *value); @@ -196,7 +196,9 @@ const Scenario eventuallyHolds{"eventually holds", [] { std::this_thread::sleep_for(20ms); value = 2; }}; - requireEventually([&] { return value == 2; }); + requireEventually([&] { + return value == 2; + }); checkEventually( [&] { return value == 2; @@ -214,9 +216,17 @@ const Scenario eventuallyHolds{"eventually holds", [] { const Scenario eventuallyTimesOut{"eventually times out", [] { using namespace std::chrono_literals; - check(!checkEventually([] { return false; }, 20ms)); + check(!checkEventually( + [] { + return false; + }, + 20ms)); trace.push_back("after check"); - requireEventually([] { return false; }, 20ms); + requireEventually( + [] { + return false; + }, + 20ms); trace.push_back("not reached"); }}; diff --git a/test/unit/BroadcastTests.cpp b/test/unit/BroadcastTests.cpp index 30711262..9dd492f3 100644 --- a/test/unit/BroadcastTests.cpp +++ b/test/unit/BroadcastTests.cpp @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief Broadcasting to every connected browser, and the threads of callbacks and browser calls (#401). #include "InjectableNetworking.hpp" -#include #include #include +#include #include #ifdef _WIN32 @@ -32,7 +32,7 @@ using namespace std::chrono_literals; namespace { const std::string broadcastUpgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; // The payload of a browser's call to a C++ function, without a reply (call identifier 0). template @@ -57,220 +57,228 @@ struct OneBrowserNet : testing::InjectableNetworking { } // namespace const Scenario broadcastKeeps{"A broadcast keeps only the latest call for a browser with too many pending writes", {"broadcast"}, [] { - using Socket = testing::InjectableSocket; - Socket::reset(); - OneBrowserNet::accepted = false; - BasicWF app{WebFrontConfig{.port = "0"}}; - auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); - auto every = app.broadcast("onEvent"); - Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); - require(app.connectedBrowsers() == 1); - - given("a browser whose handshake has not completed", [&] { - latest(std::string{"before-handshake"}); - then("it is not started yet and receives nothing", [&] { - require(!Socket::wrote("before-handshake")); - }); - }); - given("a started browser whose network completes writes only when the test says so", [&] { - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - Socket::deferWrites(); - Socket::completeDeferredWrites(); // the handshake acknowledgement - - when("three states are broadcast while the first one is still being written", [&] { - latest(std::string{"state-1"}); - latest(std::string{"state-2"}); - latest(std::string{"state-3"}); - then("only the first is written before the network completes it", [&] { - require(Socket::wrote("state-1")); - require(!Socket::wrote("state-3")); - }); - andWhen("the network completes the writes", [&] { - while (Socket::completeDeferredWrites() != 0) {} - then("the latest state follows and the intermediate one was skipped", [&] { - require(Socket::wrote("state-3")); - require(!Socket::wrote("state-2")); - }); - then("a later state is written at once", [&] { - latest(std::string{"state-4"}); - require(Socket::wrote("state-4")); - }); - }); - }); - when("states are broadcast through temporary function objects while the first one is still being written", [&] { - app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-1"}); - app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-2"}); - app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-3"}); - while (Socket::completeDeferredWrites() != 0) { } - then("they share the browser's held call: the intermediate one was skipped", [&] { - require(Socket::wrote("temporary-1")); - require(Socket::wrote("temporary-3")); - require(!Socket::wrote("temporary-2")); - }); - }); - when("states are broadcast while an event of another function is still being written", [&] { - every(std::string{"event-0"}); - latest(std::string{"state-1"}); - latest(std::string{"state-2"}); - latest(std::string{"state-3"}); - while (Socket::completeDeferredWrites() != 0) { } - then("the event does not count toward the limit of the states", [&] { - require(Socket::wrote("event-0")); - require(Socket::wrote("state-1")); - require(Socket::wrote("state-3")); - require(!Socket::wrote("state-2")); - }); - }); - when("events are broadcast without a limit while the first one is still being written", [&] { - every(std::string{"event-1"}); - every(std::string{"event-2"}); - every(std::string{"event-3"}); - while (Socket::completeDeferredWrites() != 0) {} - then("every one is written", [&] { - require(Socket::wrote("event-1")); - require(Socket::wrote("event-2")); - require(Socket::wrote("event-3")); - }); - }); - Socket::deferWrites(false); - while (Socket::completeDeferredWrites() != 0) {} - }); - app.shutdown(); - Socket::reset(); -}}; + using Socket = testing::InjectableSocket; + Socket::reset(); + OneBrowserNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto every = app.broadcast("onEvent"); + Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); + require(app.connectedBrowsers() == 1); + + given("a browser whose handshake has not completed", [&] { + latest(std::string{"before-handshake"}); + then("it is not started yet and receives nothing", [&] { + require(!Socket::wrote("before-handshake")); + }); + }); + given("a started browser whose network completes writes only when the test says so", [&] { + msg::Handshake handshake; + Socket::receive(testing::clientFrame( + std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + + when("three states are broadcast while the first one is still being written", [&] { + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + latest(std::string{"state-3"}); + then("only the first is written before the network completes it", [&] { + require(Socket::wrote("state-1")); + require(!Socket::wrote("state-3")); + }); + andWhen("the network completes the writes", [&] { + while (Socket::completeDeferredWrites() != 0) {} + then("the latest state follows and the intermediate one was skipped", [&] { + require(Socket::wrote("state-3")); + require(!Socket::wrote("state-2")); + }); + then("a later state is written at once", [&] { + latest(std::string{"state-4"}); + require(Socket::wrote("state-4")); + }); + }); + }); + when("states are broadcast through temporary function objects while the first one is still being written", [&] { + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-1"}); + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-2"}); + app.broadcast("onState", {.maxPendingWrites = 1})(std::string{"temporary-3"}); + while (Socket::completeDeferredWrites() != 0) {} + then("they share the browser's held call: the intermediate one was skipped", [&] { + require(Socket::wrote("temporary-1")); + require(Socket::wrote("temporary-3")); + require(!Socket::wrote("temporary-2")); + }); + }); + when("states are broadcast while an event of another function is still being written", [&] { + every(std::string{"event-0"}); + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + latest(std::string{"state-3"}); + while (Socket::completeDeferredWrites() != 0) {} + then("the event does not count toward the limit of the states", [&] { + require(Socket::wrote("event-0")); + require(Socket::wrote("state-1")); + require(Socket::wrote("state-3")); + require(!Socket::wrote("state-2")); + }); + }); + when("events are broadcast without a limit while the first one is still being written", [&] { + every(std::string{"event-1"}); + every(std::string{"event-2"}); + every(std::string{"event-3"}); + while (Socket::completeDeferredWrites() != 0) {} + then("every one is written", [&] { + require(Socket::wrote("event-1")); + require(Socket::wrote("event-2")); + require(Socket::wrote("event-3")); + }); + }); + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) {} + }); + app.shutdown(); + Socket::reset(); + }}; const Scenario broadcastLimit{"A broadcast limit must allow at least one pending write", {"broadcast"}, [] { - testing::InjectableSocket::reset(); - OneBrowserNet::accepted = false; - BasicWF app{WebFrontConfig{.port = "0"}}; - requireThrows([&] { (void)app.broadcast("onState", {.maxPendingWrites = 0}); }); - app.shutdown(); - testing::InjectableSocket::reset(); -}}; + testing::InjectableSocket::reset(); + OneBrowserNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + requireThrows([&] { + (void)app.broadcast("onState", {.maxPendingWrites = 0}); + }); + app.shutdown(); + testing::InjectableSocket::reset(); + }}; const Scenario browserReceives{"A browser receives a broadcast made while its onUIStarted handlers run after what they sent", {"broadcast"}, [] { - using Socket = testing::InjectableSocket; - using App = BasicWF; - Socket::reset(); - OneBrowserNet::accepted = false; - App app{WebFrontConfig{.port = "0"}}; - auto onState = app.broadcast("onState", {.maxPendingWrites = 1}); - std::size_t visitedWhileStarting{}; - app.onUIStarted([&](App::UI ui) { - onState(std::string{"broadcast-while-starting"}); - app.forEachUI([&](App::UI) { - ++visitedWhileStarting; - }); - ui.jsFunction("initial")(std::string{"initial-state"}); - }); - Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); - - when("the browser completes its handshake", [&] { - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - then("the handler's initial state comes first, then the broadcast", [&] { - require(Socket::wrote("initial-state")); - require(Socket::wrote("broadcast-while-starting")); - require(Socket::writtenAt("initial-state") < Socket::writtenAt("broadcast-while-starting")); + using Socket = testing::InjectableSocket; + using App = BasicWF; + Socket::reset(); + OneBrowserNet::accepted = false; + App app{WebFrontConfig{.port = "0"}}; + auto onState = app.broadcast("onState", {.maxPendingWrites = 1}); + std::size_t visitedWhileStarting{}; + app.onUIStarted([&](App::UI ui) { + onState(std::string{"broadcast-while-starting"}); + app.forEachUI([&](App::UI) { + ++visitedWhileStarting; + }); + ui.jsFunction("initial")(std::string{"initial-state"}); + }); + Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); + + when("the browser completes its handshake", [&] { + msg::Handshake handshake; + Socket::receive(testing::clientFrame( + std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + then("the handler's initial state comes first, then the broadcast", [&] { + require(Socket::wrote("initial-state")); + require(Socket::wrote("broadcast-while-starting")); + require(Socket::writtenAt("initial-state") < Socket::writtenAt("broadcast-while-starting")); + }); + then("forEachUI skipped the browser while its handlers ran, and visits it afterwards", [&] { + require(visitedWhileStarting == 0); + std::size_t visited{}; + app.forEachUI([&](App::UI) { + ++visited; + }); + require(visited == 1); + }); + }); + app.shutdown(); + Socket::reset(); + }}; + +const Scenario browserWhose{ + "A browser whose onUIStarted handlers run keeps only the latest calls within the limit", + {"broadcast"}, + [] { + using Socket = testing::InjectableSocket; + using App = BasicWF; + Socket::reset(); + OneBrowserNet::accepted = false; + App app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto pair = app.broadcast("onState", {.maxPendingWrites = 2}); + auto every = app.broadcast("onEvent"); + app.onUIStarted([&](App::UI) { + latest(std::string{"starting-1"}); + every(std::string{"event-1"}); + latest(std::string{"starting-2"}); + every(std::string{"event-2"}); + latest(std::string{"starting-3"}); }); - then("forEachUI skipped the browser while its handlers ran, and visits it afterwards", [&] { - require(visitedWhileStarting == 0); - std::size_t visited{}; - app.forEachUI([&](App::UI) { - ++visited; + Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); + + when("the browser completes its handshake", [&] { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + then("only the latest limited call made meanwhile is sent, after the unlimited ones made before it", [&] { + require(Socket::wrote("starting-3")); + require(!Socket::wrote("starting-1")); + require(!Socket::wrote("starting-2")); + require(Socket::wrote("event-1")); + require(Socket::wrote("event-2")); + require(Socket::writtenAt("event-2") < Socket::writtenAt("starting-3")); }); - require(visited == 1); - }); - }); - app.shutdown(); - Socket::reset(); -}}; - -const Scenario browserWhose{"A browser whose onUIStarted handlers run keeps only the latest calls within the limit", {"broadcast"}, [] { - using Socket = testing::InjectableSocket; - using App = BasicWF; - Socket::reset(); - OneBrowserNet::accepted = false; - App app{WebFrontConfig{.port = "0"}}; - auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); - auto pair = app.broadcast("onState", {.maxPendingWrites = 2}); - auto every = app.broadcast("onEvent"); - app.onUIStarted([&](App::UI) { - latest(std::string{"starting-1"}); - every(std::string{"event-1"}); - latest(std::string{"starting-2"}); - every(std::string{"event-2"}); - latest(std::string{"starting-3"}); - }); - Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); - - when("the browser completes its handshake", [&] { - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - then("only the latest limited call made meanwhile is sent, after the unlimited ones made before it", [&] { - require(Socket::wrote("starting-3")); - require(!Socket::wrote("starting-1")); - require(!Socket::wrote("starting-2")); - require(Socket::wrote("event-1")); - require(Socket::wrote("event-2")); - require(Socket::writtenAt("event-2") < Socket::writtenAt("starting-3")); }); - }); - when("calls of one function use different limits while the first is still being written", [&] { - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - Socket::deferWrites(); - Socket::completeDeferredWrites(); // the handshake acknowledgement - while (Socket::completeDeferredWrites() != 0) { } - pair(std::string{"pair-1"}); - pair(std::string{"pair-2"}); - latest(std::string{"single-3"}); - latest(std::string{"single-4"}); - pair(std::string{"pair-5"}); - while (Socket::completeDeferredWrites() != 0) { } - then("each call applies its own limit within the browser's queue of that function", [&] { - require(Socket::wrote("pair-1")); - require(Socket::wrote("pair-2")); - require(!Socket::wrote("single-3")); - require(!Socket::wrote("single-4")); - require(Socket::wrote("pair-5")); - require(Socket::writtenAt("pair-2") < Socket::writtenAt("pair-5")); + when("calls of one function use different limits while the first is still being written", [&] { + msg::Handshake handshake; + Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + while (Socket::completeDeferredWrites() != 0) {} + pair(std::string{"pair-1"}); + pair(std::string{"pair-2"}); + latest(std::string{"single-3"}); + latest(std::string{"single-4"}); + pair(std::string{"pair-5"}); + while (Socket::completeDeferredWrites() != 0) {} + then("each call applies its own limit within the browser's queue of that function", [&] { + require(Socket::wrote("pair-1")); + require(Socket::wrote("pair-2")); + require(!Socket::wrote("single-3")); + require(!Socket::wrote("single-4")); + require(Socket::wrote("pair-5")); + require(Socket::writtenAt("pair-2") < Socket::writtenAt("pair-5")); + }); + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) {} }); - Socket::deferWrites(false); - while (Socket::completeDeferredWrites() != 0) { } - }); - app.shutdown(); - Socket::reset(); -}}; + app.shutdown(); + Socket::reset(); + }}; const Scenario heldBroadcast{"A held broadcast reaches the browser after a later call of another function", {"broadcast"}, [] { - using Socket = testing::InjectableSocket; - Socket::reset(); - OneBrowserNet::accepted = false; - BasicWF app{WebFrontConfig{.port = "0"}}; - auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); - auto every = app.broadcast("onReset"); - Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - Socket::deferWrites(); - Socket::completeDeferredWrites(); // the handshake acknowledgement - - when("a state is held back, then another function is called", [&] { - latest(std::string{"state-1"}); - latest(std::string{"state-2"}); - every(std::string{"reset-after-state-2"}); - while (Socket::completeDeferredWrites() != 0) { } - then("the other function's call is written before the held state, as documented", [&] { - require(Socket::writtenAt("reset-after-state-2") < Socket::writtenAt("state-2")); - }); - }); - Socket::deferWrites(false); - while (Socket::completeDeferredWrites() != 0) { } - app.shutdown(); - Socket::reset(); -}}; + using Socket = testing::InjectableSocket; + Socket::reset(); + OneBrowserNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + auto latest = app.broadcast("onState", {.maxPendingWrites = 1}); + auto every = app.broadcast("onReset"); + Socket::receive(std::as_bytes(std::span(broadcastUpgradeRequest))); + msg::Handshake handshake; + Socket::receive( + testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + Socket::deferWrites(); + Socket::completeDeferredWrites(); // the handshake acknowledgement + + when("a state is held back, then another function is called", [&] { + latest(std::string{"state-1"}); + latest(std::string{"state-2"}); + every(std::string{"reset-after-state-2"}); + while (Socket::completeDeferredWrites() != 0) {} + then("the other function's call is written before the held state, as documented", [&] { + require(Socket::writtenAt("reset-after-state-2") < Socket::writtenAt("state-2")); + }); + }); + Socket::deferWrites(false); + while (Socket::completeDeferredWrites() != 0) {} + app.shutdown(); + Socket::reset(); + }}; namespace { using Stdnet = networking::TCPStdnet; @@ -353,142 +361,142 @@ struct Observed { } // namespace const Scenario callbacksRun{"Callbacks run one at a time on the server thread, and browser calls are made from any thread", {"broadcast"}, [] { - using App = BasicWF; - App app{WebFrontConfig{.port = "0"}}; - Observed observed; - std::mutex applicationLock; // also taken by a callback - app.onUIStarted([&](App::UI) { - observed.record(); - ++observed.started; - }); - auto closedSubscription = app.subscribeUIClosed([&](App::UI) { - observed.record(); - ++observed.closed; - }); - app.cppFunction("report", [&](App::UI ui) { - observed.record(); - std::scoped_lock lock{applicationLock}; - ui.jsFunction("reported")(std::string{"reported-ack"}); - ++observed.calls; - }); - std::promise unblock; - auto unblocked = unblock.get_future().share(); - std::atomic blocking{false}; - app.cppFunction("block", [&] { - blocking = true; - unblocked.wait(); - }); - std::thread server([&] { - app.run(); - }); - const auto serverThread = server.get_id(); - - auto first = std::make_unique(app.port()); - auto second = std::make_unique(app.port()); - broadcastWaitUntil([&] { - return observed.started == 2; - }); - require(observed.started == 2); - - when("another thread broadcasts a state", [&] { - auto onState = app.broadcast("siliconForge.onState"); - onState(std::string{"broadcast-state"}); - then("every started browser receives it", [&] { - require(first->receiveUntil("broadcast-state")); - require(second->receiveUntil("broadcast-state")); - }); - }); - when("another thread calls each browser through forEachUI", [&] { - std::vector visited; - bool documentRefused = true; - app.forEachUI([&](App::UI ui) { - visited.push_back(ui.id()); - ui.jsFunction("each")(std::string{"each-ui-" + std::to_string(ui.id())}); - try { - static_cast(ui.document()); - documentRefused = false; - } catch (const std::logic_error&) { } - }); - then("each started browser is visited once and receives its call, but its document needs the server thread", [&] { - require(visited.size() == 2); - require(documentRefused); - require(first->receiveUntil("each-ui-")); - require(second->receiveUntil("each-ui-")); - }); - }); - when("both browsers call C++ while another thread broadcasts under a lock the callback also takes", [&] { - auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 2}); - for (int i = 0; i < 20; ++i) { - first->call("report"); - second->call("report"); - std::scoped_lock lock{applicationLock}; - onState(std::string{"locked-state"}); - app.forEachUI([](App::UI ui) { - ui.jsFunction("locked")(std::string{"locked-call"}); - }); - } - broadcastWaitUntil([&] { - return observed.calls == 40; - }); - then("no call deadlocks and the callbacks never overlap", [&] { - require(observed.calls == 40); - require(observed.maxRunning == 1); - require(first->receiveUntil("reported-ack")); - require(second->receiveUntil("locked-call")); - }); - }); - when("a callback blocks the server thread", [&] { - first->call("block"); - broadcastWaitUntil([&] { - return blocking.load(); - }); - require(blocking); - auto calls = std::async(std::launch::async, [&] { - auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 1}); - onState(std::string{"while-blocked"}); - onState(std::string{"while-blocked"}); - app.forEachUI([](App::UI ui) { - ui.jsFunction("blocked")(std::string{"while-blocked"}); - static_cast(ui.pendingWrites()); - }); - }); - const bool called = waitReady(calls, 5s); - unblock.set_value(); - then("browser calls from another thread return without waiting for it", [&] { - require(called); - require(second->receiveUntil("while-blocked")); - }); - }); - if (blocking == false) - unblock.set_value(); - - when("a browser disconnects", [&] { - second.reset(); - broadcastWaitUntil([&] { - return observed.closed == 1; - }); - then("its closure is reported, and a broadcast reaches the remaining browser", [&] { - require(observed.closed == 1); - app.broadcast("siliconForge.onState", {.maxPendingWrites = 1})(std::string{"after-close"}); - require(first->receiveUntil("after-close")); - }); - }); - first.reset(); - second.reset(); - broadcastWaitUntil([&] { - return app.connectedBrowsers() == 0; - }); - app.stop(); - server.join(); - app.shutdown(); - then("every callback ran on the server thread", [&] { - std::scoped_lock lock{observed.mutex}; - require(!observed.threads.empty()); - require(std::ranges::all_of(observed.threads, [&](std::thread::id id) { - return id == serverThread; - })); - }); -}}; + using App = BasicWF; + App app{WebFrontConfig{.port = "0"}}; + Observed observed; + std::mutex applicationLock; // also taken by a callback + app.onUIStarted([&](App::UI) { + observed.record(); + ++observed.started; + }); + auto closedSubscription = app.subscribeUIClosed([&](App::UI) { + observed.record(); + ++observed.closed; + }); + app.cppFunction("report", [&](App::UI ui) { + observed.record(); + std::scoped_lock lock{applicationLock}; + ui.jsFunction("reported")(std::string{"reported-ack"}); + ++observed.calls; + }); + std::promise unblock; + auto unblocked = unblock.get_future().share(); + std::atomic blocking{false}; + app.cppFunction("block", [&] { + blocking = true; + unblocked.wait(); + }); + std::thread server([&] { + app.run(); + }); + const auto serverThread = server.get_id(); + + auto first = std::make_unique(app.port()); + auto second = std::make_unique(app.port()); + broadcastWaitUntil([&] { + return observed.started == 2; + }); + require(observed.started == 2); + + when("another thread broadcasts a state", [&] { + auto onState = app.broadcast("siliconForge.onState"); + onState(std::string{"broadcast-state"}); + then("every started browser receives it", [&] { + require(first->receiveUntil("broadcast-state")); + require(second->receiveUntil("broadcast-state")); + }); + }); + when("another thread calls each browser through forEachUI", [&] { + std::vector visited; + bool documentRefused = true; + app.forEachUI([&](App::UI ui) { + visited.push_back(ui.id()); + ui.jsFunction("each")(std::string{"each-ui-" + std::to_string(ui.id())}); + try { + static_cast(ui.document()); + documentRefused = false; + } catch (const std::logic_error&) {} + }); + then("each started browser is visited once and receives its call, but its document needs the server thread", [&] { + require(visited.size() == 2); + require(documentRefused); + require(first->receiveUntil("each-ui-")); + require(second->receiveUntil("each-ui-")); + }); + }); + when("both browsers call C++ while another thread broadcasts under a lock the callback also takes", [&] { + auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 2}); + for (int i = 0; i < 20; ++i) { + first->call("report"); + second->call("report"); + std::scoped_lock lock{applicationLock}; + onState(std::string{"locked-state"}); + app.forEachUI([](App::UI ui) { + ui.jsFunction("locked")(std::string{"locked-call"}); + }); + } + broadcastWaitUntil([&] { + return observed.calls == 40; + }); + then("no call deadlocks and the callbacks never overlap", [&] { + require(observed.calls == 40); + require(observed.maxRunning == 1); + require(first->receiveUntil("reported-ack")); + require(second->receiveUntil("locked-call")); + }); + }); + when("a callback blocks the server thread", [&] { + first->call("block"); + broadcastWaitUntil([&] { + return blocking.load(); + }); + require(blocking); + auto calls = std::async(std::launch::async, [&] { + auto onState = app.broadcast("siliconForge.onState", {.maxPendingWrites = 1}); + onState(std::string{"while-blocked"}); + onState(std::string{"while-blocked"}); + app.forEachUI([](App::UI ui) { + ui.jsFunction("blocked")(std::string{"while-blocked"}); + static_cast(ui.pendingWrites()); + }); + }); + const bool called = waitReady(calls, 5s); + unblock.set_value(); + then("browser calls from another thread return without waiting for it", [&] { + require(called); + require(second->receiveUntil("while-blocked")); + }); + }); + if (blocking == false) + unblock.set_value(); + + when("a browser disconnects", [&] { + second.reset(); + broadcastWaitUntil([&] { + return observed.closed == 1; + }); + then("its closure is reported, and a broadcast reaches the remaining browser", [&] { + require(observed.closed == 1); + app.broadcast("siliconForge.onState", {.maxPendingWrites = 1})(std::string{"after-close"}); + require(first->receiveUntil("after-close")); + }); + }); + first.reset(); + second.reset(); + broadcastWaitUntil([&] { + return app.connectedBrowsers() == 0; + }); + app.stop(); + server.join(); + app.shutdown(); + then("every callback ran on the server thread", [&] { + std::scoped_lock lock{observed.mutex}; + require(!observed.threads.empty()); + require(std::ranges::all_of(observed.threads, [&](std::thread::id id) { + return id == serverThread; + })); + }); + }}; namespace webfront::testing { template @@ -500,89 +508,97 @@ struct ConnectionIds { }; } // namespace webfront::testing -const Scenario uIKept{"A UI kept after its connection closed reaches no browser once its identifier is reused", {"broadcast", "ui"}, [] { - using App = BasicWF; - App app{WebFrontConfig{.port = "0"}}; - std::mutex mutex; - std::vector started; - std::atomic closed{0}; - auto startedSubscription = app.subscribeUIStarted([&](App::UI ui) { - std::scoped_lock lock{mutex}; - started.push_back(ui); - }); - auto closedSubscription = app.subscribeUIClosed([&](App::UI) { - ++closed; - }); - std::thread server([&] { - app.run(); - }); - const auto startedCount = [&] { - std::scoped_lock lock{mutex}; - return started.size(); - }; - - webfront::testing::ConnectionIds::startAt(app, 65535); - auto first = std::make_unique(app.port()); - broadcastWaitUntil([&] { - return startedCount() == 1; - }); - require(startedCount() == 1); - const App::UI stale = [&] { - std::scoped_lock lock{mutex}; - return started.front(); - }(); - require(stale.id() == 65535); - - first.reset(); - broadcastWaitUntil([&] { - return closed == 1 && app.connectedBrowsers() == 0; - }); - require(app.connectedBrowsers() == 0); - - // The identifier counter wraps back to the identifier the closed connection had. - webfront::testing::ConnectionIds::startAt(app, 65535); - auto second = std::make_unique(app.port()); - broadcastWaitUntil([&] { - return startedCount() == 2; - }); - require(startedCount() == 2); - const App::UI current = [&] { - std::scoped_lock lock{mutex}; - return started.back(); - }(); - - given("a later browser that received the identifier of the closed one", [&] { - require(current.id() == stale.id()); - then("the stale value does not equal it, and the value of the live connection does", [&] { - require(!(stale == current)); - require(current == current); +const Scenario uIKept{ + "A UI kept after its connection closed reaches no browser once its identifier is reused", + {"broadcast", "ui"}, + [] { + using App = BasicWF; + App app{WebFrontConfig{.port = "0"}}; + std::mutex mutex; + std::vector started; + std::atomic closed{0}; + auto startedSubscription = app.subscribeUIStarted([&](App::UI ui) { + std::scoped_lock lock{mutex}; + started.push_back(ui); + }); + auto closedSubscription = app.subscribeUIClosed([&](App::UI) { + ++closed; }); - then("the stale value drops calls, fails typed calls, and has nothing pending", [&] { - stale.jsFunction("onStale")(std::string{"stale-call"}); - auto typed = stale.jsFunction("typedStale")(); - require(typed.wait_for(0s) == std::future_status::ready); // failed at once: the later browser never replies - requireThrows([&] { (void)typed.get(); }); - requireThrows([&] { stale.addScript("stale-script"); }); - require(stale.pendingWrites() == 0); - current.jsFunction("onCurrent")(std::string{"current-call"}); - require(second->receiveUntil("current-call")); - require(!second->receiveUntil("stale-call", 100ms)); + std::thread server([&] { + app.run(); + }); + const auto startedCount = [&] { + std::scoped_lock lock{mutex}; + return started.size(); + }; + + webfront::testing::ConnectionIds::startAt(app, 65535); + auto first = std::make_unique(app.port()); + broadcastWaitUntil([&] { + return startedCount() == 1; }); - then("forEachUI visits the later connection's value only", [&] { - std::vector visited; - app.forEachUI([&](App::UI ui) { - visited.push_back(ui); + require(startedCount() == 1); + const App::UI stale = [&] { + std::scoped_lock lock{mutex}; + return started.front(); + }(); + require(stale.id() == 65535); + + first.reset(); + broadcastWaitUntil([&] { + return closed == 1 && app.connectedBrowsers() == 0; + }); + require(app.connectedBrowsers() == 0); + + // The identifier counter wraps back to the identifier the closed connection had. + webfront::testing::ConnectionIds::startAt(app, 65535); + auto second = std::make_unique(app.port()); + broadcastWaitUntil([&] { + return startedCount() == 2; + }); + require(startedCount() == 2); + const App::UI current = [&] { + std::scoped_lock lock{mutex}; + return started.back(); + }(); + + given("a later browser that received the identifier of the closed one", [&] { + require(current.id() == stale.id()); + then("the stale value does not equal it, and the value of the live connection does", [&] { + require(!(stale == current)); + require(current == current); + }); + then("the stale value drops calls, fails typed calls, and has nothing pending", [&] { + stale.jsFunction("onStale")(std::string{"stale-call"}); + auto typed = stale.jsFunction("typedStale")(); + require(typed.wait_for(0s) == std::future_status::ready); // failed at once: the later browser never replies + requireThrows([&] { + (void)typed.get(); + }); + requireThrows([&] { + stale.addScript("stale-script"); + }); + require(stale.pendingWrites() == 0); + current.jsFunction("onCurrent")(std::string{"current-call"}); + require(second->receiveUntil("current-call")); + require(!second->receiveUntil("stale-call", 100ms)); + }); + then("forEachUI visits the later connection's value only", [&] { + std::vector visited; + app.forEachUI([&](App::UI ui) { + visited.push_back(ui); + }); + require(visited.size() == 1); + require(visited.front() == current); + require(!(visited.front() == stale)); }); - require(visited.size() == 1); - require(visited.front() == current); - require(!(visited.front() == stale)); }); - }); - second.reset(); - broadcastWaitUntil([&] { - return app.connectedBrowsers() == 0; - }); - app.stop(); - server.join(); - app.shutdown(); -}}; + second.reset(); + broadcastWaitUntil([&] { + return app.connectedBrowsers() == 0; + }); + app.stop(); + server.join(); + app.shutdown(); + } +}; diff --git a/test/unit/CEFMacrosTests.cpp b/test/unit/CEFMacrosTests.cpp index 6030d8df..245cd904 100644 --- a/test/unit/CEFMacrosTests.cpp +++ b/test/unit/CEFMacrosTests.cpp @@ -23,9 +23,9 @@ using namespace webfront::bdd; const Scenario webFrontCompiles{"WebFront compiles after CEF's compiler macros", [] { - given("the stdexec headers included before CEF's NO_UNIQUE_ADDRESS, ALWAYS_INLINE and NOINLINE", [&] { - then("every stdexec header WebFront.hpp includes was already included", [&] { - static_assert(std::is_default_constructible_v); - }); - }); -}}; + given("the stdexec headers included before CEF's NO_UNIQUE_ADDRESS, ALWAYS_INLINE and NOINLINE", [&] { + then("every stdexec header WebFront.hpp includes was already included", [&] { + static_assert(std::is_default_constructible_v); + }); + }); + }}; diff --git a/test/unit/CEFPathsTests.cpp b/test/unit/CEFPathsTests.cpp index bf97d8de..40335997 100644 --- a/test/unit/CEFPathsTests.cpp +++ b/test/unit/CEFPathsTests.cpp @@ -1,31 +1,31 @@ -#include #include +#include #include using namespace webfront::bdd; const Scenario macOSCEF{"macOS CEF paths match the deployed framework layout", [] { - given("executables in different CMake target directories", [&] { - const std::filesystem::path buildRoot{"build-cef"}; - const auto deployedFramework = buildRoot / "Frameworks" / "Chromium Embedded Framework.framework"; + given("executables in different CMake target directories", [&] { + const std::filesystem::path buildRoot{"build-cef"}; + const auto deployedFramework = buildRoot / "Frameworks" / "Chromium Embedded Framework.framework"; - when("each target resolves its framework path", [&] { - then("both locate the framework deployed in the parent directory", [&] { - require(webfront::cef::detail::macOSFrameworkPath(buildRoot / "examples" / "HelloWorld") == deployedFramework); - require(webfront::cef::detail::macOSFrameworkPath(buildRoot / "webtest" / "webtest") == deployedFramework); - }); - }); - }); + when("each target resolves its framework path", [&] { + then("both locate the framework deployed in the parent directory", [&] { + require(webfront::cef::detail::macOSFrameworkPath(buildRoot / "examples" / "HelloWorld") == deployedFramework); + require(webfront::cef::detail::macOSFrameworkPath(buildRoot / "webtest" / "webtest") == deployedFramework); + }); + }); + }); - given("an application bundle with an arbitrary executable name", [&] { - const std::filesystem::path contents = std::filesystem::path{"CustomApp.app"} / "Contents"; + given("an application bundle with an arbitrary executable name", [&] { + const std::filesystem::path contents = std::filesystem::path{"CustomApp.app"} / "Contents"; - when("the executable resolves its framework path", [&] { - then("it uses Contents/Frameworks, matching the CEF library loader", [&] { - require(webfront::cef::detail::macOSFrameworkPath(contents / "MacOS" / "CustomApp") - == contents / "Frameworks" / "Chromium Embedded Framework.framework"); - }); - }); - }); -}}; + when("the executable resolves its framework path", [&] { + then("it uses Contents/Frameworks, matching the CEF library loader", [&] { + require(webfront::cef::detail::macOSFrameworkPath(contents / "MacOS" / "CustomApp") + == contents / "Frameworks" / "Chromium Embedded Framework.framework"); + }); + }); + }); + }}; diff --git a/test/unit/CommandsTests.cpp b/test/unit/CommandsTests.cpp index 0983ae38..42a672f8 100644 --- a/test/unit/CommandsTests.cpp +++ b/test/unit/CommandsTests.cpp @@ -1,6 +1,6 @@ #include "InjectableNetworking.hpp" -#include #include +#include #include #include @@ -52,21 +52,21 @@ struct FakeUI { [[nodiscard]] int id() const noexcept { return link; } - TaskHandle spawn(Task task) const; - auto jsFunction(string_view name) const; - auto writesAtMost(size_t limit) const; - auto resumeAfter(chrono::milliseconds) const; + TaskHandle spawn(Task task) const; + auto jsFunction(string_view name) const; + auto writesAtMost(size_t limit) const; + auto resumeAfter(chrono::milliseconds) const; }; // Records the bridge functions that Commands registers, like BasicWF::cppFunction, and the browser calls. struct FakeApp { using UI = FakeUI; - function list; - function start; - function cancel; - shared_ptr> closed = make_shared>(); - vector calls; + function list; + function start; + function cancel; + shared_ptr> closed = make_shared>(); + vector calls; [[nodiscard]] bool hasCppFunction(string_view name) const { return std::ranges::find(registered, name) != registered.end(); @@ -108,8 +108,8 @@ struct FakeApp { } vector registered; - size_t backlog = 0; // frames waiting for the network; each pause lets the browser read 10 - int pauses = 0; + size_t backlog = 0; // frames waiting for the network; each pause lets the browser read 10 + int pauses = 0; bool queueing = false; // each browser call adds a frame to the backlog vector paced; // "send" and "pause", in order // Destroyed first: draining its tasks lets the commands report through the members above. @@ -123,12 +123,12 @@ TaskHandle FakeUI::spawn(Task task) const { // Completes at once when the queue is short enough; else the browser reads until it is down to half the limit. auto FakeUI::writesAtMost(size_t limit) const { return networking::ex::just() | networking::ex::then([app = app, limit] { - if (app->backlog <= limit) - return; - ++app->pauses; - app->paced.push_back("pause"); - app->backlog = min(app->backlog, limit / 2); - }); + if (app->backlog <= limit) + return; + ++app->pauses; + app->paced.push_back("pause"); + app->backlog = min(app->backlog, limit / 2); + }); } auto FakeUI::resumeAfter(chrono::milliseconds) const { @@ -163,7 +163,7 @@ Task greet(Context context) { Task waitUntilStopped(Context context, shared_ptr unwound) { Unwound guard{std::move(unwound)}; context.write("waiting\n"); - co_await testing::ManualSender([](auto) { }); + co_await testing::ManualSender([](auto) {}); context.write("never reached\n"); } @@ -190,392 +190,433 @@ struct Fixture { } // namespace -const Scenario commandsRegister{"Commands register their bridge functions and list the commands", [] { - given("an application with commands", [&] { - Fixture fixture; - then("the browser discovers them, sorted, with their help", [&] { - check(fixture.app.registered == vector{"webfront.commands.list", "webfront.commands.start", "webfront.commands.cancel"}); - check(fixture.app.list() - == R"([{"name":"code","help":"Exit with 3"},)" - R"({"name":"fail","help":"Throw"},{"name":"greet","help":"Greet someone"},{"name":"wait","help":"Wait until stopped"}])"); - }); - then("a second Commands object on the application is refused", [&] { - checkThrows([&] { Commands{fixture.app}; }); - }); - - then("invalid, reserved and duplicate names are refused", [&] { - for (const auto* name : {"", "two words", "quo'te", "back\\slash", "tab\t", "wf", "clear", "exit", "help", "history", "greet"}) - checkThrows([&] { fixture.commands.add(name, "", greet); }); - }); - then("every name the terminal keeps for itself is refused, the file commands it does not provide included", [&] { - for (const auto name : webfront::commands::reservedNames) - checkThrows([&] { fixture.commands.add(std::string(name), "", greet); }); - for (const auto* name : {"ls", "cat", "tree", "mounts", "rm", "cd", "edit"}) - check(std::ranges::find(webfront::commands::reservedNames, std::string_view{name}) != webfront::commands::reservedNames.end()); - }); - }); - given("an application where only webfront.commands.cancel is taken", [&] { - FakeApp app; - app.cppFunction("webfront.commands.cancel", [](FakeUI, uint32_t) { }); - then("Commands is refused and registers nothing", [&] { - checkThrows([&] { Commands{app}; }); - check(app.registered == vector{"webfront.commands.cancel"}); - }); - }); -}}; - -const Scenario commandStreams{"A command streams its output and reports its exit", [] { - given("an application with commands", [&] { - Fixture fixture; - auto& app = fixture.app; - when("a browser runs a command with arguments", [&] { - app.start(app.ui(1), 7, "greet", R"(["Ada \"Lovelace\"", "é"])"); - then("its output, then its exit code, reach that browser", [&] { - const auto calls = app.callsOf(1); - require(calls.size() == 2); - check(calls[0].function == "webfront.commands.output"); - check(calls[0].id == 7); - check(calls[0].values == vector{"Hello Ada \"Lovelace\"\n"}); - check(calls[1].function == "webfront.commands.exit"); - check(calls[1].values == vector{"0", ""}); - check(fixture.commands.running() == 0); +const Scenario commandsRegister{ + "Commands register their bridge functions and list the commands", + [] { + given("an application with commands", [&] { + Fixture fixture; + then("the browser discovers them, sorted, with their help", [&] { + check(fixture.app.registered == vector{"webfront.commands.list", "webfront.commands.start", "webfront.commands.cancel"}); + check(fixture.app.list() + == R"([{"name":"code","help":"Exit with 3"},)" + R"({"name":"fail","help":"Throw"},{"name":"greet","help":"Greet someone"},{"name":"wait","help":"Wait until stopped"}])"); }); - }); - when("a command throws", [&] { - app.start(app.ui(1), 1, "fail", "[]"); - then("its message is reported with exit code 1", [&] { - check(app.callsOf(1).back().values == vector{"1", "boom"}); + then("a second Commands object on the application is refused", [&] { + checkThrows([&] { + Commands{fixture.app}; + }); }); - }); - when("a command sets its exit code", [&] { - app.start(app.ui(1), 1, "code", "[]"); - then("it is reported", [&] { - check(app.callsOf(1).back().values == vector{"3", ""}); + + then("invalid, reserved and duplicate names are refused", [&] { + for (const auto* name : {"", "two words", "quo'te", "back\\slash", "tab\t", "wf", "clear", "exit", "help", "history", "greet"}) + checkThrows([&] { + fixture.commands.add(name, "", greet); + }); }); - }); - when("the browser names an unknown command or sends malformed arguments", [&] { - then("its call is rejected and nothing runs", [&] { - checkThrows([&] { app.start(app.ui(1), 1, "absent", "[]"); }); - checkThrows([&] { app.start(app.ui(1), 1, "greet", R"(["unterminated)"); }); - checkThrows([&] { app.start(app.ui(1), 1, "greet", R"({"not":"an array"})"); }); - check(app.calls.empty()); - check(fixture.commands.running() == 0); + then("every name the terminal keeps for itself is refused, the file commands it does not provide included", [&] { + for (const auto name : webfront::commands::reservedNames) + checkThrows([&] { + fixture.commands.add(std::string(name), "", greet); + }); + for (const auto* name : {"ls", "cat", "tree", "mounts", "rm", "cd", "edit"}) + check(std::ranges::find(webfront::commands::reservedNames, std::string_view{name}) != webfront::commands::reservedNames.end()); }); }); - }); -}}; - -const Scenario commandOutput{"Command output is split under the bridge string limit on character boundaries", [] { - given("a text of two-byte characters longer than two pieces", [&] { - string text; - for (int i = 0; i < 70000; ++i) - text += "é"; - when("it is split", [&] { - const auto pieces = commands::detail::chunks(text); - then("each piece is under the limit, ends on a character boundary and the pieces rebuild the text", [&] { - require(pieces.size() == 3); - string rebuilt; - for (const auto piece : pieces) { - check(piece.size() <= commands::maxChunkBytes); - check(piece.size() % 2 == 0); - rebuilt += piece; - } - check(rebuilt == text); + given("an application where only webfront.commands.cancel is taken", [&] { + FakeApp app; + app.cppFunction("webfront.commands.cancel", [](FakeUI, uint32_t) {}); + then("Commands is refused and registers nothing", [&] { + checkThrows([&] { + Commands{app}; + }); + check(app.registered == vector{"webfront.commands.cancel"}); }); }); - when("a command writes it", [&] { - FakeApp app; - Commands commands{app}; - commands.add("big", "", [text](Context context) -> Task { - context.write(text); - co_return; + }}; + +const Scenario commandStreams{"A command streams its output and reports its exit", [] { + given("an application with commands", [&] { + Fixture fixture; + auto& app = fixture.app; + when("a browser runs a command with arguments", [&] { + app.start(app.ui(1), 7, "greet", R"(["Ada \"Lovelace\"", "é"])"); + then("its output, then its exit code, reach that browser", [&] { + const auto calls = app.callsOf(1); + require(calls.size() == 2); + check(calls[0].function == "webfront.commands.output"); + check(calls[0].id == 7); + check(calls[0].values == vector{"Hello Ada \"Lovelace\"\n"}); + check(calls[1].function == "webfront.commands.exit"); + check(calls[1].values == vector{"0", ""}); + check(fixture.commands.running() == 0); + }); + }); + when("a command throws", [&] { + app.start(app.ui(1), 1, "fail", "[]"); + then("its message is reported with exit code 1", [&] { + check(app.callsOf(1).back().values == vector{"1", "boom"}); + }); + }); + when("a command sets its exit code", [&] { + app.start(app.ui(1), 1, "code", "[]"); + then("it is reported", [&] { + check(app.callsOf(1).back().values == vector{"3", ""}); + }); + }); + when("the browser names an unknown command or sends malformed arguments", [&] { + then("its call is rejected and nothing runs", [&] { + checkThrows([&] { + app.start(app.ui(1), 1, "absent", "[]"); + }); + checkThrows([&] { + app.start(app.ui(1), 1, "greet", R"(["unterminated)"); + }); + checkThrows([&] { + app.start(app.ui(1), 1, "greet", R"({"not":"an array"})"); + }); + check(app.calls.empty()); + check(fixture.commands.running() == 0); + }); + }); + }); + }}; + +const Scenario commandOutput{ + "Command output is split under the bridge string limit on character boundaries", + [] { + given("a text of two-byte characters longer than two pieces", [&] { + string text; + for (int i = 0; i < 70000; ++i) + text += "é"; + when("it is split", [&] { + const auto pieces = commands::detail::chunks(text); + then("each piece is under the limit, ends on a character boundary and the pieces rebuild the text", [&] { + require(pieces.size() == 3); + string rebuilt; + for (const auto piece : pieces) { + check(piece.size() <= commands::maxChunkBytes); + check(piece.size() % 2 == 0); + rebuilt += piece; + } + check(rebuilt == text); + }); }); - app.start(app.ui(1), 1, "big", "[]"); - then("the browser receives it in pieces", [&] { - const auto calls = app.callsOf(1); - require(calls.size() == 4); - check(calls[0].values[0] + calls[1].values[0] + calls[2].values[0] == text); - check(calls[3].function == "webfront.commands.exit"); + when("a command writes it", [&] { + FakeApp app; + Commands commands{app}; + commands.add("big", "", [text](Context context) -> Task { + context.write(text); + co_return; + }); + app.start(app.ui(1), 1, "big", "[]"); + then("the browser receives it in pieces", [&] { + const auto calls = app.callsOf(1); + require(calls.size() == 4); + check(calls[0].values[0] + calls[1].values[0] + calls[2].values[0] == text); + check(calls[3].function == "webfront.commands.exit"); + }); }); }); - }); - given("bytes that are not UTF-8: continuation bytes only", [&] { - const string bytes(10, '\x80'); - when("they are split", [&] { - const auto pieces = commands::detail::chunks(bytes, 4); - then("the split still ends, in pieces of the limit", [&] { - check(pieces == vector{string_view(bytes).substr(0, 4), string_view(bytes).substr(4, 4), string_view(bytes).substr(8)}); + given("bytes that are not UTF-8: continuation bytes only", [&] { + const string bytes(10, '\x80'); + when("they are split", [&] { + const auto pieces = commands::detail::chunks(bytes, 4); + then("the split still ends, in pieces of the limit", [&] { + check(pieces == vector{string_view(bytes).substr(0, 4), string_view(bytes).substr(4, 4), string_view(bytes).substr(8)}); + }); }); }); - }); - given("short and empty texts", [&] { - check(commands::detail::chunks("").empty()); - check(commands::detail::chunks("abc") == vector{"abc"}); - }); -}}; + given("short and empty texts", [&] { + check(commands::detail::chunks("").empty()); + check(commands::detail::chunks("abc") == vector{"abc"}); + }); + }}; const Scenario printingWaits{"Printing waits while the browser has not read the output", [] { - given("a browser that has more frames to read than allowed", [&] { - FakeApp app; - Commands commands{app}; - commands.add("print", "", [](Context context) -> Task { - co_await context.print("line\n"); - }); - app.backlog = 55; - when("a command prints", [&] { - app.start(app.ui(1), 1, "print", "[]"); - then("it waits once, until no more than the allowed frames are pending, then ends", [&] { - check(app.pauses == 1); - check(app.backlog <= commands::maxPendingOutput); - check(app.callsOf(1).back().values == vector{"0", ""}); - }); - }); - }); -}}; + given("a browser that has more frames to read than allowed", [&] { + FakeApp app; + Commands commands{app}; + commands.add("print", "", [](Context context) -> Task { + co_await context.print("line\n"); + }); + app.backlog = 55; + when("a command prints", [&] { + app.start(app.ui(1), 1, "print", "[]"); + then("it waits once, until no more than the allowed frames are pending, then ends", [&] { + check(app.pauses == 1); + check(app.backlog <= commands::maxPendingOutput); + check(app.callsOf(1).back().values == vector{"0", ""}); + }); + }); + }); + }}; const Scenario printingLong{"Printing a long text waits between its pieces", [] { - given("a browser with as many frames to read as allowed", [&] { - FakeApp app; - Commands commands{app}; - commands.add("print", "", [](Context context) -> Task { - co_await context.print(string(2 * commands::maxChunkBytes + 1, 'x')); - }); - app.backlog = commands::maxPendingOutput; - app.queueing = true; - when("a command prints a text of three pieces", [&] { - app.start(app.ui(1), 1, "print", "[]"); - then("it waits after the piece that overfills the queue, before sending the next", [&] { - check(app.paced == vector{"send", "pause", "send", "send", "send"}); - }); - }); - }); -}}; + given("a browser with as many frames to read as allowed", [&] { + FakeApp app; + Commands commands{app}; + commands.add("print", "", [](Context context) -> Task { + co_await context.print(string(2 * commands::maxChunkBytes + 1, 'x')); + }); + app.backlog = commands::maxPendingOutput; + app.queueing = true; + when("a command prints a text of three pieces", [&] { + app.start(app.ui(1), 1, "print", "[]"); + then("it waits after the piece that overfills the queue, before sending the next", [&] { + check(app.paced == vector{"send", "pause", "send", "send", "send"}); + }); + }); + }); + }}; const Scenario printTask{"A print task may be awaited after its context is gone", [] { - given("a command that creates a print task from a context, then reuses its storage for another", [&] { - FakeApp app; - Commands commands{app}; - commands.add("print", "", [&app](Context context) -> Task { - optional temporary{context}; - auto printing = temporary->print("mine\n"); - temporary.reset(); - temporary.emplace(make_shared>(app.ui(1), 99, vector{})); - co_await std::move(printing); - }); - when("it awaits the task", [&] { - app.start(app.ui(1), 1, "print", "[]"); - then("the text is printed by the command that created the task", [&] { - const auto calls = app.callsOf(1); - require(calls.size() == 2); - check(calls[0].id == 1); - check(calls[0].values == vector{"mine\n"}); - }); - }); - }); -}}; + given("a command that creates a print task from a context, then reuses its storage for another", [&] { + FakeApp app; + Commands commands{app}; + commands.add("print", "", [&app](Context context) -> Task { + optional temporary{context}; + auto printing = temporary->print("mine\n"); + temporary.reset(); + temporary.emplace(make_shared>(app.ui(1), 99, vector{})); + co_await std::move(printing); + }); + when("it awaits the task", [&] { + app.start(app.ui(1), 1, "print", "[]"); + then("the text is printed by the command that created the task", [&] { + const auto calls = app.callsOf(1); + require(calls.size() == 2); + check(calls[0].id == 1); + check(calls[0].values == vector{"mine\n"}); + }); + }); + }); + }}; const Scenario ctrlC{"Ctrl+C stops a running command and the next one runs at once", [] { - given("a command waiting in a browser", [&] { - Fixture fixture; - auto& app = fixture.app; - app.start(app.ui(1), 1, "wait", "[]"); - require(fixture.commands.running() == 1); - require(!(*fixture.unwound)); - then("its number cannot start another command", [&] { - checkThrows([&] { app.start(app.ui(1), 1, "greet", "[]"); }); - }); - when("a command that returns once asked to stop is cancelled", [&] { - fixture.commands.add("polite", "", [](Context context) -> Task { - co_await (testing::ManualSender([](auto) { }) | networking::ex::upon_stopped([] { return size_t{}; })); - context.exit(0); - }); - app.start(app.ui(1), 9, "polite", "[]"); - app.cancel(app.ui(1), 9); - then("it reports exit code 130, not success", [&] { - check(app.callsOf(1).back().values == vector{"130", ""}); - }); - }); - when("the browser cancels it", [&] { - app.cancel(app.ui(1), 1); - then("the command unwinds and reports exit code 130", [&] { - check(*fixture.unwound); - check(fixture.commands.running() == 0); - const auto calls = app.callsOf(1); - check(calls.back().function == "webfront.commands.exit"); - check(calls.back().values == vector{"130", ""}); - }); - andWhen("the browser runs another command and cancels the ended one again", [&] { - app.start(app.ui(1), 2, "greet", "[]"); - app.cancel(app.ui(1), 1); - then("the new command answers normally", [&] { - const auto calls = app.callsOf(1); - check(calls.back().id == 2); - check(calls.back().values == vector{"0", ""}); - }); - }); - }); - }); -}}; + given("a command waiting in a browser", [&] { + Fixture fixture; + auto& app = fixture.app; + app.start(app.ui(1), 1, "wait", "[]"); + require(fixture.commands.running() == 1); + require(!(*fixture.unwound)); + then("its number cannot start another command", [&] { + checkThrows([&] { + app.start(app.ui(1), 1, "greet", "[]"); + }); + }); + when("a command that returns once asked to stop is cancelled", [&] { + fixture.commands.add("polite", "", [](Context context) -> Task { + co_await (testing::ManualSender([](auto) {}) | networking::ex::upon_stopped([] { + return size_t{}; + })); + context.exit(0); + }); + app.start(app.ui(1), 9, "polite", "[]"); + app.cancel(app.ui(1), 9); + then("it reports exit code 130, not success", [&] { + check(app.callsOf(1).back().values == vector{"130", ""}); + }); + }); + when("the browser cancels it", [&] { + app.cancel(app.ui(1), 1); + then("the command unwinds and reports exit code 130", [&] { + check(*fixture.unwound); + check(fixture.commands.running() == 0); + const auto calls = app.callsOf(1); + check(calls.back().function == "webfront.commands.exit"); + check(calls.back().values == vector{"130", ""}); + }); + andWhen("the browser runs another command and cancels the ended one again", [&] { + app.start(app.ui(1), 2, "greet", "[]"); + app.cancel(app.ui(1), 1); + then("the new command answers normally", [&] { + const auto calls = app.callsOf(1); + check(calls.back().id == 2); + check(calls.back().values == vector{"0", ""}); + }); + }); + }); + }); + }}; const Scenario eachBrowser{"Each browser has its own commands", [] { - given("a waiting command in each of two browsers", [&] { - Fixture fixture; - auto& app = fixture.app; - auto second = make_shared(false); - fixture.commands.add("wait2", "", [second](Context context) { - return waitUntilStopped(std::move(context), second); - }); - app.start(app.ui(1), 1, "wait", "[]"); - app.start(app.ui(2), 1, "wait2", "[]"); - require(fixture.commands.running() == 2); - when("the first browser cancels its command, which has the same number", [&] { - app.cancel(app.ui(1), 1); - then("the second browser's command keeps running", [&] { - check(*fixture.unwound); - check(!(*second)); - check(fixture.commands.running() == 1); - }); - }); - when("the second browser disconnects", [&] { - const auto before = app.callsOf(2).size(); - app.disconnect(2); - then("its command is stopped and nothing more is sent to it", [&] { - check(*second); - check(!(*fixture.unwound)); - check(fixture.commands.running() == 1); - check(app.callsOf(2).size() == before); - }); - }); - }); -}}; + given("a waiting command in each of two browsers", [&] { + Fixture fixture; + auto& app = fixture.app; + auto second = make_shared(false); + fixture.commands.add("wait2", "", [second](Context context) { + return waitUntilStopped(std::move(context), second); + }); + app.start(app.ui(1), 1, "wait", "[]"); + app.start(app.ui(2), 1, "wait2", "[]"); + require(fixture.commands.running() == 2); + when("the first browser cancels its command, which has the same number", [&] { + app.cancel(app.ui(1), 1); + then("the second browser's command keeps running", [&] { + check(*fixture.unwound); + check(!(*second)); + check(fixture.commands.running() == 1); + }); + }); + when("the second browser disconnects", [&] { + const auto before = app.callsOf(2).size(); + app.disconnect(2); + then("its command is stopped and nothing more is sent to it", [&] { + check(*second); + check(!(*fixture.unwound)); + check(fixture.commands.running() == 1); + check(app.callsOf(2).size() == before); + }); + }); + }); + }}; const Scenario browserGiven{"A browser given the identifier of a disconnected one starts afresh", [] { - given("a command that ignores its stop, in a browser that disconnects", [&] { - Fixture fixture; - auto& app = fixture.app; - auto finish = make_shared(); - fixture.commands.add("deaf", "", [finish](Context) -> Task { - co_await networking::ex::write_env(testing::ManualSender([finish](auto completion) { *finish = std::move(completion); }), - networking::ex::prop{networking::ex::get_stop_token, networking::ex::never_stop_token{}}); - }); - app.start(app.ui(2), 1, "deaf", "[]"); - app.disconnect(2); - when("a new browser with the same identifier runs a command with the same number", [&] { - app.start(app.ui(2), 1, "greet", R"(["again"])"); - then("it runs, and only its own messages reach the new browser", [&] { - const auto calls = app.callsOf(2); - require(calls.size() == 2); - check(calls[0].values == vector{"Hello again\n"}); - check(calls[1].values == vector{"0", ""}); - }); - andWhen("the deaf command ends at last", [&] { - finish->complete({}, 0); - then("its exit report does not reach the new browser either", [&] { - check(app.callsOf(2).size() == 2); - }); - }); - }); - if (finish->complete) - finish->complete({}, 0); // lets the shutdown drain it - }); -}}; + given("a command that ignores its stop, in a browser that disconnects", [&] { + Fixture fixture; + auto& app = fixture.app; + auto finish = make_shared(); + fixture.commands.add("deaf", "", [finish](Context) -> Task { + co_await networking::ex::write_env( + testing::ManualSender([finish](auto completion) { + *finish = std::move(completion); + }), + networking::ex::prop{networking::ex::get_stop_token, networking::ex::never_stop_token{}}); + }); + app.start(app.ui(2), 1, "deaf", "[]"); + app.disconnect(2); + when("a new browser with the same identifier runs a command with the same number", [&] { + app.start(app.ui(2), 1, "greet", R"(["again"])"); + then("it runs, and only its own messages reach the new browser", [&] { + const auto calls = app.callsOf(2); + require(calls.size() == 2); + check(calls[0].values == vector{"Hello again\n"}); + check(calls[1].values == vector{"0", ""}); + }); + andWhen("the deaf command ends at last", [&] { + finish->complete({}, 0); + then("its exit report does not reach the new browser either", [&] { + check(app.callsOf(2).size() == 2); + }); + }); + }); + if (finish->complete) + finish->complete({}, 0); // lets the shutdown drain it + }); + }}; const Scenario shutdownDrains{"Shutdown drains running commands", [] { - given("a waiting command", [&] { - Fixture fixture; - auto& app = fixture.app; - app.start(app.ui(1), 1, "wait", "[]"); - when("the application shuts down", [&] { - app.real.shutdown(); - then("the command unwound before shutdown returned", [&] { - check(*fixture.unwound); - check(fixture.commands.running() == 0); - }); - andWhen("a browser starts another command", [&] { - then("its call is rejected and nothing is left running", [&] { - checkThrows([&] { app.start(app.ui(1), 2, "greet", "[]"); }); - check(fixture.commands.running() == 0); - }); - }); - }); - }); -}}; + given("a waiting command", [&] { + Fixture fixture; + auto& app = fixture.app; + app.start(app.ui(1), 1, "wait", "[]"); + when("the application shuts down", [&] { + app.real.shutdown(); + then("the command unwound before shutdown returned", [&] { + check(*fixture.unwound); + check(fixture.commands.running() == 0); + }); + andWhen("a browser starts another command", [&] { + then("its call is rejected and nothing is left running", [&] { + checkThrows([&] { + app.start(app.ui(1), 2, "greet", "[]"); + }); + check(fixture.commands.running() == 0); + }); + }); + }); + }); + }}; const Scenario commandMay{"A command may take its context by reference", [] { - given("a command whose coroutine keeps a reference to its context across a suspension", [&] { - FakeApp app; - Commands commands{app}; - commands.add("late", "", [](const Context& context) -> Task { - co_await context.ui().resumeAfter(chrono::milliseconds(1)); - context.write("after the pause\n"); - }); - when("it runs", [&] { - app.start(app.ui(1), 1, "late", "[]"); - then("its context is still valid after the suspension", [&] { - check(app.callsOf(1).front().values == vector{"after the pause\n"}); - }); - }); - }); -}}; + given("a command whose coroutine keeps a reference to its context across a suspension", [&] { + FakeApp app; + Commands commands{app}; + commands.add("late", "", [](const Context& context) -> Task { + co_await context.ui().resumeAfter(chrono::milliseconds(1)); + context.write("after the pause\n"); + }); + when("it runs", [&] { + app.start(app.ui(1), 1, "late", "[]"); + then("its context is still valid after the suspension", [&] { + check(app.callsOf(1).front().values == vector{"after the pause\n"}); + }); + }); + }); + }}; const Scenario copyContext{"A copy of a context may outlive its command", [] { - given("a command that keeps a copy of its context", [&] { - FakeApp app; - Commands commands{app}; - auto kept = make_shared>(); - commands.add("keep", "", [kept](Context context) -> Task { - kept->emplace(context); - co_return; - }); - app.start(app.ui(1), 1, "keep", "[]"); - when("the command has ended", [&] { - then("the copy still reads its stop state, and writes nothing", [&] { - require(kept->has_value()); - check(!((*kept)->stopRequested())); - check(!((*kept)->stopToken().stop_requested())); - const auto calls = app.callsOf(1).size(); - (*kept)->write("late\n"); - check(app.callsOf(1).size() == calls + 1); - }); - }); - }); -}}; + given("a command that keeps a copy of its context", [&] { + FakeApp app; + Commands commands{app}; + auto kept = make_shared>(); + commands.add("keep", "", [kept](Context context) -> Task { + kept->emplace(context); + co_return; + }); + app.start(app.ui(1), 1, "keep", "[]"); + when("the command has ended", [&] { + then("the copy still reads its stop state, and writes nothing", [&] { + require(kept->has_value()); + check(!((*kept)->stopRequested())); + check(!((*kept)->stopToken().stop_requested())); + const auto calls = app.callsOf(1).size(); + (*kept)->write("late\n"); + check(app.callsOf(1).size() == calls + 1); + }); + }); + }); + }}; const Scenario commandsMay{"Commands may outlive their registering object", [] { - given("commands whose Commands object is gone", [&] { - FakeApp app; - { - Commands commands{app}; - commands.add("greet", "", greet); - } - then("the browser still runs them", [&] { - app.start(app.ui(1), 1, "greet", R"(["you"])"); - check(app.callsOf(1).front().values == vector{"Hello you\n"}); - }); - }); -}}; + given("commands whose Commands object is gone", [&] { + FakeApp app; + { + Commands commands{app}; + commands.add("greet", "", greet); + } + then("the browser still runs them", [&] { + app.start(app.ui(1), 1, "greet", R"(["you"])"); + check(app.callsOf(1).front().values == vector{"Hello you\n"}); + }); + }); + }}; const Scenario basicWFProvides{"BasicWF provides the application facilities of commands", [] { - given("an application over the networking mock", [&] { - RealApp app(WebFrontConfig{.port = "0"}); - then("browsers have identifiers and disconnections can be subscribed to", [&] { - check(RealApp::UI(app, 5, 1).id() == 5); - auto subscription = app.subscribeUIClosed([](RealApp::UI) { }); - check(subscription.active()); - }); - then("a second Commands object is refused, and cppFunction tells a taken name", [&] { - Commands commands{app}; - checkThrows([&] { Commands{app}; }); - check(!app.cppFunction("webfront.commands.list", [] { return 0; })); - check(app.cppFunction("another", [] { return 0; })); - }); - then("calls to a browser that is gone are dropped, and typed calls fail", [&] { - const RealApp::UI gone(app, 42, 1); - check(app.connectedBrowsers() == 0); - checkNothrow([&] { gone.jsFunction("console.log")("dropped"); }); - auto result = gone.jsFunction("Math.abs")(-1); - checkThrows([&] { (void)result.get(); }, equals("Browser connection closed")); - checkNothrow([&] { gone.jsFunctionSender("Math.abs")(-1); }); - }); - }); -}}; + given("an application over the networking mock", [&] { + RealApp app(WebFrontConfig{.port = "0"}); + then("browsers have identifiers and disconnections can be subscribed to", [&] { + check(RealApp::UI(app, 5, 1).id() == 5); + auto subscription = app.subscribeUIClosed([](RealApp::UI) {}); + check(subscription.active()); + }); + then("a second Commands object is refused, and cppFunction tells a taken name", [&] { + Commands commands{app}; + checkThrows([&] { + Commands{app}; + }); + check(!app.cppFunction("webfront.commands.list", [] { + return 0; + })); + check(app.cppFunction("another", [] { + return 0; + })); + }); + then("calls to a browser that is gone are dropped, and typed calls fail", [&] { + const RealApp::UI gone(app, 42, 1); + check(app.connectedBrowsers() == 0); + checkNothrow([&] { + gone.jsFunction("console.log")("dropped"); + }); + auto result = gone.jsFunction("Math.abs")(-1); + checkThrows( + [&] { + (void)result.get(); + }, + equals("Browser connection closed")); + checkNothrow([&] { + gone.jsFunctionSender("Math.abs")(-1); + }); + }); + }); + }}; diff --git a/test/unit/ContentPolicyTests.cpp b/test/unit/ContentPolicyTests.cpp index e4f783d2..0674c64a 100644 --- a/test/unit/ContentPolicyTests.cpp +++ b/test/unit/ContentPolicyTests.cpp @@ -1,8 +1,8 @@ #include "Mocks.hpp" -#include #include #include #include +#include #include #include @@ -63,139 +63,147 @@ struct WarningCapture { }; } // namespace -const Scenario contentPolicyCompares{"Content policy compares complete HTTP origins", [] { - const detail::BoundContentPolicy policy{"http://127.0.0.1:9002/index.html"}; - given("the default policy", [&] { - then("same-origin URLs and native clients are allowed", [&] { - require(policy.allowsBridge("http://127.0.0.1:9002")); - require(policy.allowsBridge(std::nullopt)); - require(policy.allowsNavigation("http://127.0.0.1:9002/next?x=1#fragment")); +const Scenario contentPolicyCompares{ + "Content policy compares complete HTTP origins", + [] { + const detail::BoundContentPolicy policy{"http://127.0.0.1:9002/index.html"}; + given("the default policy", [&] { + then("same-origin URLs and native clients are allowed", [&] { + require(policy.allowsBridge("http://127.0.0.1:9002")); + require(policy.allowsBridge(std::nullopt)); + require(policy.allowsNavigation("http://127.0.0.1:9002/next?x=1#fragment")); + }); + then("a Blob of the application's origin (a generated download) is allowed, one of another origin is not", [&] { + require(policy.allowsNavigation("blob:http://127.0.0.1:9002/0b1f2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")); + require(policy.allowsNavigation("BLOB:http://127.0.0.1:9002/id")); + for (const auto* url : + {"blob:https://example.com/id", "blob:null/id", "blob:", "blob:http://127.0.0.1:9002@evil/id", "blob:blob:http://127.0.0.1:9002/id"}) { + auto scope = info(url); + require(!policy.allowsNavigation(url)); + } + }); + then("other origins and ambiguous syntax fail closed", [&] { + for (const auto* origin : invalidBridgeOrigins) { + auto scope = info(origin); + require(!policy.allowsBridge(origin)); + } + for (const auto* url : {"https://example.com/", + "http://127.0.0.1:9002@evil/", + "javascript:alert(1)", + "data:text/html,hi", + "file:///tmp/index.html", + "about:blank", + "http://127.0.0.1:9002\\@evil/"}) { + auto scope = info(url); + require(!policy.allowsNavigation(url)); + } + }); }); - then("a Blob of the application's origin (a generated download) is allowed, one of another origin is not", [&] { - require(policy.allowsNavigation("blob:http://127.0.0.1:9002/0b1f2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")); - require(policy.allowsNavigation("BLOB:http://127.0.0.1:9002/id")); - for (const auto* url : {"blob:https://example.com/id", "blob:null/id", "blob:", "blob:http://127.0.0.1:9002@evil/id", "blob:blob:http://127.0.0.1:9002/id"}) { - auto scope = info(url); - require(!policy.allowsNavigation(url)); - } + given("explicit allow-lists and mandatory Origin", [&] { + const ContentPolicy options{.bridgeAllowedOrigins = {"HTTPS://UI.EXAMPLE:443"}, + .navigationAllowedOrigins = {"https://docs.example"}, + .allowMissingOrigin = false}; + const detail::BoundContentPolicy configured{"http://127.0.0.1:9002", options}; + require(configured.allowsBridge("https://ui.example")); + require(!configured.allowsBridge(std::nullopt)); + require(!configured.allowsBridge("https://docs.example")); + require(configured.allowsNavigation("https://docs.example/help")); + require(!configured.allowsNavigation("https://ui.example/")); + requireThrows([&] { + (detail::BoundContentPolicy{"http://127.0.0.1:9002", {.bridgeAllowedOrigins = {"*"}}}); + }); + requireThrows([&] { + (detail::BoundContentPolicy{"http://127.0.0.1:9002", {.navigationAllowedOrigins = {"https://example.com/path"}}}); + }); }); - then("other origins and ambiguous syntax fail closed", [&] { - for (const auto* origin : invalidBridgeOrigins) { - auto scope = info(origin); - require(!policy.allowsBridge(origin)); - } - for (const auto* url : {"https://example.com/", - "http://127.0.0.1:9002@evil/", - "javascript:alert(1)", - "data:text/html,hi", - "file:///tmp/index.html", - "about:blank", - "http://127.0.0.1:9002\\@evil/"}) { - auto scope = info(url); - require(!policy.allowsNavigation(url)); - } + given("the explicit permissive HTTP(S) development options", [&] { + const detail::BoundContentPolicy configured{ + "http://localhost:80", + {.allowAnyBridgeOrigin = true, .allowAnyNavigation = true} + }; + require(configured.allowsBridge("https://other.example")); + require(configured.allowsNavigation("http://other.example/path")); + require(!configured.allowsBridge("null")); + require(!configured.allowsNavigation("javascript:alert(1)")); }); - }); - given("explicit allow-lists and mandatory Origin", [&] { - const ContentPolicy options{.bridgeAllowedOrigins = {"HTTPS://UI.EXAMPLE:443"}, - .navigationAllowedOrigins = {"https://docs.example"}, - .allowMissingOrigin = false}; - const detail::BoundContentPolicy configured{"http://127.0.0.1:9002", options}; - require(configured.allowsBridge("https://ui.example")); - require(!configured.allowsBridge(std::nullopt)); - require(!configured.allowsBridge("https://docs.example")); - require(configured.allowsNavigation("https://docs.example/help")); - require(!configured.allowsNavigation("https://ui.example/")); - requireThrows([&] { (detail::BoundContentPolicy{"http://127.0.0.1:9002", {.bridgeAllowedOrigins = {"*"}}}); }); - requireThrows([&] { (detail::BoundContentPolicy{"http://127.0.0.1:9002", {.navigationAllowedOrigins = {"https://example.com/path"}}}); }); - }); - given("the explicit permissive HTTP(S) development options", [&] { - const detail::BoundContentPolicy configured{ - "http://localhost:80", - {.allowAnyBridgeOrigin = true, .allowAnyNavigation = true} - }; - require(configured.allowsBridge("https://other.example")); - require(configured.allowsNavigation("http://other.example/path")); - require(!configured.allowsBridge("null")); - require(!configured.allowsNavigation("javascript:alert(1)")); - }); - given("default ports, case and bracketed IPv6", [&] { - require(detail::BoundContentPolicy{"http://LOCALHOST:80"}.allowsBridge("http://localhost")); - require(detail::BoundContentPolicy{"https://[::1]:443"}.allowsBridge("https://[::1]")); - require(!(detail::BoundContentPolicy{"http://[::1]:9002"}.allowsBridge("http://[::1]:9003"))); - }); -}}; + given("default ports, case and bracketed IPv6", [&] { + require(detail::BoundContentPolicy{"http://LOCALHOST:80"}.allowsBridge("http://localhost")); + require(detail::BoundContentPolicy{"https://[::1]:443"}.allowsBridge("https://[::1]")); + require(!(detail::BoundContentPolicy{"http://[::1]:9002"}.allowsBridge("http://[::1]:9003"))); + }); + }}; const Scenario contentPolicyControls{"Content policy controls popup delegation", [] { - std::vector opened; - auto launch = [&](const std::string& url) { - opened.push_back(url); - }; - given("the default policy", [&] { - detail::BoundContentPolicy{}.handlePopup("https://example.com/help", true, launch); - require(opened.empty()); - }); - given("system browser popups are explicitly enabled", [&] { - const detail::BoundContentPolicy policy{"http://127.0.0.1:9002", {.popups = PopupPolicy::systemBrowser}}; - policy.handlePopup("https://example.com/help", true, launch); - policy.handlePopup("file:///etc/passwd", true, launch); - policy.handlePopup("javascript:alert(1)", true, launch); - require(opened == std::vector{"https://example.com/help"}); - when("a script requests repeated popups without a user gesture", [&] { - opened.clear(); - for (int count = 0; count < 100; ++count) - policy.handlePopup("https://example.com/help", false, launch); - then("no URL reaches the external launcher", [&] { - require(opened.empty()); - }); - }); - }); -}}; + std::vector opened; + auto launch = [&](const std::string& url) { + opened.push_back(url); + }; + given("the default policy", [&] { + detail::BoundContentPolicy{}.handlePopup("https://example.com/help", true, launch); + require(opened.empty()); + }); + given("system browser popups are explicitly enabled", [&] { + const detail::BoundContentPolicy policy{"http://127.0.0.1:9002", {.popups = PopupPolicy::systemBrowser}}; + policy.handlePopup("https://example.com/help", true, launch); + policy.handlePopup("file:///etc/passwd", true, launch); + policy.handlePopup("javascript:alert(1)", true, launch); + require(opened == std::vector{"https://example.com/help"}); + when("a script requests repeated popups without a user gesture", [&] { + opened.clear(); + for (int count = 0; count < 100; ++count) + policy.handlePopup("https://example.com/help", false, launch); + then("no URL reaches the external launcher", [&] { + require(opened.empty()); + }); + }); + }); + }}; const Scenario webSocketUpgrades{"WebSocket upgrades authorize Origin before returning 101", [] { - using namespace webfront::http; - using Net = networking::NetworkingMock; - auto upgrade = [](const std::string& headers, ContentPolicy policy = {}) { - const std::string input = "GET / HTTP/1.1\r\nHost: attacker.example\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" - + headers + "\r\n"; - Request request; - require(request.parseSomeData(input.begin(), input.end())); - RequestHandler> handler{ - ".", - detail::BoundContentPolicy{"http://127.0.0.1:9002/", std::move(policy)} - }; - return handler.handleRequest(request); - }; - then("the configured application origin and absent Origin are accepted independently of Host", [&] { - require(upgrade("Origin: http://127.0.0.1:9002\r\n").statusCode == Response::switchingProtocols); - require(upgrade("").statusCode == Response::switchingProtocols); - }); - then("cross-origin, opaque, malformed and duplicate Origin receive a deterministic 403", [&] { - for (const auto* headers : {"Origin: https://attacker.example\r\n", - "Origin: null\r\n", - "Origin: http://127.0.0.1:9002/path\r\n", - "Origin: http://127.0.0.1:9002\r\norigin: https://attacker.example\r\n", - "Origin: http://127.0.0.1:9002\r\nOrigin: http://127.0.0.1:9002\r\n"}) { - const auto response = upgrade(headers); - require(response.statusCode == Response::forbidden); - require(!response.getHeaderValue("Sec-WebSocket-Accept")); - require(!response.getHeaderValue("Upgrade")); - require(response.content.contains("WebSocket Origin rejected by content policy")); - require(response.content.contains("bridgeAllowedOrigins")); - require(response.getHeaderValue("Content-Type") == "text/plain; charset=utf-8"); - require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); - } - }); - then("the allow-list and native-client opt-out reach the handshake", [&] { - require(upgrade("Origin: https://ui.example\r\n", {.bridgeAllowedOrigins = {"https://ui.example"}}).statusCode == Response::switchingProtocols); - require(upgrade("", {.allowMissingOrigin = false}).statusCode == Response::forbidden); - }); - then("a refusal logs an actionable diagnostic for alternate hosts and wildcard binds", [&] { - WarningCapture capture; - require(upgrade("Origin: http://192.168.1.2:9002\r\n").statusCode == Response::forbidden); - require(!capture.messages.empty()); - require(capture.messages.back().contains("bridgeAllowedOrigins")); - require(capture.messages.back().contains("wildcard binds authorize loopback only")); - }); -}}; + using namespace webfront::http; + using Net = networking::NetworkingMock; + auto upgrade = [](const std::string& headers, ContentPolicy policy = {}) { + const std::string input = "GET / HTTP/1.1\r\nHost: attacker.example\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + + headers + "\r\n"; + Request request; + require(request.parseSomeData(input.begin(), input.end())); + RequestHandler> handler{ + ".", + detail::BoundContentPolicy{"http://127.0.0.1:9002/", std::move(policy)} + }; + return handler.handleRequest(request); + }; + then("the configured application origin and absent Origin are accepted independently of Host", [&] { + require(upgrade("Origin: http://127.0.0.1:9002\r\n").statusCode == Response::switchingProtocols); + require(upgrade("").statusCode == Response::switchingProtocols); + }); + then("cross-origin, opaque, malformed and duplicate Origin receive a deterministic 403", [&] { + for (const auto* headers : {"Origin: https://attacker.example\r\n", + "Origin: null\r\n", + "Origin: http://127.0.0.1:9002/path\r\n", + "Origin: http://127.0.0.1:9002\r\norigin: https://attacker.example\r\n", + "Origin: http://127.0.0.1:9002\r\nOrigin: http://127.0.0.1:9002\r\n"}) { + const auto response = upgrade(headers); + require(response.statusCode == Response::forbidden); + require(!response.getHeaderValue("Sec-WebSocket-Accept")); + require(!response.getHeaderValue("Upgrade")); + require(response.content.contains("WebSocket Origin rejected by content policy")); + require(response.content.contains("bridgeAllowedOrigins")); + require(response.getHeaderValue("Content-Type") == "text/plain; charset=utf-8"); + require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); + } + }); + then("the allow-list and native-client opt-out reach the handshake", [&] { + require(upgrade("Origin: https://ui.example\r\n", {.bridgeAllowedOrigins = {"https://ui.example"}}).statusCode + == Response::switchingProtocols); + require(upgrade("", {.allowMissingOrigin = false}).statusCode == Response::forbidden); + }); + then("a refusal logs an actionable diagnostic for alternate hosts and wildcard binds", [&] { + WarningCapture capture; + require(upgrade("Origin: http://192.168.1.2:9002\r\n").statusCode == Response::forbidden); + require(!capture.messages.empty()); + require(capture.messages.back().contains("bridgeAllowedOrigins")); + require(capture.messages.back().contains("wildcard binds authorize loopback only")); + }); + }}; diff --git a/test/unit/DefaultFSTests.cpp b/test/unit/DefaultFSTests.cpp index 1de5967d..0aa7ed05 100644 --- a/test/unit/DefaultFSTests.cpp +++ b/test/unit/DefaultFSTests.cpp @@ -1,6 +1,5 @@ #include "TemporaryDirectory.hpp" #include - #include #include @@ -24,85 +23,88 @@ class TemporaryRoot { file << content; } - filesystem::path path() const { return root.path(); } + filesystem::path path() const { + return root.path(); + } private: webfront::test::TemporaryDirectory root; }; string readAll(fs::File& file) { - string content; + string content; array buffer; - while (auto bytesRead = file.read(buffer)) content.append(buffer.data(), bytesRead); + while (auto bytesRead = file.read(buffer)) + content.append(buffer.data(), bytesRead); return content; } -} // namespace +} // namespace // The default composition is the protected bridge, the optional root and IndexFS, nothing else. static_assert(std::is_same_v>); const Scenario defaultFSServes{"DefaultFS serves only embedded assets when no document root is configured", [] { - given("a DefaultFS constructed with an empty document root", [&] { - fs::DefaultFS defaultFS{filesystem::path{}}; - - then("the embedded WebFront.js, index.html, and favicon.ico are served", [&] { - require(defaultFS.open("WebFront.js").has_value()); - require(defaultFS.open("index.html").has_value()); - require(defaultFS.open("favicon.ico").has_value()); - }); - - then("an arbitrary file is not found, and no local filesystem access is attempted", [&] { - require(!defaultFS.open("does-not-exist.txt").has_value()); - require(!defaultFS.open("webfront-bootstrap.mjs").has_value()); - }); - }); -}}; + given("a DefaultFS constructed with an empty document root", [&] { + fs::DefaultFS defaultFS{filesystem::path{}}; + + then("the embedded WebFront.js, index.html, and favicon.ico are served", [&] { + require(defaultFS.open("WebFront.js").has_value()); + require(defaultFS.open("index.html").has_value()); + require(defaultFS.open("favicon.ico").has_value()); + }); + + then("an arbitrary file is not found, and no local filesystem access is attempted", [&] { + require(!defaultFS.open("does-not-exist.txt").has_value()); + require(!defaultFS.open("webfront-bootstrap.mjs").has_value()); + }); + }); + }}; const Scenario defaultFSLayers{"DefaultFS layers a configured document root over the embedded fallback", [] { - given("a document root containing a custom index.html", [&] { - TemporaryRoot root; - root.write("index.html", "Custom"); - fs::DefaultFS defaultFS{root.path()}; - - when("index.html is requested", [&] { - auto file = defaultFS.open("index.html"); - then("the custom file overrides the embedded fallback page", [&] { - require(file.has_value()); - require(readAll(*file) == "Custom"); - }); - }); - }); - - given("a document root that also contains a file named WebFront.js", [&] { - TemporaryRoot root; - root.write("WebFront.js", "// not the real bridge script"); - root.write("webfront-dom.mjs", "// wrong DOM version"); - fs::DefaultFS defaultFS{root.path()}; - - when("WebFront.js is requested", [&] { - auto file = defaultFS.open("WebFront.js"); - then("the embedded, version-matched script is served instead of the local file", [&] { - require(file.has_value()); - require(readAll(*file) != "// not the real bridge script"); - auto dom = defaultFS.open("webfront-dom.mjs"); - require(dom.has_value()); - require(readAll(*dom) != "// wrong DOM version"); - }); - }); - }); - - given("a document root containing a file not otherwise served", [&] { - TemporaryRoot root; - root.write("app.mjs", "export const ready = true;"); - fs::DefaultFS defaultFS{root.path()}; - - when("app.mjs is requested", [&] { - auto file = defaultFS.open("app.mjs"); - then("the local development file is served", [&] { - require(file.has_value()); - require(readAll(*file) == "export const ready = true;"); - }); - }); - }); -}}; + given("a document root containing a custom index.html", [&] { + TemporaryRoot root; + root.write("index.html", "Custom"); + fs::DefaultFS defaultFS{root.path()}; + + when("index.html is requested", [&] { + auto file = defaultFS.open("index.html"); + then("the custom file overrides the embedded fallback page", [&] { + require(file.has_value()); + require(readAll(*file) == "Custom"); + }); + }); + }); + + given("a document root that also contains a file named WebFront.js", [&] { + TemporaryRoot root; + root.write("WebFront.js", "// not the real bridge script"); + root.write("webfront-dom.mjs", "// wrong DOM version"); + fs::DefaultFS defaultFS{root.path()}; + + when("WebFront.js is requested", [&] { + auto file = defaultFS.open("WebFront.js"); + then("the embedded, version-matched script is served instead of the local file", [&] { + require(file.has_value()); + require(readAll(*file) != "// not the real bridge script"); + auto dom = defaultFS.open("webfront-dom.mjs"); + require(dom.has_value()); + require(readAll(*dom) != "// wrong DOM version"); + }); + }); + }); + + given("a document root containing a file not otherwise served", [&] { + TemporaryRoot root; + root.write("app.mjs", "export const ready = true;"); + fs::DefaultFS defaultFS{root.path()}; + + when("app.mjs is requested", [&] { + auto file = defaultFS.open("app.mjs"); + then("the local development file is served", [&] { + require(file.has_value()); + require(readAll(*file) == "export const ready = true;"); + }); + }); + }); + }}; diff --git a/test/unit/DeferredCallTests.cpp b/test/unit/DeferredCallTests.cpp index 871dec93..a17866b5 100644 --- a/test/unit/DeferredCallTests.cpp +++ b/test/unit/DeferredCallTests.cpp @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief C++ callbacks that answer a JavaScript call later: their result, failures, stop, disconnection and shutdown (#459). #include "InjectableNetworking.hpp" -#include -#include #include #include +#include +#include #include #include @@ -21,7 +21,7 @@ using Socket = testing::InjectableSocket; namespace { const std::string deferredUpgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; struct DeferredNet : testing::InjectableNetworking { static inline bool accepted{}; @@ -39,13 +39,19 @@ using DeferredApp = BasicWF; /// The operations the test completes by hand, by the name of the call that awaits them. struct DeferredGates { std::vector open; - void release(std::size_t index) { open.at(index).complete({}, 0); } - void stopOne(std::size_t index) { open.at(index).stop(); } + void release(std::size_t index) { + open.at(index).complete({}, 0); + } + void stopOne(std::size_t index) { + open.at(index).stop(); + } }; DeferredGates deferredGates; testing::ManualSender deferredGate() { - return testing::ManualSender([](testing::ManualSender::Completion completion) { deferredGates.open.push_back(std::move(completion)); }); + return testing::ManualSender([](testing::ManualSender::Completion completion) { + deferredGates.open.push_back(std::move(completion)); + }); } ResultTask echoLater(std::string value) { @@ -137,250 +143,259 @@ struct DeferredBrowser { } // namespace const Scenario callbackReturns{"A callback that returns a task answers when the task completes", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("echoLater", &echoLater); - browser.connect(); - - when("the browser calls it", [&] { - browser.call("echoLater", 5, "x"); - then("nothing is answered while the task is suspended", [&] { - require(deferredGates.open.size() == 1); - require(!Socket::wrote("answered:x")); - }); - andWhen("the task completes", [&] { - deferredGates.release(0); - then("its value is sent as the result of the call", [&] { - require(Socket::wrote("answered:x")); - }); - }); - }); - when("the call asks for no answer", [&] { - browser.call("echoLater", 0, "x"); - deferredGates.release(0); - then("nothing is sent", [&] { - require(!Socket::wrote("answered:x")); - }); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + + when("the browser calls it", [&] { + browser.call("echoLater", 5, "x"); + then("nothing is answered while the task is suspended", [&] { + require(deferredGates.open.size() == 1); + require(!Socket::wrote("answered:x")); + }); + andWhen("the task completes", [&] { + deferredGates.release(0); + then("its value is sent as the result of the call", [&] { + require(Socket::wrote("answered:x")); + }); + }); + }); + when("the call asks for no answer", [&] { + browser.call("echoLater", 0, "x"); + deferredGates.release(0); + then("nothing is sent", [&] { + require(!Socket::wrote("answered:x")); + }); + }); + }}; const Scenario deferredCallback{"A deferred callback that fails rejects the call with its code", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("failLater", &failLater); - browser.connect(); - browser.call("failLater", 9, "x"); - deferredGates.release(0); - then("the code and the message are sent", [&] { - require(Socket::wrote("quota:exceeded")); - require(Socket::wrote("the disk is full")); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("failLater", &failLater); + browser.connect(); + browser.call("failLater", 9, "x"); + deferredGates.release(0); + then("the code and the message are sent", [&] { + require(Socket::wrote("quota:exceeded")); + require(Socket::wrote("the disk is full")); + }); + }}; const Scenario deferredCallbackThrows{"A deferred callback that throws before returning its task rejects the call at once", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction, std::string>("throwsNow", [](const std::string&) -> ResultTask { - throw BridgeError("early", "refused before it started"); - }); - browser.connect(); - browser.call("throwsNow", 4, "x"); - then("the rejection is sent without waiting", [&] { - require(Socket::wrote("early")); - require(Socket::wrote("refused before it started")); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction, std::string>("throwsNow", + [](const std::string&) -> ResultTask { + throw BridgeError("early", + "refused before it started"); + }); + browser.connect(); + browser.call("throwsNow", 4, "x"); + then("the rejection is sent without waiting", [&] { + require(Socket::wrote("early")); + require(Socket::wrote("refused before it started")); + }); + }}; const Scenario deferredCallbackWhose{"A deferred callback whose operation is stopped rejects the call as cancelled", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("echoLater", &echoLater); - browser.connect(); - browser.call("echoLater", 3, "x"); - deferredGates.stopOne(0); - then("the cancellation code is sent", [&] { - require(Socket::wrote(std::string(bridge_code::cancelled))); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + browser.call("echoLater", 3, "x"); + deferredGates.stopOne(0); + then("the cancellation code is sent", [&] { + require(Socket::wrote(std::string(bridge_code::cancelled))); + }); + }}; const Scenario callbackMay{"A callback may be a task without result", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("voidLater", &voidLater); - browser.connect(); - Socket::discardWrites(); - const auto before = Socket::discardedBytes(); - browser.call("voidLater", 2); - require(Socket::discardedBytes() == before); - deferredGates.release(0); - then("a return without value is sent", [&] { - require(Socket::discardedBytes() > before); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("voidLater", &voidLater); + browser.connect(); + Socket::discardWrites(); + const auto before = Socket::discardedBytes(); + browser.call("voidLater", 2); + require(Socket::discardedBytes() == before); + deferredGates.release(0); + then("a return without value is sent", [&] { + require(Socket::discardedBytes() > before); + }); + }}; const Scenario callbackTaking{"A callback taking the caller can answer later", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction, DeferredApp::UI, std::string>("withCaller", [](DeferredApp::UI, const std::string& value) -> ResultTask { - return echoLater(value); - }); - browser.connect(); - browser.call("withCaller", 6, "who"); - deferredGates.release(0); - then("the browser receives the value", [&] { - require(Socket::wrote("answered:who")); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction, DeferredApp::UI, std::string>( + "withCaller", + [](DeferredApp::UI, const std::string& value) -> ResultTask { + return echoLater(value); + }); + browser.connect(); + browser.call("withCaller", 6, "who"); + deferredGates.release(0); + then("the browser receives the value", [&] { + require(Socket::wrote("answered:who")); + }); + }}; const Scenario severalDeferred{"Several deferred calls of one connection are answered independently", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("echoLater", &echoLater); - browser.connect(); - browser.call("echoLater", 1, "first"); - browser.call("echoLater", 2, "second"); - browser.call("echoLater", 3, "third"); - require(deferredGates.open.size() == 3); - deferredGates.release(2); - deferredGates.release(0); - then("each is answered when it completes, whatever the order", [&] { - require(Socket::wrote("answered:third")); - require(Socket::wrote("answered:first")); - require(!Socket::wrote("answered:second")); - deferredGates.release(1); - require(Socket::wrote("answered:second")); - require(Socket::writtenAt("answered:third") < Socket::writtenAt("answered:first")); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.connect(); + browser.call("echoLater", 1, "first"); + browser.call("echoLater", 2, "second"); + browser.call("echoLater", 3, "third"); + require(deferredGates.open.size() == 3); + deferredGates.release(2); + deferredGates.release(0); + then("each is answered when it completes, whatever the order", [&] { + require(Socket::wrote("answered:third")); + require(Socket::wrote("answered:first")); + require(!Socket::wrote("answered:second")); + deferredGates.release(1); + require(Socket::wrote("answered:second")); + require(Socket::writtenAt("answered:third") < Socket::writtenAt("answered:first")); + }); + }}; const Scenario callReuses{"A call that reuses the identifier of a running call is dropped without any answer", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("echoLater", &echoLater); - browser.app.cppFunction("plain", [] { return std::string("plain-result"); }); - browser.connect(); - browser.call("echoLater", 7, "first"); - browser.call("echoLater", 7, "again"); - browser.call("plain", 7); - browser.call("noSuchFunction", 7); - then("no callback runs and nothing is sent for the duplicates, whatever the function", [&] { - require(deferredGates.open.size() == 1); - require(!Socket::wrote("plain-result")); - require(!Socket::wrote("already in use")); - require(!Socket::wrote("was not found")); - }); - then("the first call still completes with its own answer", [&] { - deferredGates.release(0); - require(Socket::wrote("answered:first")); - require(!Socket::wrote("answered:again")); - }); - andWhen("it was answered", [&] { - deferredGates.release(0); - browser.call("echoLater", 7, "later"); - then("the identifier is free again", [&] { - require(deferredGates.open.size() == 2); - }); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("echoLater", &echoLater); + browser.app.cppFunction("plain", [] { + return std::string("plain-result"); + }); + browser.connect(); + browser.call("echoLater", 7, "first"); + browser.call("echoLater", 7, "again"); + browser.call("plain", 7); + browser.call("noSuchFunction", 7); + then("no callback runs and nothing is sent for the duplicates, whatever the function", [&] { + require(deferredGates.open.size() == 1); + require(!Socket::wrote("plain-result")); + require(!Socket::wrote("already in use")); + require(!Socket::wrote("was not found")); + }); + then("the first call still completes with its own answer", [&] { + deferredGates.release(0); + require(Socket::wrote("answered:first")); + require(!Socket::wrote("answered:again")); + }); + andWhen("it was answered", [&] { + deferredGates.release(0); + browser.call("echoLater", 7, "later"); + then("the identifier is free again", [&] { + require(deferredGates.open.size() == 2); + }); + }); + }}; const Scenario disconnectionBrowser{"The disconnection of the browser stops its deferred calls and drops their answers", {"deferred"}, [] { - DeferredBrowser browser; - std::weak_ptr observed; - browser.app.cppFunction>("watched", [&observed]() -> ResultTask { - return watchedLater(&observed, std::make_shared(1)); - }); - browser.connect(); - browser.call("watched", 8); - require(!observed.expired()); - - when("the connection closes while the call is pending", [&] { - Socket::fail(std::make_error_code(std::errc::connection_reset)); - then("the work is stopped and destroyed, and no answer is sent", [&] { - require(observed.expired()); - require(!Socket::wrote("late")); - require(!Socket::wrote(std::string(bridge_code::cancelled))); - }); - }); -}}; + DeferredBrowser browser; + std::weak_ptr observed; + browser.app.cppFunction>("watched", [&observed]() -> ResultTask { + return watchedLater(&observed, std::make_shared(1)); + }); + browser.connect(); + browser.call("watched", 8); + require(!observed.expired()); + + when("the connection closes while the call is pending", [&] { + Socket::fail(std::make_error_code(std::errc::connection_reset)); + then("the work is stopped and destroyed, and no answer is sent", [&] { + require(observed.expired()); + require(!Socket::wrote("late")); + require(!Socket::wrote(std::string(bridge_code::cancelled))); + }); + }); + }}; const Scenario shuttingApplication{"Shutting the application down joins its pending deferred calls", {"deferred"}, [] { - DeferredBrowser browser; - std::weak_ptr observed; - browser.app.cppFunction>("watched", [&observed]() -> ResultTask { - return watchedLater(&observed, std::make_shared(1)); - }); - browser.connect(); - browser.call("watched", 8); - require(!observed.expired()); - browser.app.shutdown(); - then("the pending work is gone when shutdown returns", [&] { - require(observed.expired()); - require(!Socket::wrote("late")); - }); -}}; + DeferredBrowser browser; + std::weak_ptr observed; + browser.app.cppFunction>("watched", [&observed]() -> ResultTask { + return watchedLater(&observed, std::make_shared(1)); + }); + browser.connect(); + browser.call("watched", 8); + require(!observed.expired()); + browser.app.shutdown(); + then("the pending work is gone when shutdown returns", [&] { + require(observed.expired()); + require(!Socket::wrote("late")); + }); + }}; const Scenario identifiersFlight{"The identifiers of in-flight calls are claimed once and released on finish", {"deferred"}, [] { - detail::DeferredCalls calls; - const auto key = calls.reserve(5); - require(key != 0); - require(calls.reserve(5) == 0); - require(calls.reserve(0) != 0); // zero asks for no answer: never in flight - require(calls.reserve(0) != 0); - when("the call finishes, as a task the server refused does at once", [&] { - calls.finish(5, key); - then("the identifier can be claimed again", [&] { - require(calls.reserve(5) != 0); - }); - }); - when("the connection closes", [&] { - calls.close(); - then("nothing can be claimed any more", [&] { - require(calls.reserve(6) == 0); - }); - }); -}}; + detail::DeferredCalls calls; + const auto key = calls.reserve(5); + require(key != 0); + require(calls.reserve(5) == 0); + require(calls.reserve(0) != 0); // zero asks for no answer: never in flight + require(calls.reserve(0) != 0); + when("the call finishes, as a task the server refused does at once", [&] { + calls.finish(5, key); + then("the identifier can be claimed again", [&] { + require(calls.reserve(5) != 0); + }); + }); + when("the connection closes", [&] { + calls.close(); + then("nothing can be claimed any more", [&] { + require(calls.reserve(6) == 0); + }); + }); + }}; const Scenario decodedArguments{"The decoded arguments of a deferred callback live until it completes", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction("byReference", &byReferenceLater); - browser.connect(); - browser.call("byReference", 3, std::string(60, 'r')); // beyond the small string buffer: a dangling reference would read freed memory - deferredGates.release(0); - then("the coroutine still reads its argument", [&] { - require(Socket::wrote("reference:" + std::string(60, 'r'))); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction("byReference", &byReferenceLater); + browser.connect(); + browser.call("byReference", + 3, + std::string(60, 'r')); // beyond the small string buffer: a dangling reference would read freed memory + deferredGates.release(0); + then("the coroutine still reads its argument", [&] { + require(Socket::wrote("reference:" + std::string(60, 'r'))); + }); + }}; const Scenario callRefused{"A call refused as a duplicate does not run the callback", {"deferred"}, [] { - DeferredBrowser browser; - sideEffects = 0; - browser.app.cppFunction, std::string>("counting", [](const std::string& value) -> ResultTask { - ++sideEffects; // an action taken before the task is returned - return countingLater(value); - }); - browser.connect(); - browser.call("counting", 7, "first"); - browser.call("counting", 7, "again"); - then("the callback ran once and the duplicate was refused", [&] { - require(sideEffects == 1); - require(!Socket::wrote("already in use")); - }); -}}; + DeferredBrowser browser; + sideEffects = 0; + browser.app.cppFunction, std::string>("counting", + [](const std::string& value) -> ResultTask { + ++sideEffects; // an action taken before the task is returned + return countingLater(value); + }); + browser.connect(); + browser.call("counting", 7, "first"); + browser.call("counting", 7, "again"); + then("the callback ran once and the duplicate was refused", [&] { + require(sideEffects == 1); + require(!Socket::wrote("already in use")); + }); + }}; const Scenario callingUI{"The calling UI of a deferred callback lives until it completes", {"deferred"}, [] { - DeferredBrowser browser; - browser.app.cppFunction, const DeferredApp::UI&, std::string>("uiReference", &uiReferenceLater); - browser.app.cppFunction, DeferredApp::UI&, std::string>("uiMutable", &uiMutableLater); - browser.connect(); - browser.call("uiReference", 1, std::string(60, 'u')); - browser.call("uiMutable", 2, std::string(60, 'm')); - deferredGates.release(0); - deferredGates.release(1); - then("the coroutines still read the UI they were given", [&] { - require(Socket::wrote(":" + std::string(60, 'u'))); - require(Socket::wrote(":" + std::string(60, 'm'))); - require(Socket::wrote("mutable")); - }); -}}; + DeferredBrowser browser; + browser.app.cppFunction, const DeferredApp::UI&, std::string>("uiReference", &uiReferenceLater); + browser.app.cppFunction, DeferredApp::UI&, std::string>("uiMutable", &uiMutableLater); + browser.connect(); + browser.call("uiReference", 1, std::string(60, 'u')); + browser.call("uiMutable", 2, std::string(60, 'm')); + deferredGates.release(0); + deferredGates.release(1); + then("the coroutines still read the UI they were given", [&] { + require(Socket::wrote(":" + std::string(60, 'u'))); + require(Socket::wrote(":" + std::string(60, 'm'))); + require(Socket::wrote("mutable")); + }); + }}; const Scenario callUnknown{"A call to an unknown function is rejected with the not-found code of the bridge", {"deferred"}, [] { - DeferredBrowser browser; - browser.connect(); - browser.call("noSuchFunction", 4); - then("the code reserved to the bridge reaches the browser", [&] { - require(Socket::wrote(std::string(bridge_code::notFound))); - require(Socket::wrote("was not found")); - }); -}}; + DeferredBrowser browser; + browser.connect(); + browser.call("noSuchFunction", 4); + then("the code reserved to the bridge reaches the browser", [&] { + require(Socket::wrote(std::string(bridge_code::notFound))); + require(Socket::wrote("was not found")); + }); + }}; diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index cd339e82..acbb36e7 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -1,11 +1,11 @@ #include "TemporaryDirectory.hpp" -#include #include #include +#include #include -#include #include +#include #include #include #include @@ -49,451 +49,541 @@ std::string read(developer::Store& store, std::string path) { } // namespace const Scenario developerPublication{"Developer publication preserves the installed files until commit", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - given("an installed output", [&] { - auto first = store.begin("generated/LifeUI.hpp", false); - store.write(first, "output", 0, bytes("old")); - store.commit(first); - when("the next output is interrupted", [&] { - auto second = store.begin("generated/LifeUI.hpp", false); - store.write(second, "output", 0, bytes("partial")); - require(read(store, "generated/LifeUI.hpp") == "old"); - store.abort(second); - then("the installed output remains intact", [&] { - require(read(store, "generated/LifeUI.hpp") == "old"); - }); - }); - when("a complete replacement is committed", [&] { - auto second = store.begin("generated/LifeUI.hpp", false); - store.write(second, "output", 0, bytes("new")); - store.commit(second); - then("the new output replaces it", [&] { - require(read(store, "generated/LifeUI.hpp") == "new"); - }); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + given("an installed output", [&] { + auto first = store.begin("generated/LifeUI.hpp", false); + store.write(first, "output", 0, bytes("old")); + store.commit(first); + when("the next output is interrupted", [&] { + auto second = store.begin("generated/LifeUI.hpp", false); + store.write(second, "output", 0, bytes("partial")); + require(read(store, "generated/LifeUI.hpp") == "old"); + store.abort(second); + then("the installed output remains intact", [&] { + require(read(store, "generated/LifeUI.hpp") == "old"); + }); + }); + when("a complete replacement is committed", [&] { + auto second = store.begin("generated/LifeUI.hpp", false); + store.write(second, "output", 0, bytes("new")); + store.commit(second); + then("the new output replaces it", [&] { + require(read(store, "generated/LifeUI.hpp") == "new"); + }); + }); + }); + }}; const Scenario publicationWaits{"A publication waits for a file that another reader is about to release", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - given("a published directory with a file held open, as a scan of what was just written holds it on Windows", [&] { - auto first = store.begin("packages/library", true); - store.write(first, "index.js", 0, bytes("old")); - store.commit(first); - std::ifstream held(project.path() / "packages/library/index.js", std::ios::binary); - require(held.is_open()); - auto released = std::async(std::launch::async, [&held] { - std::this_thread::sleep_for(std::chrono::milliseconds{100}); - held.close(); - }); - when("the directory is replaced before the reader closes the file", [&] { - auto second = store.begin("packages/library", true); - store.write(second, "index.js", 0, bytes("new")); - store.commit(second); - then("the publication is completed once the file is released", [&] { - require(read(store, "packages/library/index.js") == "new"); - }); - }); - released.get(); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + given("a published directory with a file held open, as a scan of what was just written holds it on Windows", [&] { + auto first = store.begin("packages/library", true); + store.write(first, "index.js", 0, bytes("old")); + store.commit(first); + std::ifstream held(project.path() / "packages/library/index.js", std::ios::binary); + require(held.is_open()); + auto released = std::async(std::launch::async, [&held] { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + held.close(); + }); + when("the directory is replaced before the reader closes the file", [&] { + auto second = store.begin("packages/library", true); + store.write(second, "index.js", 0, bytes("new")); + store.commit(second); + then("the publication is completed once the file is released", [&] { + require(read(store, "packages/library/index.js") == "new"); + }); + }); + released.get(); + }); + }}; const Scenario publishedHTTP{"A published HTTP source remains readable across directory replacement", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - fs::DeveloperFS filesystem{project.path()}; - std::string previous = "old-body"; - while (previous.size() < 200000) - previous += static_cast('a' + previous.size() % 26); - auto first = store.begin(".webfront/developer/preview", true); - store.write(first, "app.js", 0, bytes(previous)); - store.commit(first); - auto held = filesystem.open("/webfront/developer/preview/app.js"); - require(held); - require(held->knownSize() == previous.size()); - auto second = store.begin(".webfront/developer/preview", true); - store.write(second, "app.js", 0, bytes("new-body")); - requireNothrow([&] { store.commit(second); }); - std::array content{}; - require(held->read(content) == content.size()); - require(std::string_view(content.data(), content.size()) == "old-body"); - require(held->seek(4)); - require(held->read(std::span(content).first(4)) == 4); - require(std::string_view(content.data(), 4) == "body"); - require(held->seek(65531)); - require(held->read(content) == content.size()); - require(std::string_view(content.data(), content.size()) == std::string_view(previous).substr(65531, content.size())); - require(held->seek(previous.size() - 3)); - require(held->read(content) == 3); - require(std::string_view(content.data(), 3) == std::string_view(previous).substr(previous.size() - 3)); - require(held->read(content) == 0); - auto current = filesystem.open("/webfront/developer/preview/app.js"); - require(current); - require(current->read(content) == content.size()); - require(std::string_view(content.data(), content.size()) == "new-body"); - auto third = store.begin(".webfront/developer/preview", true); - store.write(third, "app.js", 0, {}); - requireNothrow([&] { store.commit(third); }); - auto empty = filesystem.open("/webfront/developer/preview/app.js"); - require(empty); - require(empty->knownSize() == 0); - require(empty->read(content) == 0); - require(current->seek(0)); - require(current->read(content) == content.size()); - require(std::string_view(content.data(), content.size()) == "new-body"); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + fs::DeveloperFS filesystem{project.path()}; + std::string previous = "old-body"; + while (previous.size() < 200000) + previous += static_cast('a' + previous.size() % 26); + auto first = store.begin(".webfront/developer/preview", true); + store.write(first, "app.js", 0, bytes(previous)); + store.commit(first); + auto held = filesystem.open("/webfront/developer/preview/app.js"); + require(held); + require(held->knownSize() == previous.size()); + auto second = store.begin(".webfront/developer/preview", true); + store.write(second, "app.js", 0, bytes("new-body")); + requireNothrow([&] { + store.commit(second); + }); + std::array content{}; + require(held->read(content) == content.size()); + require(std::string_view(content.data(), content.size()) == "old-body"); + require(held->seek(4)); + require(held->read(std::span(content).first(4)) == 4); + require(std::string_view(content.data(), 4) == "body"); + require(held->seek(65531)); + require(held->read(content) == content.size()); + require(std::string_view(content.data(), content.size()) == std::string_view(previous).substr(65531, content.size())); + require(held->seek(previous.size() - 3)); + require(held->read(content) == 3); + require(std::string_view(content.data(), 3) == std::string_view(previous).substr(previous.size() - 3)); + require(held->read(content) == 0); + auto current = filesystem.open("/webfront/developer/preview/app.js"); + require(current); + require(current->read(content) == content.size()); + require(std::string_view(content.data(), content.size()) == "new-body"); + auto third = store.begin(".webfront/developer/preview", true); + store.write(third, "app.js", 0, {}); + requireNothrow([&] { + store.commit(third); + }); + auto empty = filesystem.open("/webfront/developer/preview/app.js"); + require(empty); + require(empty->knownSize() == 0); + require(empty->read(content) == 0); + require(current->seek(0)); + require(current->read(content) == content.size()); + require(std::string_view(content.data(), content.size()) == "new-body"); + }}; const Scenario developerWrites{"Developer writes are bounded and paths stay inside the explicit project", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - given("a staged preview", [&] { - const auto id = store.begin(".webfront/developer/preview", true); - when("the browser sends invalid chunks or paths", [&] { - then("none are published", [&] { - requireThrows([&] { store.write(id, "../escape", 0, bytes("bad")); }); - requireThrows([&] { store.write(id, "index.html", 1, bytes("bad")); }); - requireThrows([&] { store.write(id, "big", 0, std::vector(developer::chunkSize + 1)); }); - requireThrows([&] { store.begin("../escape", false); }); - requireThrows([&] { store.read("../escape", 0); }); - requireThrows([&] { store.begin(".webfront/developer/staging/x", true); }); - requireThrows([&] { store.begin(".webfront", true); }); - requireThrows([&] { store.begin(".webfront/developer", true); }); - requireThrows([&] { store.begin(".webfront/developer/preview/assets", true); }); - }); - }); - when("a zero-length file and a nested file are sent", [&] { - store.write(id, "empty", 0, {}); - store.write(id, "assets/a.js", 0, bytes("abc")); - store.write(id, "assets/a.js", 3, bytes("def")); - store.commit(id); - then("both are readable after commit", [&] { - require(read(store, ".webfront/developer/preview/empty").empty()); - requireThrows([&] { store.read(".webfront/developer/preview/assets", 0); }); - require(read(store, ".webfront/developer/preview/assets/a.js") == "abcdef"); - }); - }); - }); - given("an escaping directory symlink", [&] { - TemporaryDirectory outside; - std::error_code error; - std::filesystem::create_directory_symlink(outside.path(), project.path() / "escape", error); - if (!error) { - then("reads and destinations are rejected", [&] { - requireThrows([&] { store.begin("escape/new.hpp", false); }); - requireThrows([&] { store.read("escape/secret", 0); }); - }); - } - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + given("a staged preview", [&] { + const auto id = store.begin(".webfront/developer/preview", true); + when("the browser sends invalid chunks or paths", [&] { + then("none are published", [&] { + requireThrows([&] { + store.write(id, "../escape", 0, bytes("bad")); + }); + requireThrows([&] { + store.write(id, "index.html", 1, bytes("bad")); + }); + requireThrows([&] { + store.write(id, "big", 0, std::vector(developer::chunkSize + 1)); + }); + requireThrows([&] { + store.begin("../escape", false); + }); + requireThrows([&] { + store.read("../escape", 0); + }); + requireThrows([&] { + store.begin(".webfront/developer/staging/x", true); + }); + requireThrows([&] { + store.begin(".webfront", true); + }); + requireThrows([&] { + store.begin(".webfront/developer", true); + }); + requireThrows([&] { + store.begin(".webfront/developer/preview/assets", true); + }); + }); + }); + when("a zero-length file and a nested file are sent", [&] { + store.write(id, "empty", 0, {}); + store.write(id, "assets/a.js", 0, bytes("abc")); + store.write(id, "assets/a.js", 3, bytes("def")); + store.commit(id); + then("both are readable after commit", [&] { + require(read(store, ".webfront/developer/preview/empty").empty()); + requireThrows([&] { + store.read(".webfront/developer/preview/assets", 0); + }); + require(read(store, ".webfront/developer/preview/assets/a.js") == "abcdef"); + }); + }); + }); + given("an escaping directory symlink", [&] { + TemporaryDirectory outside; + std::error_code error; + std::filesystem::create_directory_symlink(outside.path(), project.path() / "escape", error); + if (!error) { + then("reads and destinations are rejected", [&] { + requireThrows([&] { + store.begin("escape/new.hpp", false); + }); + requireThrows([&] { + store.read("escape/secret", 0); + }); + }); + } + }); + }}; const Scenario developerFilesystem{"Developer filesystem serves only published resources and protects the bridge", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - fs::DeveloperFS filesystem{project.path()}; - given("published preview and test runner assets and private project files", [&] { - const auto id = store.begin(".webfront/developer/preview", true); - store.write(id, "index.html", 0, bytes("preview")); - store.commit(id); - const auto runner = store.begin(".webfront/developer/test", true); - store.write(runner, "index.html", 0, bytes("runner")); - store.commit(runner); - then("the preview and bootstrap are served but project sources are not", [&] { - require(filesystem.open("/webfront/developer/preview/index.html")); - require(filesystem.open("/webfront/developer/test/index.html")); - require(!filesystem.open("/webfront/developer/build/app.js")); - require(filesystem.open("/webfront-bootstrap.html")); - require(filesystem.open("/webfront-bootstrap.mjs")); - require(filesystem.open("/WebFront.js")); - require(!filesystem.open("/CMakeLists.txt")); - require(!filesystem.open("/webfront/developer/staging/file")); - require(!filesystem.open("/webfront/developer/preview/../../secret")); - require(http::MimeType("wasm").toString() == "application/wasm"); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + fs::DeveloperFS filesystem{project.path()}; + given("published preview and test runner assets and private project files", [&] { + const auto id = store.begin(".webfront/developer/preview", true); + store.write(id, "index.html", 0, bytes("preview")); + store.commit(id); + const auto runner = store.begin(".webfront/developer/test", true); + store.write(runner, "index.html", 0, bytes("runner")); + store.commit(runner); + then("the preview and bootstrap are served but project sources are not", [&] { + require(filesystem.open("/webfront/developer/preview/index.html")); + require(filesystem.open("/webfront/developer/test/index.html")); + require(!filesystem.open("/webfront/developer/build/app.js")); + require(filesystem.open("/webfront-bootstrap.html")); + require(filesystem.open("/webfront-bootstrap.mjs")); + require(filesystem.open("/WebFront.js")); + require(!filesystem.open("/CMakeLists.txt")); + require(!filesystem.open("/webfront/developer/staging/file")); + require(!filesystem.open("/webfront/developer/preview/../../secret")); + require(http::MimeType("wasm").toString() == "application/wasm"); + }); + }); + }}; const Scenario downloadedStarter{"A downloaded starter never replaces a developer's existing project", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - given("an existing project directory", [&] { - std::filesystem::create_directories(project.path() / "ui"); - then("new-only publication refuses to stage over it", [&] { - requireThrows([&] { store.begin("ui", true, false); }); - require(std::filesystem::is_directory(project.path() / "ui")); - }); - }); - given("a new starter staged before its destination exists", [&] { - auto id = store.begin("new-ui", true, false); - store.write(id, "main.tsx", 0, bytes("starter")); - when("a local directory appears before commit", [&] { - std::filesystem::create_directory(project.path() / "new-ui"); - then("commit refuses to replace that directory", [&] { - requireThrows([&] { store.commit(id); }); - require(!std::filesystem::exists(project.path() / "new-ui/main.tsx")); - store.abort(id); - }); - }); - when("the destination remains new", [&] { - store.commit(id); - then("the starter is published", [&] { - require(read(store, "new-ui/main.tsx") == "starter"); - }); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + given("an existing project directory", [&] { + std::filesystem::create_directories(project.path() / "ui"); + then("new-only publication refuses to stage over it", [&] { + requireThrows([&] { + store.begin("ui", true, false); + }); + require(std::filesystem::is_directory(project.path() / "ui")); + }); + }); + given("a new starter staged before its destination exists", [&] { + auto id = store.begin("new-ui", true, false); + store.write(id, "main.tsx", 0, bytes("starter")); + when("a local directory appears before commit", [&] { + std::filesystem::create_directory(project.path() / "new-ui"); + then("commit refuses to replace that directory", [&] { + requireThrows([&] { + store.commit(id); + }); + require(!std::filesystem::exists(project.path() / "new-ui/main.tsx")); + store.abort(id); + }); + }); + when("the destination remains new", [&] { + store.commit(id); + then("the starter is published", [&] { + require(read(store, "new-ui/main.tsx") == "starter"); + }); + }); + }); + }}; const Scenario transactionsAbandoned{"Transactions abandoned by a disconnected browser never lock the project", [] { - TemporaryDirectory project; - const auto stagingRoot = project.path() / ".webfront/developer/staging"; - given("the maximum number of unfinished transactions", [&] { - developer::Store store{project.path()}; - std::vector ids; - for (std::size_t index = 0; index < developer::maxTransactions; ++index) - ids.push_back(store.begin("generated/" + std::to_string(index), true)); - then("active transactions still bound the number of publications", [&] { - requireThrows([&] { store.begin("generated/extra", true); }); - }); - }); - given("unfinished transactions left by a browser that reloaded", [&] { - developer::Store store{project.path(), std::chrono::milliseconds{0}}; - std::vector ids; - for (std::size_t index = 0; index < developer::maxTransactions; ++index) - ids.push_back(store.begin("generated/" + std::to_string(index), true)); - when("a new publication begins", [&] { - const auto id = store.begin("generated/new", true); - then("the abandoned ones are discarded with their staging", [&] { - require(!std::filesystem::exists(stagingRoot / ids.front())); - requireThrows([&] { store.write(ids.front(), "file", 0, bytes("late")); }); - store.write(id, "file", 0, bytes("fresh")); - store.commit(id); - require(read(store, "generated/new/file") == "fresh"); - }); - }); - }); - given("staging left by a crashed process", [&] { - std::filesystem::create_directories(stagingRoot / "1"); - std::filesystem::create_directories(stagingRoot / "2"); - std::filesystem::last_write_time(stagingRoot / "1", std::filesystem::file_time_type::clock::now() - std::chrono::hours{2}); - when("the project is opened again", [&] { - developer::Store store{project.path()}; - then("only the stale staging is removed", [&] { - require(!std::filesystem::exists(stagingRoot / "1")); - require(std::filesystem::exists(stagingRoot / "2")); - }); - }); - }); - given("a backup left by a crashed commit", [&] { - developer::Store store{project.path()}; - auto first = store.begin("generated/out.hpp", false); - store.write(first, "output", 0, bytes("old")); - store.commit(first); - const auto second = store.begin("generated/out.hpp", false); - store.write(second, "output", 0, bytes("new")); - std::filesystem::create_directories(stagingRoot / (second + "-backup/inner")); - std::ofstream{stagingRoot / (second + "-backup/inner/file")} << "stale"; - then("the replacement still commits", [&] { - store.commit(second); - require(read(store, "generated/out.hpp") == "new"); - }); - }); -}}; + TemporaryDirectory project; + const auto stagingRoot = project.path() / ".webfront/developer/staging"; + given("the maximum number of unfinished transactions", [&] { + developer::Store store{project.path()}; + std::vector ids; + for (std::size_t index = 0; index < developer::maxTransactions; ++index) + ids.push_back(store.begin("generated/" + std::to_string(index), true)); + then("active transactions still bound the number of publications", [&] { + requireThrows([&] { + store.begin("generated/extra", true); + }); + }); + }); + given("unfinished transactions left by a browser that reloaded", [&] { + developer::Store store{project.path(), std::chrono::milliseconds{0}}; + std::vector ids; + for (std::size_t index = 0; index < developer::maxTransactions; ++index) + ids.push_back(store.begin("generated/" + std::to_string(index), true)); + when("a new publication begins", [&] { + const auto id = store.begin("generated/new", true); + then("the abandoned ones are discarded with their staging", [&] { + require(!std::filesystem::exists(stagingRoot / ids.front())); + requireThrows([&] { + store.write(ids.front(), "file", 0, bytes("late")); + }); + store.write(id, "file", 0, bytes("fresh")); + store.commit(id); + require(read(store, "generated/new/file") == "fresh"); + }); + }); + }); + given("staging left by a crashed process", [&] { + std::filesystem::create_directories(stagingRoot / "1"); + std::filesystem::create_directories(stagingRoot / "2"); + std::filesystem::last_write_time(stagingRoot / "1", + std::filesystem::file_time_type::clock::now() - std::chrono::hours{2}); + when("the project is opened again", [&] { + developer::Store store{project.path()}; + then("only the stale staging is removed", [&] { + require(!std::filesystem::exists(stagingRoot / "1")); + require(std::filesystem::exists(stagingRoot / "2")); + }); + }); + }); + given("a backup left by a crashed commit", [&] { + developer::Store store{project.path()}; + auto first = store.begin("generated/out.hpp", false); + store.write(first, "output", 0, bytes("old")); + store.commit(first); + const auto second = store.begin("generated/out.hpp", false); + store.write(second, "output", 0, bytes("new")); + std::filesystem::create_directories(stagingRoot / (second + "-backup/inner")); + std::ofstream{stagingRoot / (second + "-backup/inner/file")} << "stale"; + then("the replacement still commits", [&] { + store.commit(second); + require(read(store, "generated/out.hpp") == "new"); + }); + }); + }}; const Scenario linkNever{"A link never turns the staging area into a destination or leads its cleanup outside the project", [] { - TemporaryDirectory project; - given("a symbolic link to the staging area inside the project", [&] { - developer::Store store{project.path()}; - std::filesystem::create_directories(project.path() / ".webfront/developer/staging"); - const auto victim = store.begin("victim", true); - std::error_code error; - std::filesystem::create_directory_symlink(project.path() / ".webfront/developer/staging", project.path() / "alias", error); - if (!error) { - then("it cannot be used as a publication destination", [&] { - requireThrows([&] { store.begin("alias", true); }); - requireThrows([&] { store.begin("alias/" + victim, true); }); - }); - } - store.abort(victim); - }); - given("a staging directory that is a link to an old file outside the project", [&] { - TemporaryDirectory outside; - const auto victim = outside.path() / "keep.txt"; - std::ofstream{victim} << "outside"; - std::filesystem::last_write_time(victim, std::filesystem::file_time_type::clock::now() - std::chrono::hours{3}); - std::filesystem::create_directories(project.path() / ".webfront/developer"); - std::error_code error; - std::filesystem::create_directory_symlink(outside.path(), project.path() / ".webfront/developer/staging", error); - if (!error) { - when("the project is opened, which cleans the stale staging", [&] { - developer::Store store{project.path()}; - then("the outside file is untouched", [&] { - require(std::filesystem::exists(victim)); - }); - }); - } - }); -}}; + TemporaryDirectory project; + given("a symbolic link to the staging area inside the project", [&] { + developer::Store store{project.path()}; + std::filesystem::create_directories(project.path() / ".webfront/developer/staging"); + const auto victim = store.begin("victim", true); + std::error_code error; + std::filesystem::create_directory_symlink(project.path() / ".webfront/developer/staging", project.path() / "alias", error); + if (!error) { + then("it cannot be used as a publication destination", [&] { + requireThrows([&] { + store.begin("alias", true); + }); + requireThrows([&] { + store.begin("alias/" + victim, true); + }); + }); + } + store.abort(victim); + }); + given("a staging directory that is a link to an old file outside the project", [&] { + TemporaryDirectory outside; + const auto victim = outside.path() / "keep.txt"; + std::ofstream{victim} << "outside"; + std::filesystem::last_write_time(victim, std::filesystem::file_time_type::clock::now() - std::chrono::hours{3}); + std::filesystem::create_directories(project.path() / ".webfront/developer"); + std::error_code error; + std::filesystem::create_directory_symlink(outside.path(), project.path() / ".webfront/developer/staging", error); + if (!error) { + when("the project is opened, which cleans the stale staging", [&] { + developer::Store store{project.path()}; + then("the outside file is untouched", [&] { + require(std::filesystem::exists(victim)); + }); + }); + } + }); + }}; const Scenario developerBridge{"The developer bridge refuses WebSocket clients without an Origin", [] { - given("the default application configuration", [&] { - require(WebFrontConfig{}.contentPolicy.allowMissingOrigin); - when("it is prepared for a developer project", [&] { - const auto config = developer::projectConfig({}, "project"); - then("the project is the document root and a missing Origin is refused", [&] { - require(config.documentRoot == "project"); - require(!config.contentPolicy.allowMissingOrigin); - }); - }); - }); -}}; + given("the default application configuration", [&] { + require(WebFrontConfig{}.contentPolicy.allowMissingOrigin); + when("it is prepared for a developer project", [&] { + const auto config = developer::projectConfig({}, "project"); + then("the project is the document root and a missing Origin is refused", [&] { + require(config.documentRoot == "project"); + require(!config.contentPolicy.allowMissingOrigin); + }); + }); + }); + }}; const Scenario developerStore{"The developer store refuses malformed requests without changing the project", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - given("a staged directory holding LICENSE", [&] { - const auto id = store.begin("package", true); - store.write(id, "LICENSE", 0, bytes("first")); - then("a second file whose name differs only by case is refused, and the first keeps its content", [&] { - requireThrows([&] { store.write(id, "License", 0, bytes("second")); }); - store.write(id, "LICENSE", 5, bytes("!")); - store.commit(id); - require(read(store, "package/LICENSE") == "first!"); - }); - }); - given("a project file and a single-output transaction", [&] { - std::ofstream(project.path() / "notes.txt") << "text"; - const auto id = store.begin("generated/output.hpp", false); - then("invalid reads and writes are rejected", [&] { - requireThrows([&] { store.read("notes.txt", std::numeric_limits::max()); }); - requireThrows([&] { store.write(id, "other", 0, bytes("x")); }); - requireThrows([&] { store.commit(id); }); - }); - then("aborting is idempotent and ends the transaction", [&] { - requireNothrow([&] { store.abort("unknown"); }); - requireNothrow([&] { store.abort(id); }); - requireThrows([&] { store.commit(id); }); - }); - }); - given("an existing destination", [&] { - std::ofstream(project.path() / "taken.txt") << "text"; - then("only the replacing form may publish over it", [&] { - requireThrows([&] { store.beginNew("taken.txt", false); }); - requireNothrow([&] { store.abort(store.beginReplacing("taken.txt", false)); }); - }); - }); - given("a path that is not a directory", [&] { - std::ofstream(project.path() / "file") << "x"; - then("it cannot be a project", [&] { - requireThrows([&] { developer::Store{project.path() / "file"}; }); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + given("a staged directory holding LICENSE", [&] { + const auto id = store.begin("package", true); + store.write(id, "LICENSE", 0, bytes("first")); + then("a second file whose name differs only by case is refused, and the first keeps its content", [&] { + requireThrows([&] { + store.write(id, "License", 0, bytes("second")); + }); + store.write(id, "LICENSE", 5, bytes("!")); + store.commit(id); + require(read(store, "package/LICENSE") == "first!"); + }); + }); + given("a project file and a single-output transaction", [&] { + std::ofstream(project.path() / "notes.txt") << "text"; + const auto id = store.begin("generated/output.hpp", false); + then("invalid reads and writes are rejected", [&] { + requireThrows([&] { + store.read("notes.txt", std::numeric_limits::max()); + }); + requireThrows([&] { + store.write(id, "other", 0, bytes("x")); + }); + requireThrows([&] { + store.commit(id); + }); + }); + then("aborting is idempotent and ends the transaction", [&] { + requireNothrow([&] { + store.abort("unknown"); + }); + requireNothrow([&] { + store.abort(id); + }); + requireThrows([&] { + store.commit(id); + }); + }); + }); + given("an existing destination", [&] { + std::ofstream(project.path() / "taken.txt") << "text"; + then("only the replacing form may publish over it", [&] { + requireThrows([&] { + store.beginNew("taken.txt", false); + }); + requireNothrow([&] { + store.abort(store.beginReplacing("taken.txt", false)); + }); + }); + }); + given("a path that is not a directory", [&] { + std::ofstream(project.path() / "file") << "x"; + then("it cannot be a project", [&] { + requireThrows([&] { + developer::Store{project.path() / "file"}; + }); + }); + }); + }}; const Scenario developerApplication{"A developer application is not told to use the developer environment", [] { - using App = BasicDeveloperApp; - TemporaryDirectory project; - std::ostringstream captured; - struct Redirect { - explicit Redirect(std::ostream& out) { - detail::developmentPathOutput = &out; - detail::developmentPathNoted.clear(); - } - ~Redirect() { detail::developmentPathOutput = nullptr; } - } const redirect{captured}; - given("a project whose developer environment is bootstrapped", [&] { - App app(project.path(), WebFrontConfig{.port = "0"}); - app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); - when("it is shown", [&] { - app.show(); - then("its document root, the project that wf builds, raises no note", [&] { - require(captured.str().find(detail::developmentPathNote) == std::string::npos); + using App = BasicDeveloperApp; + TemporaryDirectory project; + std::ostringstream captured; + struct Redirect { + explicit Redirect(std::ostream& out) { + detail::developmentPathOutput = &out; + detail::developmentPathNoted.clear(); + } + ~Redirect() { + detail::developmentPathOutput = nullptr; + } + } const redirect{captured}; + given("a project whose developer environment is bootstrapped", [&] { + App app(project.path(), WebFrontConfig{.port = "0"}); + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); + when("it is shown", [&] { + app.show(); + then("its document root, the project that wf builds, raises no note", [&] { + require(captured.str().find(detail::developmentPathNote) == std::string::npos); + }); + }); + }); + given("the same application without its developer environment", [&] { + App app(project.path(), WebFrontConfig{.port = "0"}); + when("it is shown", [&] { + app.show(); + then("it serves a plain document root and is told the development path", [&] { + require(captured.str().find(detail::developmentPathNote) != std::string::npos); + }); + }); + }); + }}; + +const Scenario developerApplicationNeeds{ + "The developer application needs an explicit project and a trusted environment", + [] { + using App = BasicDeveloperApp; + const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; + given("no project directory", [&] { + App app({}, WebFrontConfig{.port = "0"}); + then("bootstrap is refused", [&] { + requireThrows([&] { + app.bootstrap("developer", trusted); + }); }); }); - }); - given("the same application without its developer environment", [&] { - App app(project.path(), WebFrontConfig{.port = "0"}); - when("it is shown", [&] { - app.show(); - then("it serves a plain document root and is told the development path", [&] { - require(captured.str().find(detail::developmentPathNote) != std::string::npos); + given("a project directory", [&] { + TemporaryDirectory project; + App app(project.path(), WebFrontConfig{.port = "0"}); + then("an unknown mode or an unpinned environment is refused", [&] { + requireThrows([&] { + app.bootstrap("other", trusted); + }); + requireThrows([&] { + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "md5-abc"}); + }); + requireThrows([&] { + app.bootstrap("developer", {.environment = "", .integrity = "sha512-abc"}); + }); + }); + then("a pinned environment is accepted once", [&] { + requireNothrow([&] { + app.bootstrap("developer", trusted); + }); + requireThrows([&] { + app.bootstrap("developer", trusted); + }); + }); + then("a registry that is neither HTTPS nor same-origin is refused", [&] { + for (const auto* registry : {"http://registry.test/", "//registry.test/", "/\\registry.test/", "/mirror\\..\\x/", "registry/", ""}) { + auto options = trusted; + options.registry = registry; + requireThrows([&] { + app.bootstrap("developer", options); + }); + } + }); + then("a manifest directory that is absolute, has an empty or dot component, or leaves the project is refused", [&] { + for (const auto* directory : + {"/etc", "a//b", "a/", "../outside", "a/../b", "a\\b", "C:/wf", "./wf", ".webfront", ".webfront/developer/preview"}) { + auto options = trusted; + options.manifestDirectory = directory; + requireThrows([&] { + app.bootstrap("developer", options); + }); + } + }); + then("a relative manifest directory is accepted", [&] { + auto options = trusted; + options.manifestDirectory = "js/developer"; + requireNothrow([&] { + app.bootstrap("developer", options); + }); }); }); - }); -}}; + }}; -const Scenario developerApplicationNeeds{"The developer application needs an explicit project and a trusted environment", [] { - using App = BasicDeveloperApp; - const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; - given("no project directory", [&] { - App app({}, WebFrontConfig{.port = "0"}); - then("bootstrap is refused", [&] { - requireThrows([&] { app.bootstrap("developer", trusted); }); - }); - }); - given("a project directory", [&] { - TemporaryDirectory project; - App app(project.path(), WebFrontConfig{.port = "0"}); - then("an unknown mode or an unpinned environment is refused", [&] { - requireThrows([&] { app.bootstrap("other", trusted); }); - requireThrows([&] { app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "md5-abc"}); }); - requireThrows([&] { app.bootstrap("developer", {.environment = "", .integrity = "sha512-abc"}); }); - }); - then("a pinned environment is accepted once", [&] { - requireNothrow([&] { app.bootstrap("developer", trusted); }); - requireThrows([&] { app.bootstrap("developer", trusted); }); - }); - then("a registry that is neither HTTPS nor same-origin is refused", [&] { - for (const auto* registry : {"http://registry.test/", "//registry.test/", "/\\registry.test/", "/mirror\\..\\x/", "registry/", ""}) { - auto options = trusted; - options.registry = registry; - requireThrows([&] { app.bootstrap("developer", options); }); - } - }); - then("a manifest directory that is absolute, has an empty or dot component, or leaves the project is refused", [&] { - for (const auto* directory : {"/etc", "a//b", "a/", "../outside", "a/../b", "a\\b", "C:/wf", "./wf", ".webfront", ".webfront/developer/preview"}) { - auto options = trusted; - options.manifestDirectory = directory; - requireThrows([&] { app.bootstrap("developer", options); }); - } +const Scenario environmentLearns{ + "The environment learns which registry and manifest directory the application chose", + [] { + const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; + given("neither option", [&] { + then( + "the default registry is passed and marked as not chosen, so the manifest's applies, and the manifest is in the " + "project directory", + [&] { + require( + developer::bootstrapConfig(trusted) + == R"({"environment":"https://example.test/env.tgz","integrity":"sha512-abc","registry":"https://registry.npmjs.org/","registryExplicit":false,"supported":{"protocol":[1],"api":[1]}})"); + }); }); - then("a relative manifest directory is accepted", [&] { + given("a manifest directory chosen by the application", [&] { auto options = trusted; options.manifestDirectory = "js/developer"; - requireNothrow([&] { app.bootstrap("developer", options); }); - }); - }); -}}; - -const Scenario environmentLearns{"The environment learns which registry and manifest directory the application chose", [] { - const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; - given("neither option", [&] { - then("the default registry is passed and marked as not chosen, so the manifest's applies, and the manifest is in the " - "project directory", [&] { - require(developer::bootstrapConfig(trusted) - == R"({"environment":"https://example.test/env.tgz","integrity":"sha512-abc","registry":"https://registry.npmjs.org/","registryExplicit":false,"supported":{"protocol":[1],"api":[1]}})"); - }); - }); - given("a manifest directory chosen by the application", [&] { - auto options = trusted; - options.manifestDirectory = "js/developer"; - then("it is passed, before the supported versions", [&] { - require(developer::bootstrapConfig(options), - endsWith(R"("registryExplicit":false,"manifestDirectory":"js/developer","supported":{"protocol":[1],"api":[1]}})")); + then("it is passed, before the supported versions", [&] { + require(developer::bootstrapConfig(options), + endsWith(R"("registryExplicit":false,"manifestDirectory":"js/developer","supported":{"protocol":[1],"api":[1]}})")); + }); }); - }); - given("a same-origin mirror chosen by the application", [&] { - auto options = trusted; - options.registry = "/mirror/"; - then("it is passed as the application's choice", [&] { - require(developer::bootstrapConfig(options), endsWith(R"("registry":"/mirror/","registryExplicit":true,"supported":{"protocol":[1],"api":[1]}})")); + given("a same-origin mirror chosen by the application", [&] { + auto options = trusted; + options.registry = "/mirror/"; + then("it is passed as the application's choice", [&] { + require(developer::bootstrapConfig(options), + endsWith(R"("registry":"/mirror/","registryExplicit":true,"supported":{"protocol":[1],"api":[1]}})")); + }); }); - }); -}}; + }}; namespace { -constexpr auto manifestPath = "webfront.project.json"; -constexpr auto lockPath = "webfront-packages.lock.json"; +constexpr auto manifestPath = "webfront.project.json"; +constexpr auto lockPath = "webfront-packages.lock.json"; const std::vector pair{manifestPath, lockPath}; void publishFile(developer::Store& store, const std::string& path, std::string_view text) { @@ -519,8 +609,9 @@ void publishPair(developer::Store& store, std::string_view manifest, std::string // The lock file stays in the journal directory; anything else is a journal or its remains. [[nodiscard]] bool journalsRemain(const std::filesystem::path& directory) { - return std::ranges::any_of(std::filesystem::directory_iterator(directory), - [](const auto& entry) { return entry.path().filename() != developer::lockName; }); + return std::ranges::any_of(std::filesystem::directory_iterator(directory), [](const auto& entry) { + return entry.path().filename() != developer::lockName; + }); } [[nodiscard]] std::string projectState(developer::Store& store) { @@ -535,261 +626,292 @@ void publishPair(developer::Store& store, std::string_view manifest, std::string throw developer::InjectedFault{"crash at " + step}; }}; const auto expected = store.state(pair); - requireThrows([&] { publishPair(store, "manifest-2", "lock-2", expected); }); + requireThrows([&] { + publishPair(store, "manifest-2", "lock-2", expected); + }); } developer::Store reopened{project}; return projectState(reopened); } } // namespace -const Scenario manifestLock{"A manifest and its lock are published together or not at all", [] { - TemporaryDirectory project; - { - developer::Store store{project.path()}; - publishFile(store, manifestPath, "manifest-1"); - publishFile(store, lockPath, "lock-1"); - } - given("an installed manifest and lock", [&] { - developer::Store store{project.path()}; - when("both files are published after an uninterrupted install", [&] { - publishPair(store, "manifest-2", "lock-2", store.state(pair)); - then("both are replaced and no journal remains", [&] { - require(projectState(store) == "manifest-2|lock-2"); - require(!journalsRemain(project.path() / ".webfront/developer/journal")); +const Scenario manifestLock{ + "A manifest and its lock are published together or not at all", + [] { + TemporaryDirectory project; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + given("an installed manifest and lock", [&] { + developer::Store store{project.path()}; + when("both files are published after an uninterrupted install", [&] { + publishPair(store, "manifest-2", "lock-2", store.state(pair)); + then("both are replaced and no journal remains", [&] { + require(projectState(store) == "manifest-2|lock-2"); + require(!journalsRemain(project.path() / ".webfront/developer/journal")); + }); }); - }); - when("the process stops before the journal is committed", [&] { - store.state(pair); - then("the previous state is intact after restart", [&] { - require(crashAt("before-journal", project.path()) == "manifest-1|lock-1"); + when("the process stops before the journal is committed", [&] { + store.state(pair); + then("the previous state is intact after restart", [&] { + require(crashAt("before-journal", project.path()) == "manifest-1|lock-1"); + }); }); - }); - when("the process stops right after the journal is committed", [&] { - then("restart completes the publication", [&] { - require(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); + when("the process stops right after the journal is committed", [&] { + then("restart completes the publication", [&] { + require(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); + }); }); - }); - when("the process stops between the two replacements", [&] { - then("restart completes the publication", [&] { - require(crashAt("replacement-1", project.path()) == "manifest-2|lock-2"); + when("the process stops between the two replacements", [&] { + then("restart completes the publication", [&] { + require(crashAt("replacement-1", project.path()) == "manifest-2|lock-2"); + }); }); - }); - when("the process stops once the replacements are durable but the journal is still there", [&] { - then("restart completes the publication", [&] { - require(crashAt("replacements-synced", project.path()) == "manifest-2|lock-2"); + when("the process stops once the replacements are durable but the journal is still there", [&] { + then("restart completes the publication", [&] { + require(crashAt("replacements-synced", project.path()) == "manifest-2|lock-2"); + }); }); - }); - when("the journal is removed", [&] { - std::vector steps; - std::vector journalPresent; - { - developer::Store observed{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { - steps.emplace_back(name); - if (name == "replacements-synced") - journalPresent.push_back(journalsRemain(project.path() / ".webfront/developer/journal")); - }}; - publishPair(observed, "manifest-2", "lock-2", observed.state(pair)); - } - then("it is only after both replacements, and the journal was still present until then", [&] { - require(steps == std::vector{"before-journal", "after-journal", "replacement-1", "replacement-2", "replacements-synced"}); - require(journalPresent == std::vector{true}); + when("the journal is removed", [&] { + std::vector steps; + std::vector journalPresent; + { + developer::Store observed{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { + steps.emplace_back(name); + if (name == "replacements-synced") + journalPresent.push_back(journalsRemain(project.path() / ".webfront/developer/journal")); + }}; + publishPair(observed, "manifest-2", "lock-2", observed.state(pair)); + } + then("it is only after both replacements, and the journal was still present until then", [&] { + require(steps == std::vector{"before-journal", "after-journal", "replacement-1", "replacement-2", "replacements-synced"}); + require(journalPresent == std::vector{true}); + }); }); - }); - when("the process stops after the second replacement", [&] { - then("restart completes the publication", [&] { - require(crashAt("replacement-2", project.path()) == "manifest-2|lock-2"); + when("the process stops after the second replacement", [&] { + then("restart completes the publication", [&] { + require(crashAt("replacement-2", project.path()) == "manifest-2|lock-2"); + }); }); }); - }); - given("a publication committed but interrupted between its replacements", [&] { - { - developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { - if (name == "replacement-1") - throw developer::InjectedFault{"crash"}; - }}; - requireThrows([&] { publishPair(store, "manifest-2", "lock-2", store.state(pair)); }); - } - when("the recovery itself is interrupted, once at each of its steps", [&] { - for (const char* step : {"replacement-1", "replacement-2"}) { - requireThrows([&] { developer::Store(project.path(), developer::defaultAbandonedAfter, - [step](std::string_view name) { - if (name == step) - throw developer::InjectedFault{"crash"}; - }); }); + given("a publication committed but interrupted between its replacements", [&] { + { + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "replacement-1") + throw developer::InjectedFault{"crash"}; + }}; + requireThrows([&] { + publishPair(store, "manifest-2", "lock-2", store.state(pair)); + }); } - then("a later restart still reaches the new state", [&] { - developer::Store store{project.path()}; - require(projectState(store) == "manifest-2|lock-2"); - require(!journalsRemain(project.path() / ".webfront/developer/journal")); - }); - }); - }); - given("leftovers of a publication that never reached its commit point", [&] { - const auto journal = project.path() / ".webfront/developer/journal"; - std::filesystem::create_directories(journal / "7.d"); - std::ofstream{journal / "7.d" / "0"} << "orphan"; - std::ofstream{journal / "7.tmp"} << "webfront-journal 1\nwebfront.project.json\n0\n"; - std::ofstream{journal / "8.journal"} << "webfront-journal 1\nwebfront.project.json\n0\n"; - when("the project is opened", [&] { - developer::Store store{project.path()}; - then("they are abandoned and the project keeps its files", [&] { - require(!journalsRemain(journal)); - require(projectState(store) == "manifest-1|lock-1"); + when("the recovery itself is interrupted, once at each of its steps", [&] { + for (const char* step : {"replacement-1", "replacement-2"}) { + requireThrows([&] { + developer::Store(project.path(), developer::defaultAbandonedAfter, [step](std::string_view name) { + if (name == step) + throw developer::InjectedFault{"crash"}; + }); + }); + } + then("a later restart still reaches the new state", [&] { + developer::Store store{project.path()}; + require(projectState(store) == "manifest-2|lock-2"); + require(!journalsRemain(project.path() / ".webfront/developer/journal")); + }); }); }); - }); -}}; - -const Scenario committedPublication{"A committed publication that cannot be completed does not prevent opening the project", [] { - TemporaryDirectory project; - const auto journal = project.path() / ".webfront/developer/journal"; - { - developer::Store store{project.path()}; - publishFile(store, manifestPath, "manifest-1"); - publishFile(store, lockPath, "lock-1"); - } - given("a publication committed before a crash whose manifest replacement is now blocked", [&] { - require(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); - { - // Commit a second publication, then obstruct its first target. - developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { - if (name == "after-journal") - throw developer::InjectedFault{"crash"}; - }}; - requireThrows([&] { publishPair(store, "manifest-3", "lock-3", store.state(pair)); }); - } - std::filesystem::remove(project.path() / manifestPath); - std::filesystem::create_directories(project.path() / manifestPath / "obstacle"); - when("the project is opened", [&] { - developer::Store store{project.path()}; - then("it opens, reports the failure, refuses to read a state and keeps the journal", [&] { - require(store.recoveryFailure().has_value()); - requireThrows([&] { store.state(pair); }); - require(journalsRemain(journal)); - require(read(store, lockPath) == "lock-2"); - }); - andWhen("the obstacle is removed", [&] { - std::filesystem::remove_all(project.path() / manifestPath); - then("the next state completes the publication", [&] { - store.state(pair); - require(!store.recoveryFailure().has_value()); - require(projectState(store) == "manifest-3|lock-3"); + given("leftovers of a publication that never reached its commit point", [&] { + const auto journal = project.path() / ".webfront/developer/journal"; + std::filesystem::create_directories(journal / "7.d"); + std::ofstream{journal / "7.d" / "0"} << "orphan"; + std::ofstream{journal / "7.tmp"} << "webfront-journal 1\nwebfront.project.json\n0\n"; + std::ofstream{journal / "8.journal"} << "webfront-journal 1\nwebfront.project.json\n0\n"; + when("the project is opened", [&] { + developer::Store store{project.path()}; + then("they are abandoned and the project keeps its files", [&] { require(!journalsRemain(journal)); + require(projectState(store) == "manifest-1|lock-1"); }); }); }); - }); - given("a replacement failing during the publication", [&] { - bool failOnce = true; - developer::Store store{project.path(), developer::defaultAbandonedAfter, [&failOnce](std::string_view name) { - if (name == "replacement-1" && std::exchange(failOnce, false)) - throw std::runtime_error("target locked"); - }}; - when("the group is published", [&] { - then("the caller learns that the change is committed but not applied, and the next state applies it", [&] { - requireThrows([&] { publishPair(store, "manifest-2", "lock-2", store.state(pair)); }); - require(store.recoveryFailure().has_value()); - store.state(pair); - require(projectState(store) == "manifest-2|lock-2"); - require(!journalsRemain(journal)); - }); - }); - }); - given("a failure before the commit point", [&] { - developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { - if (name == "before-journal") - throw std::runtime_error("disk full"); - }}; - const auto first = store.begin(manifestPath, false); - const auto second = store.begin(lockPath, false); - store.write(first, "output", 0, bytes("manifest-2")); - store.write(second, "output", 0, bytes("lock-2")); - requireThrows([&] { store.commitGroup({first, second}, pair, store.state(pair)); }, equals("disk full")); - then("the staged files are returned to their transactions, which still publish", [&] { - require(projectState(store) == "manifest-1|lock-1"); - require(!journalsRemain(journal)); - store.commit(first); - store.commit(second); - require(projectState(store) == "manifest-2|lock-2"); - }); - }); -}}; + }}; + +const Scenario committedPublication{"A committed publication that cannot be completed does not prevent opening the project", [] { + TemporaryDirectory project; + const auto journal = project.path() / ".webfront/developer/journal"; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + given("a publication committed before a crash whose manifest replacement is now blocked", [&] { + require(crashAt("after-journal", project.path()) == "manifest-2|lock-2"); + { + // Commit a second publication, then obstruct its first target. + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "after-journal") + throw developer::InjectedFault{"crash"}; + }}; + requireThrows([&] { + publishPair(store, "manifest-3", "lock-3", store.state(pair)); + }); + } + std::filesystem::remove(project.path() / manifestPath); + std::filesystem::create_directories(project.path() / manifestPath / "obstacle"); + when("the project is opened", [&] { + developer::Store store{project.path()}; + then("it opens, reports the failure, refuses to read a state and keeps the journal", [&] { + require(store.recoveryFailure().has_value()); + requireThrows([&] { + store.state(pair); + }); + require(journalsRemain(journal)); + require(read(store, lockPath) == "lock-2"); + }); + andWhen("the obstacle is removed", [&] { + std::filesystem::remove_all(project.path() / manifestPath); + then("the next state completes the publication", [&] { + store.state(pair); + require(!store.recoveryFailure().has_value()); + require(projectState(store) == "manifest-3|lock-3"); + require(!journalsRemain(journal)); + }); + }); + }); + }); + given("a replacement failing during the publication", [&] { + bool failOnce = true; + developer::Store store{project.path(), developer::defaultAbandonedAfter, [&failOnce](std::string_view name) { + if (name == "replacement-1" && std::exchange(failOnce, false)) + throw std::runtime_error("target locked"); + }}; + when("the group is published", [&] { + then("the caller learns that the change is committed but not applied, and the next state applies it", [&] { + requireThrows([&] { + publishPair(store, "manifest-2", "lock-2", store.state(pair)); + }); + require(store.recoveryFailure().has_value()); + store.state(pair); + require(projectState(store) == "manifest-2|lock-2"); + require(!journalsRemain(journal)); + }); + }); + }); + given("a failure before the commit point", [&] { + developer::Store store{project.path(), developer::defaultAbandonedAfter, [](std::string_view name) { + if (name == "before-journal") + throw std::runtime_error("disk full"); + }}; + const auto first = store.begin(manifestPath, false); + const auto second = store.begin(lockPath, false); + store.write(first, "output", 0, bytes("manifest-2")); + store.write(second, "output", 0, bytes("lock-2")); + requireThrows( + [&] { + store.commitGroup({first, second}, pair, store.state(pair)); + }, + equals("disk full")); + then("the staged files are returned to their transactions, which still publish", [&] { + require(projectState(store) == "manifest-1|lock-1"); + require(!journalsRemain(journal)); + store.commit(first); + store.commit(second); + require(projectState(store) == "manifest-2|lock-2"); + }); + }); + }}; const Scenario publicationPrepared{"A publication prepared from stale state is refused", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - publishFile(store, manifestPath, "manifest-1"); - publishFile(store, lockPath, "lock-1"); - given("two browsers reading the same state", [&] { - const auto firstBrowser = store.state(pair); - const auto secondBrowser = store.state(pair); - require(firstBrowser == secondBrowser); - when("the first publishes, then the second does with what it read", [&] { - publishPair(store, "manifest-a", "lock-a", firstBrowser); - then("the second is refused and nothing is lost", [&] { - requireThrows([&] { publishPair(store, "manifest-b", "lock-b", secondBrowser); }, contains("changed since it was read")); - require(projectState(store) == "manifest-a|lock-a"); - }); - andThen("it succeeds after reading the new state again", [&] { - publishPair(store, "manifest-ab", "lock-ab", store.state(pair)); - require(projectState(store) == "manifest-ab|lock-ab"); - }); - }); - when("a file changes outside the store", [&] { - publishFile(store, lockPath, "lock-c"); - then("the state differs and the group is refused", [&] { - require(store.state(pair) != firstBrowser); - requireThrows([&] { publishPair(store, "manifest-b", "lock-b", firstBrowser); }); - }); - }); - }); - given("a missing lock", [&] { - std::filesystem::remove(project.path() / lockPath); - then("its absence is part of the state", [&] { - const auto absent = store.state(pair); - publishFile(store, lockPath, ""); - require(store.state(pair) != absent); - }); - }); - given("malformed groups", [&] { - const auto first = store.begin(manifestPath, false); - store.write(first, "output", 0, bytes("x")); - then("they are refused without changing the project", [&] { - requireThrows([&] { store.commitGroup({}, pair, store.state(pair)); }); - requireThrows([&] { store.commitGroup({first, first}, pair, store.state(pair)); }); - requireThrows([&] { store.commitGroup({first}, {lockPath}, store.state({lockPath})); }); - require(projectState(store) == "manifest-1|lock-1"); - store.abort(first); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + given("two browsers reading the same state", [&] { + const auto firstBrowser = store.state(pair); + const auto secondBrowser = store.state(pair); + require(firstBrowser == secondBrowser); + when("the first publishes, then the second does with what it read", [&] { + publishPair(store, "manifest-a", "lock-a", firstBrowser); + then("the second is refused and nothing is lost", [&] { + requireThrows( + [&] { + publishPair(store, "manifest-b", "lock-b", secondBrowser); + }, + contains("changed since it was read")); + require(projectState(store) == "manifest-a|lock-a"); + }); + andThen("it succeeds after reading the new state again", [&] { + publishPair(store, "manifest-ab", "lock-ab", store.state(pair)); + require(projectState(store) == "manifest-ab|lock-ab"); + }); + }); + when("a file changes outside the store", [&] { + publishFile(store, lockPath, "lock-c"); + then("the state differs and the group is refused", [&] { + require(store.state(pair) != firstBrowser); + requireThrows([&] { + publishPair(store, "manifest-b", "lock-b", firstBrowser); + }); + }); + }); + }); + given("a missing lock", [&] { + std::filesystem::remove(project.path() / lockPath); + then("its absence is part of the state", [&] { + const auto absent = store.state(pair); + publishFile(store, lockPath, ""); + require(store.state(pair) != absent); + }); + }); + given("malformed groups", [&] { + const auto first = store.begin(manifestPath, false); + store.write(first, "output", 0, bytes("x")); + then("they are refused without changing the project", [&] { + requireThrows([&] { + store.commitGroup({}, pair, store.state(pair)); + }); + requireThrows([&] { + store.commitGroup({first, first}, pair, store.state(pair)); + }); + requireThrows([&] { + store.commitGroup({first}, {lockPath}, store.state({lockPath})); + }); + require(projectState(store) == "manifest-1|lock-1"); + store.abort(first); + }); + }); + }}; -const Scenario newDirectories{"New directories are durable once their parents are synchronized", [] { - TemporaryDirectory project; - const auto root = std::filesystem::canonical(project.path()); - given("a project without the journal directory", [&] { - std::vector synced; - when("the directories are created", [&] { - developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", - [&](const std::filesystem::path& directory) { - // The directory just created must exist when its parent is synchronized. - require(std::filesystem::exists(directory / (synced.empty() ? ".webfront" : synced.size() == 1 ? "developer" : "journal"))); - synced.push_back(directory); - }); - then("each created directory has its parent synchronized, outermost first", [&] { - require(synced == std::vector{root, root / ".webfront", root / ".webfront/developer"}); +const Scenario newDirectories{ + "New directories are durable once their parents are synchronized", + [] { + TemporaryDirectory project; + const auto root = std::filesystem::canonical(project.path()); + given("a project without the journal directory", [&] { + std::vector synced; + when("the directories are created", [&] { + developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", [&](const std::filesystem::path& directory) { + // The directory just created must exist when its parent is synchronized. + require(std::filesystem::exists(directory / (synced.empty() ? ".webfront" : synced.size() == 1 ? "developer" : "journal"))); + synced.push_back(directory); + }); + then("each created directory has its parent synchronized, outermost first", [&] { + require(synced == std::vector{root, root / ".webfront", root / ".webfront/developer"}); + }); }); - }); - when("some of them already exist", [&] { - std::filesystem::create_directories(root / ".webfront/developer"); - developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", - [&](const std::filesystem::path& directory) { synced.push_back(directory); }); - then("only the missing one is created and synchronized", [&] { - require(synced == std::vector{root / ".webfront/developer"}); + when("some of them already exist", [&] { + std::filesystem::create_directories(root / ".webfront/developer"); + developer::createDirectoriesDurably(root, root / ".webfront/developer/journal", [&](const std::filesystem::path& directory) { + synced.push_back(directory); + }); + then("only the missing one is created and synchronized", [&] { + require(synced == std::vector{root / ".webfront/developer"}); + }); }); }); - }); -}}; + }}; namespace { // Holds a thread at a step until opened. Opening is idempotent and also happens on destruction, so a failed @@ -797,15 +919,17 @@ namespace { class Gate { public: void open() { - std::call_once(once, [this] { opened.set_value(); }); + std::call_once(once, [this] { + opened.set_value(); + }); } void wait() const { future.wait(); } private: - std::once_flag once; - std::promise opened; + std::once_flag once; + std::promise opened; std::shared_future future{opened.get_future().share()}; }; struct OpenOnExit { @@ -817,287 +941,324 @@ struct OpenOnExit { } // namespace const Scenario secondOpener{"A second opener of the project waits for a publication in progress instead of abandoning it", [] { - TemporaryDirectory project; - { - developer::Store store{project.path()}; - publishFile(store, manifestPath, "manifest-1"); - publishFile(store, lockPath, "lock-1"); - } - given("a publication stopped between staging its files and writing its journal", [&] { - Gate reached; - Gate release; - developer::Store publisher{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { - if (name == "before-journal") { - reached.open(); - release.wait(); - } - }}; - const auto before = publisher.state(pair); - auto publication = std::async(std::launch::async, [&] { - try { - publishPair(publisher, "manifest-2", "lock-2", before); - } catch (...) { - reached.open(); // do not leave the test waiting for a step that is never reached - throw; + TemporaryDirectory project; + { + developer::Store store{project.path()}; + publishFile(store, manifestPath, "manifest-1"); + publishFile(store, lockPath, "lock-1"); + } + given("a publication stopped between staging its files and writing its journal", [&] { + Gate reached; + Gate release; + developer::Store publisher{project.path(), developer::defaultAbandonedAfter, [&](std::string_view name) { + if (name == "before-journal") { + reached.open(); + release.wait(); + } + }}; + const auto before = publisher.state(pair); + auto publication = std::async(std::launch::async, [&] { + try { + publishPair(publisher, "manifest-2", "lock-2", before); + } catch (...) { + reached.open(); // do not leave the test waiting for a step that is never reached + throw; + } + }); + const OpenOnExit unblock{release}; + reached.wait(); + when("another store, as another process would, opens the project meanwhile", [&] { + auto opening = std::async(std::launch::async, [&] { + developer::Store other{project.path()}; + return projectState(other); + }); + const auto waiting = opening.wait_for(std::chrono::milliseconds(300)); + release.open(); + publication.get(); + then("it waited, then sees the completed publication", [&] { + check(waiting == std::future_status::timeout); + require(opening.get() == "manifest-2|lock-2"); + }); + }); + when("another store tries to publish from the state read before the first publication", [&] { + // The refusal is read in its own thread: an exception object shared across threads by a future is + // reported as a race by ThreadSanitizer, whose runtime does not see libc++abi's reference counting. + auto competing = std::async(std::launch::async, [&]() -> std::string { + try { + developer::Store other{project.path()}; + publishPair(other, "manifest-3", "lock-3", before); + return "published"; + } catch (const std::exception& error) { + return error.what(); + } + }); + const auto waiting = competing.wait_for(std::chrono::milliseconds(300)); + release.open(); + publication.get(); + then("its precondition is checked after the first publication, which wins", [&] { + check(waiting == std::future_status::timeout); + require(competing.get(), contains("changed since it was read")); + require(projectState(publisher) == "manifest-2|lock-2"); + }); + }); + }); + }}; + +const Scenario sha256Vectors{ + "SHA-256 matches the FIPS 180-4 vectors at every padding boundary, fed whole or in pieces", + [] { + using utils::Sha256; + const auto digest = [](std::string_view text, std::size_t piece) { + Sha256 hasher; + for (std::size_t offset = 0; offset < text.size(); offset += piece) + hasher.update(text.substr(offset, piece)); + return Sha256::hex(hasher.finish()); + }; + const std::string million(1000000, 'a'); + for (const auto& [text, expected] : std::initializer_list>{ + {"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + {"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, + {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}, + {std::string_view(million).substr(0, 55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"}, + {std::string_view(million).substr(0, 56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"}, + {std::string_view(million).substr(0, 64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"}, + {million, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"} + }) + for (const std::size_t piece : {std::size_t{1}, std::size_t{63}, std::size_t{4096}, std::max(text.size(), 1)}) { + auto scope = info("length ", text.size(), ", pieces of ", piece); + require(digest(text, piece) == expected); } - }); - const OpenOnExit unblock{release}; - reached.wait(); - when("another store, as another process would, opens the project meanwhile", [&] { - auto opening = std::async(std::launch::async, [&] { developer::Store other{project.path()}; return projectState(other); }); - const auto waiting = opening.wait_for(std::chrono::milliseconds(300)); - release.open(); - publication.get(); - then("it waited, then sees the completed publication", [&] { - check(waiting == std::future_status::timeout); - require(opening.get() == "manifest-2|lock-2"); + }}; + +const Scenario projectDirectoryDigested{ + "A project directory is digested whole, its links marked and never followed", + [] { + TemporaryDirectory project; + TemporaryDirectory outside; + developer::Store store{project.path()}; + publishFile(store, "ui/main.tsx", "main"); + publishFile(store, "ui/parts/a.ts", "a"); + publishFile(store, "ui/b.css", "b"); + const auto text = [&](std::string path) { + const auto bytes = store.digests(std::move(path)); + return std::string(bytes.begin(), bytes.end()); + }; + const std::string expected = R"({"b.css":"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d",)" + R"("main.tsx":"0d6e4079e36703ebd37c00722f5891d28b0e2811dc114b129215123adcce3605",)" + R"("parts/a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"})"; + then("every file below the directory, nested ones included, maps its relative path to its SHA-256", [&] { + require(text("ui") == expected); + require(text("ui/parts") == R"({"a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"})"); + }); + then("a missing directory, a file or a path leaving the project is refused", [&] { + requireThrows( + [&] { + store.digests("missing"); + }, + contains("Cannot list project directory")); + requireThrows( + [&] { + store.digests("ui/main.tsx"); + }, + contains("Cannot list project directory")); + requireThrows([&] { + store.digests("../outside"); }); }); - when("another store tries to publish from the state read before the first publication", [&] { - // The refusal is read in its own thread: an exception object shared across threads by a future is - // reported as a race by ThreadSanitizer, whose runtime does not see libc++abi's reference counting. - auto competing = std::async(std::launch::async, [&]() -> std::string { - try { - developer::Store other{project.path()}; - publishPair(other, "manifest-3", "lock-3", before); - return "published"; - } catch (const std::exception& error) { - return error.what(); - } - }); - const auto waiting = competing.wait_for(std::chrono::milliseconds(300)); - release.open(); - publication.get(); - then("its precondition is checked after the first publication, which wins", [&] { - check(waiting == std::future_status::timeout); - require(competing.get(), contains("changed since it was read")); - require(projectState(publisher) == "manifest-2|lock-2"); - }); + given("an extra link to a file of the project, a link outside it and one back to the directory itself", [&] { + std::ofstream(outside.path() / "secret.txt") << "secret"; + std::error_code fileError, outError, loopError; + std::filesystem::create_symlink(project.path() / "ui" / "main.tsx", project.path() / "ui" / "alias.txt", fileError); + std::filesystem::create_directory_symlink(outside.path(), project.path() / "ui" / "escape", outError); + std::filesystem::create_directory_symlink(project.path() / "ui", project.path() / "ui" / "parts" / "loop", loopError); + if (!fileError && !outError && !loopError) { + then("each is a difference that no digest equals, and none is followed", [&] { + require(text("ui") + == R"({"alias.txt":"link","b.css":"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d",)" + R"("escape":"link","main.tsx":"0d6e4079e36703ebd37c00722f5891d28b0e2811dc114b129215123adcce3605",)" + R"("parts/a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb","parts/loop":"link"})"); + }); + } }); - }); -}}; - -const Scenario sha256Vectors{"SHA-256 matches the FIPS 180-4 vectors at every padding boundary, fed whole or in pieces", [] { - using utils::Sha256; - const auto digest = [](std::string_view text, std::size_t piece) { - Sha256 hasher; - for (std::size_t offset = 0; offset < text.size(); offset += piece) - hasher.update(text.substr(offset, piece)); - return Sha256::hex(hasher.finish()); - }; - const std::string million(1000000, 'a'); - for (const auto& [text, expected] : std::initializer_list>{ - {"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, - {"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, - {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}, - {std::string_view(million).substr(0, 55), "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"}, - {std::string_view(million).substr(0, 56), "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"}, - {std::string_view(million).substr(0, 64), "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"}, - {million, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"}}) - for (const std::size_t piece : {std::size_t{1}, std::size_t{63}, std::size_t{4096}, std::max(text.size(), 1)}) { - auto scope = info("length ", text.size(), ", pieces of ", piece); - require(digest(text, piece) == expected); - } -}}; - -const Scenario projectDirectoryDigested{"A project directory is digested whole, its links marked and never followed", [] { - TemporaryDirectory project; - TemporaryDirectory outside; - developer::Store store{project.path()}; - publishFile(store, "ui/main.tsx", "main"); - publishFile(store, "ui/parts/a.ts", "a"); - publishFile(store, "ui/b.css", "b"); - const auto text = [&](std::string path) { - const auto bytes = store.digests(std::move(path)); - return std::string(bytes.begin(), bytes.end()); - }; - const std::string expected = R"({"b.css":"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d",)" - R"("main.tsx":"0d6e4079e36703ebd37c00722f5891d28b0e2811dc114b129215123adcce3605",)" - R"("parts/a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"})"; - then("every file below the directory, nested ones included, maps its relative path to its SHA-256", [&] { - require(text("ui") == expected); - require(text("ui/parts") == R"({"a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"})"); - }); - then("a missing directory, a file or a path leaving the project is refused", [&] { - requireThrows([&] { store.digests("missing"); }, contains("Cannot list project directory")); - requireThrows([&] { store.digests("ui/main.tsx"); }, contains("Cannot list project directory")); - requireThrows([&] { store.digests("../outside"); }); - }); - given("an extra link to a file of the project, a link outside it and one back to the directory itself", [&] { - std::ofstream(outside.path() / "secret.txt") << "secret"; - std::error_code fileError, outError, loopError; - std::filesystem::create_symlink(project.path() / "ui" / "main.tsx", project.path() / "ui" / "alias.txt", fileError); - std::filesystem::create_directory_symlink(outside.path(), project.path() / "ui" / "escape", outError); - std::filesystem::create_directory_symlink(project.path() / "ui", project.path() / "ui" / "parts" / "loop", loopError); - if (!fileError && !outError && !loopError) { - then("each is a difference that no digest equals, and none is followed", [&] { - require(text("ui") == R"({"alias.txt":"link","b.css":"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d",)" - R"("escape":"link","main.tsx":"0d6e4079e36703ebd37c00722f5891d28b0e2811dc114b129215123adcce3605",)" - R"("parts/a.ts":"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb","parts/loop":"link"})"); - }); - } - }); -}}; + }}; const Scenario projectDirectoryListed{"A project directory is listed without leaving the project", [] { - TemporaryDirectory project; - TemporaryDirectory outside; - developer::Store store{project.path()}; - publishFile(store, "ui/main.tsx", "main"); - publishFile(store, "ui/parts/a.ts", "a"); - publishFile(store, "ui/b.css", "b"); - const auto text = [&](std::string path) { - const auto bytes = store.list(std::move(path)); - return std::string(bytes.begin(), bytes.end()); - }; - given("files and a subdirectory", [&] { - then("names are a sorted JSON array, and directories end with a slash", [&] { - require(text("ui") == R"(["b.css","main.tsx","parts/"])"); - require(text("ui/parts") == R"(["a.ts"])"); - require(text(""), contains("ui/")); - }); - }); - given("a link to a directory outside the project", [&] { - std::error_code error; - std::filesystem::create_directory_symlink(outside.path(), project.path() / "ui" / "escape", error); - if (!error) { - then("it is omitted, and listing through it is refused", [&] { - require(text("ui") == R"(["b.css","main.tsx","parts/"])"); - requireThrows([&] { store.list("ui/escape"); }); - }); - } - }); - given("a link whose target cannot be resolved, because it points to itself", [&] { - std::error_code error; - std::filesystem::create_symlink(project.path() / "ui" / "loop", project.path() / "ui" / "loop", error); - if (!error) { - then("only that entry is omitted", [&] { - require(text("ui") == R"(["b.css","main.tsx","parts/"])"); - }); - } - }); + TemporaryDirectory project; + TemporaryDirectory outside; + developer::Store store{project.path()}; + publishFile(store, "ui/main.tsx", "main"); + publishFile(store, "ui/parts/a.ts", "a"); + publishFile(store, "ui/b.css", "b"); + const auto text = [&](std::string path) { + const auto bytes = store.list(std::move(path)); + return std::string(bytes.begin(), bytes.end()); + }; + given("files and a subdirectory", [&] { + then("names are a sorted JSON array, and directories end with a slash", [&] { + require(text("ui") == R"(["b.css","main.tsx","parts/"])"); + require(text("ui/parts") == R"(["a.ts"])"); + require(text(""), contains("ui/")); + }); + }); + given("a link to a directory outside the project", [&] { + std::error_code error; + std::filesystem::create_directory_symlink(outside.path(), project.path() / "ui" / "escape", error); + if (!error) { + then("it is omitted, and listing through it is refused", [&] { + require(text("ui") == R"(["b.css","main.tsx","parts/"])"); + requireThrows([&] { + store.list("ui/escape"); + }); + }); + } + }); + given("a link whose target cannot be resolved, because it points to itself", [&] { + std::error_code error; + std::filesystem::create_symlink(project.path() / "ui" / "loop", project.path() / "ui" / "loop", error); + if (!error) { + then("only that entry is omitted", [&] { + require(text("ui") == R"(["b.css","main.tsx","parts/"])"); + }); + } + }); #ifndef _WIN32 - given("a file whose name contains a line break", [&] { - std::ofstream(project.path() / "ui" / "a\nb").put('x'); - then("it is one escaped entry, not two", [&] { - require(text("ui") == R"(["a\u000ab","b.css","main.tsx","parts/"])"); - }); - }); + given("a file whose name contains a line break", [&] { + std::ofstream(project.path() / "ui" / "a\nb").put('x'); + then("it is one escaped entry, not two", [&] { + require(text("ui") == R"(["a\u000ab","b.css","main.tsx","parts/"])"); + }); + }); #endif - given("a missing directory, a file or a path escaping the project", [&] { - then("listing fails", [&] { - requireThrows([&] { store.list("missing"); }, contains("Cannot list project directory")); - requireThrows([&] { store.list("ui/main.tsx"); }, contains("Cannot list project directory")); - requireThrows([&] { store.list("../outside"); }); - }); - }); -}}; + given("a missing directory, a file or a path escaping the project", [&] { + then("listing fails", [&] { + requireThrows( + [&] { + store.list("missing"); + }, + contains("Cannot list project directory")); + requireThrows( + [&] { + store.list("ui/main.tsx"); + }, + contains("Cannot list project directory")); + requireThrows([&] { + store.list("../outside"); + }); + }); + }); + }}; const Scenario projectPaths{"Project paths beyond the 260 characters of Windows are published, grouped and read like any other", [] { - TemporaryDirectory project; - developer::Store store{project.path()}; - std::string directory = "deep"; // absolute paths below it exceed MAX_PATH; none of its directories exists yet - while (project.path().native().size() + directory.size() < 300) - directory += "/" + std::string(40, 'd'); - when("a file is published there", [&] { - const auto destination = directory + "/file.txt"; - publishFile(store, destination, "long"); - then("it can be read back and replaced", [&] { - require(read(store, destination) == "long"); - publishFile(store, destination, "longer"); - require(read(store, destination) == "longer"); - }); - then("a path escaping the project is still refused", [&] { - requireThrows([&] { store.read(directory + "/../../../../../../../../../../../../../../../../../outside", 0); }); - }); - }); - when("two files are published there as one group", [&] { - const std::vector paths{directory + "/a.txt", directory + "/b.txt"}; - publishGroup(store, paths, {"one", "two"}, store.state(paths)); - then("both are readable and no journal remains", [&] { - require(read(store, paths[0]) == "one"); - require(read(store, paths[1]) == "two"); - require(!journalsRemain(project.path() / ".webfront/developer/journal")); - }); - }); -}}; + TemporaryDirectory project; + developer::Store store{project.path()}; + std::string directory = "deep"; // absolute paths below it exceed MAX_PATH; none of its directories exists yet + while (project.path().native().size() + directory.size() < 300) + directory += "/" + std::string(40, 'd'); + when("a file is published there", [&] { + const auto destination = directory + "/file.txt"; + publishFile(store, destination, "long"); + then("it can be read back and replaced", [&] { + require(read(store, destination) == "long"); + publishFile(store, destination, "longer"); + require(read(store, destination) == "longer"); + }); + then("a path escaping the project is still refused", [&] { + requireThrows([&] { + store.read(directory + "/../../../../../../../../../../../../../../../../../outside", 0); + }); + }); + }); + when("two files are published there as one group", [&] { + const std::vector paths{directory + "/a.txt", directory + "/b.txt"}; + publishGroup(store, paths, {"one", "two"}, store.state(paths)); + then("both are readable and no journal remains", [&] { + require(read(store, paths[0]) == "one"); + require(read(store, paths[1]) == "two"); + require(!journalsRemain(project.path() / ".webfront/developer/journal")); + }); + }); + }}; const Scenario projectWhose{"A project whose own directory exceeds the 260 characters of Windows can be opened", [] { - TemporaryDirectory outer; - auto root = outer.path(); - while (root.native().size() < 302) - root /= std::string(40, 'r'); - std::filesystem::create_directories(developer::extendedPath(root)); - given("a store on that directory", [&] { - developer::Store store{root}; - when("a file is published and a group is committed", [&] { - publishFile(store, "file.txt", "root"); - const std::vector paths{"sub/a.txt", "sub/b.txt"}; - publishGroup(store, paths, {"one", "two"}, store.state(paths)); - then("everything is readable and the project stays confined", [&] { - require(read(store, "file.txt") == "root"); - require(read(store, "sub/b.txt") == "two"); - requireThrows([&] { store.read("../outside", 0); }); - }); - }); - }); - given("a developer filesystem on that directory", [&] { - then("it opens", [&] { - requireNothrow([&] { fs::DeveloperFS{root}; }); - }); - }); -}}; + TemporaryDirectory outer; + auto root = outer.path(); + while (root.native().size() < 302) + root /= std::string(40, 'r'); + std::filesystem::create_directories(developer::extendedPath(root)); + given("a store on that directory", [&] { + developer::Store store{root}; + when("a file is published and a group is committed", [&] { + publishFile(store, "file.txt", "root"); + const std::vector paths{"sub/a.txt", "sub/b.txt"}; + publishGroup(store, paths, {"one", "two"}, store.state(paths)); + then("everything is readable and the project stays confined", [&] { + require(read(store, "file.txt") == "root"); + require(read(store, "sub/b.txt") == "two"); + requireThrows([&] { + store.read("../outside", 0); + }); + }); + }); + }); + given("a developer filesystem on that directory", [&] { + then("it opens", [&] { + requireNothrow([&] { + fs::DeveloperFS{root}; + }); + }); + }); + }}; #ifdef _WIN32 const Scenario faultingMemory{"Published files are copied from memory that may fault, reporting a failed read by value", [] { - given("a committed page, a page that cannot be read and a guard page", [&] { - SYSTEM_INFO info{}; - ::GetSystemInfo(&info); - const auto page = static_cast(info.dwPageSize); - auto* region = static_cast(::VirtualAlloc(nullptr, 3 * page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); - if (region == nullptr) - throw std::runtime_error{"VirtualAlloc failed"}; - struct Free { - char* region; - ~Free() { - ::VirtualFree(region, 0, MEM_RELEASE); - } - } free{region}; - std::memset(region, 'x', page); - DWORD previous = 0; - require(::VirtualProtect(region + page, page, PAGE_NOACCESS, &previous) != 0); - require(::VirtualProtect(region + 2 * page, page, PAGE_READWRITE | PAGE_GUARD, &previous) != 0); - std::vector out(2 * page); - then("a readable range is copied", [&] { - check(fs::detail::copyReadable(out.data(), region, page)); - check(out[0] == 'x'); - check(out[page - 1] == 'x'); - }); - then("a range that reaches an unreadable page fails without an exception", [&] { - check(!fs::detail::copyReadable(out.data(), region, 2 * page)); - check(!fs::detail::copyReadable(out.data(), region + page, 1)); - }); - then("a guard page does not raise a structured exception either", [&] { - check(!fs::detail::copyReadable(out.data(), region + 2 * page, 1)); - }); - }); - given("a published file of 200 kB", [&] { - TemporaryDirectory project; - developer::Store store{project.path()}; - const auto id = store.begin(".webfront/developer/preview", true); - const std::string content(200000, 'p'); - store.write(id, "big.bin", 0, bytes(content)); - store.commit(id); - fs::DeveloperFS filesystem{project.path()}; - then("it is read whole through its mapped windows, whatever the block size", [&] { - auto file = filesystem.open("/webfront/developer/preview/big.bin"); - require(file.has_value()); - std::string got; - std::vector block(70001); - for (std::size_t n; (n = file->read(block)) != 0;) - got.append(block.data(), n); - check(got == content); - }); - }); -}}; + given("a committed page, a page that cannot be read and a guard page", [&] { + SYSTEM_INFO info{}; + ::GetSystemInfo(&info); + const auto page = static_cast(info.dwPageSize); + auto* region = static_cast(::VirtualAlloc(nullptr, 3 * page, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (region == nullptr) + throw std::runtime_error{"VirtualAlloc failed"}; + struct Free { + char* region; + ~Free() { + ::VirtualFree(region, 0, MEM_RELEASE); + } + } free{region}; + std::memset(region, 'x', page); + DWORD previous = 0; + require(::VirtualProtect(region + page, page, PAGE_NOACCESS, &previous) != 0); + require(::VirtualProtect(region + 2 * page, page, PAGE_READWRITE | PAGE_GUARD, &previous) != 0); + std::vector out(2 * page); + then("a readable range is copied", [&] { + check(fs::detail::copyReadable(out.data(), region, page)); + check(out[0] == 'x'); + check(out[page - 1] == 'x'); + }); + then("a range that reaches an unreadable page fails without an exception", [&] { + check(!fs::detail::copyReadable(out.data(), region, 2 * page)); + check(!fs::detail::copyReadable(out.data(), region + page, 1)); + }); + then("a guard page does not raise a structured exception either", [&] { + check(!fs::detail::copyReadable(out.data(), region + 2 * page, 1)); + }); + }); + given("a published file of 200 kB", [&] { + TemporaryDirectory project; + developer::Store store{project.path()}; + const auto id = store.begin(".webfront/developer/preview", true); + const std::string content(200000, 'p'); + store.write(id, "big.bin", 0, bytes(content)); + store.commit(id); + fs::DeveloperFS filesystem{project.path()}; + then("it is read whole through its mapped windows, whatever the block size", [&] { + auto file = filesystem.open("/webfront/developer/preview/big.bin"); + require(file.has_value()); + std::string got; + std::vector block(70001); + for (std::size_t n; (n = file->read(block)) != 0;) + got.append(block.data(), n); + check(got == content); + }); + }); + }}; #endif diff --git a/test/unit/DomBatchTests.cpp b/test/unit/DomBatchTests.cpp index c0716523..9fa8a9f0 100644 --- a/test/unit/DomBatchTests.cpp +++ b/test/unit/DomBatchTests.cpp @@ -18,136 +18,164 @@ std::vector packet(std::initializer_list payload) { } // namespace const Scenario dOMCommands{"DOM commands have a portable golden encoding and round trip every operation", [] { - given("A little-endian correlation id and interned UTF-8 names", [&] { - DomBatch batch(0x12345678); - batch.add({DomOp::name, 0, 0, 0, "div"}); - batch.add({DomOp::element, 128, 0}); - then("The exact bytes use canonical LEB128 independently of host endianness", [&] { - const auto expected = packet({1, 0, 3, 'd', 'i', 'v', 2, 0x80, 1, 0}); - require(std::ranges::equal(batch.data(), expected)); - require(batch.header().size() == 6); - require(batch.payload().size() == expected.size() - 6); - }); - }); - given("Every numbered operation, uint32 boundaries, and multi-byte UTF-8", [&] { - const std::vector expected{ - {DomOp::name, 0, 0, 0, "\xef\xbb\xbf"}, - {DomOp::element, 0xffffffff, 127}, - {DomOp::text, 128, 0, 0, "été 🌍"}, - {DomOp::attribute, 1, 2, 0, "title"}, - {DomOp::unsetAttribute, 1, 2}, - {DomOp::property, 1, 2, 0, "false"}, - {DomOp::setText, 128, 0, 0, ""}, - {DomOp::append, 1, 128}, - {DomOp::insertBefore, 1, 2, 128}, - {DomOp::remove, 2}, - {DomOp::listen, 1, 3, 3}, - {DomOp::unlisten, 1, 3}, - {DomOp::mount, 1, 4} - }; - DomBatch batch(0x12345678); - for (const auto& op : expected) - batch.add(op); - then("Decoding recovers all fields without borrowing the input", [&] { - const auto [id, decoded] = DomBatch::decode(batch.data()); - require(id == 0x12345678); - require(decoded == expected); - }); - }); -}}; + given("A little-endian correlation id and interned UTF-8 names", [&] { + DomBatch batch(0x12345678); + batch.add({DomOp::name, 0, 0, 0, "div"}); + batch.add({DomOp::element, 128, 0}); + then("The exact bytes use canonical LEB128 independently of host endianness", [&] { + const auto expected = packet({1, 0, 3, 'd', 'i', 'v', 2, 0x80, 1, 0}); + require(std::ranges::equal(batch.data(), expected)); + require(batch.header().size() == 6); + require(batch.payload().size() == expected.size() - 6); + }); + }); + given("Every numbered operation, uint32 boundaries, and multi-byte UTF-8", [&] { + const std::vector expected{ + {DomOp::name, 0, 0, 0, "\xef\xbb\xbf"}, + {DomOp::element, 0xffffffff, 127}, + {DomOp::text, 128, 0, 0, "été 🌍"}, + {DomOp::attribute, 1, 2, 0, "title"}, + {DomOp::unsetAttribute, 1, 2}, + {DomOp::property, 1, 2, 0, "false"}, + {DomOp::setText, 128, 0, 0, ""}, + {DomOp::append, 1, 128}, + {DomOp::insertBefore, 1, 2, 128}, + {DomOp::remove, 2}, + {DomOp::listen, 1, 3, 3}, + {DomOp::unlisten, 1, 3}, + {DomOp::mount, 1, 4} + }; + DomBatch batch(0x12345678); + for (const auto& op : expected) + batch.add(op); + then("Decoding recovers all fields without borrowing the input", [&] { + const auto [id, decoded] = DomBatch::decode(batch.data()); + require(id == 0x12345678); + require(decoded == expected); + }); + }); + }}; const Scenario dOMCodecs{"DOM codecs reject malformed input and enforce the complete command budget", [] { - given("Malformed opcodes, varints, strings and listener flags", [&] { - const std::vector> invalid{packet({0}), - packet({14}), - packet({10}), - packet({10, 0x80}), - packet({10, 0x80, 0}), - packet({10, 0xff, 0xff, 0xff, 0xff, 0x10}), - packet({10, 0x80, 0x80, 0x80, 0x80, 0x80, 1}), - packet({3, 1, 3, 'x'}), - packet({3, 1, 2, 0xc0, 0x80}), - packet({3, 1, 3, 0xed, 0xa0, 0x80}), - packet({3, 1, 4, 0xf4, 0x90, 0x80, 0x80}), - packet({3, 1, 1, 0xc2}), - packet({3, 1, 2, 0xc2, 'a'}), - packet({11, 1, 2, 4})}; - then("Each is rejected", [&] { - for (const auto& bytes : invalid) - requireThrows([&] { DomBatch::decode(bytes); }); - auto header = packet({}); - for (std::size_t size = 0; size < 6; ++size) - requireThrows([&] { DomBatch::decode(std::span(header).first(size)); }); - header[0] = std::byte{4}; - requireThrows([&] { DomBatch::decode(header); }); - header[0] = std::byte{5}; - header[1] = std::byte{0}; - requireThrows([&] { DomBatch::decode(header); }); - }); - }); - given("A text operation filling exactly 1 MiB including headers", [&] { - DomBatch batch(1); - batch.add({DomOp::text, 1, 0, 0, std::string(DomBatch::maxBytes - 11, 'x')}); - then("The boundary succeeds, the next operation fails atomically, and the decoder rejects oversized input", [&] { - require(batch.data().size() == DomBatch::maxBytes); - require(DomBatch::decode(batch.data()).second.front().value.size() == DomBatch::maxBytes - 11); - requireThrows([&] { batch.add({DomOp::remove, 1}); }); - require(batch.data().size() == DomBatch::maxBytes); - auto bytes = std::vector(batch.data().begin(), batch.data().end()); - bytes.push_back(std::byte{0}); - requireThrows([&] { DomBatch::decode(bytes); }); - }); - }); - given("An invalid outgoing operation", [&] { - DomBatch batch(1); - then("No prefix is appended", [&] { - requireThrows([&] { batch.add({DomOp::text, 1, 0, 0, std::string("\xc0\x80", 2)}); }); - requireThrows([&] { batch.add({DomOp::listen, 1, 2, 4}); }); - requireThrows([&] { batch.add({static_cast(255), 1}); }); - require(batch.data().size() == DomBatch::headerBytes); - }); - }); -}}; + given("Malformed opcodes, varints, strings and listener flags", [&] { + const std::vector> invalid{packet({0}), + packet({14}), + packet({10}), + packet({10, 0x80}), + packet({10, 0x80, 0}), + packet({10, 0xff, 0xff, 0xff, 0xff, 0x10}), + packet({10, 0x80, 0x80, 0x80, 0x80, 0x80, 1}), + packet({3, 1, 3, 'x'}), + packet({3, 1, 2, 0xc0, 0x80}), + packet({3, 1, 3, 0xed, 0xa0, 0x80}), + packet({3, 1, 4, 0xf4, 0x90, 0x80, 0x80}), + packet({3, 1, 1, 0xc2}), + packet({3, 1, 2, 0xc2, 'a'}), + packet({11, 1, 2, 4})}; + then("Each is rejected", [&] { + for (const auto& bytes : invalid) + requireThrows([&] { + DomBatch::decode(bytes); + }); + auto header = packet({}); + for (std::size_t size = 0; size < 6; ++size) + requireThrows([&] { + DomBatch::decode(std::span(header).first(size)); + }); + header[0] = std::byte{4}; + requireThrows([&] { + DomBatch::decode(header); + }); + header[0] = std::byte{5}; + header[1] = std::byte{0}; + requireThrows([&] { + DomBatch::decode(header); + }); + }); + }); + given("A text operation filling exactly 1 MiB including headers", [&] { + DomBatch batch(1); + batch.add({DomOp::text, 1, 0, 0, std::string(DomBatch::maxBytes - 11, 'x')}); + then("The boundary succeeds, the next operation fails atomically, and the decoder rejects oversized input", [&] { + require(batch.data().size() == DomBatch::maxBytes); + require(DomBatch::decode(batch.data()).second.front().value.size() == DomBatch::maxBytes - 11); + requireThrows([&] { + batch.add({DomOp::remove, 1}); + }); + require(batch.data().size() == DomBatch::maxBytes); + auto bytes = std::vector(batch.data().begin(), batch.data().end()); + bytes.push_back(std::byte{0}); + requireThrows([&] { + DomBatch::decode(bytes); + }); + }); + }); + given("An invalid outgoing operation", [&] { + DomBatch batch(1); + then("No prefix is appended", [&] { + requireThrows([&] { + batch.add({DomOp::text, 1, 0, 0, std::string("\xc0\x80", 2)}); + }); + requireThrows([&] { + batch.add({DomOp::listen, 1, 2, 4}); + }); + requireThrows([&] { + batch.add({static_cast(255), 1}); + }); + require(batch.data().size() == DomBatch::headerBytes); + }); + }); + }}; const Scenario dOMBatch{"DOM batch identifiers and operands are explicit and canonical", [] { - static_assert(!(std::is_default_constructible_v)); - given("the reserved uncorrelated identifier zero", [&] { - then("neither encoder nor decoder accepts it as a real batch", [&] { - requireThrows([&] { DomBatch(0); }); - auto raw = packet({}); - std::fill(raw.begin() + 2, raw.begin() + 6, std::byte{0}); - requireThrows([&] { DomBatch::decode(raw); }); - }); - }); - given("nonzero operands absent from the operation's wire layout", [&] { - DomBatch batch(1); - const std::vector invalid{ - {DomOp::remove, 1, 2}, - {DomOp::text, 1, 0, 3, "text"}, - {DomOp::append, 1, 2, 3}, - {DomOp::listen, 1, 2, 0, "unused"} - }; - then("each encoding fails without appending a prefix", [&] { - for (const auto& op : invalid) - requireThrows([&] { batch.add(op); }); - require(batch.data().size() == DomBatch::headerBytes); - }); - }); -}}; + static_assert(!(std::is_default_constructible_v)); + given("the reserved uncorrelated identifier zero", [&] { + then("neither encoder nor decoder accepts it as a real batch", [&] { + requireThrows([&] { + DomBatch(0); + }); + auto raw = packet({}); + std::fill(raw.begin() + 2, raw.begin() + 6, std::byte{0}); + requireThrows([&] { + DomBatch::decode(raw); + }); + }); + }); + given("nonzero operands absent from the operation's wire layout", [&] { + DomBatch batch(1); + const std::vector invalid{ + {DomOp::remove, 1, 2}, + {DomOp::text, 1, 0, 3, "text"}, + {DomOp::append, 1, 2, 3}, + {DomOp::listen, 1, 2, 0, "unused"} + }; + then("each encoding fails without appending a prefix", [&] { + for (const auto& op : invalid) + requireThrows([&] { + batch.add(op); + }); + require(batch.data().size() == DomBatch::headerBytes); + }); + }); + }}; const Scenario dOMOperation{"DOM operation counts bound owning decoder allocation independently of wire bytes", [] { - given("a batch containing exactly the maximum number of minimum-sized operations", [&] { - DomBatch batch(1); - for (std::size_t i = 0; i < DomBatch::maxOperations; ++i) - batch.add({DomOp::remove, 1}); - then("the exact boundary decodes, and both codecs reject one additional operation", [&] { - require(DomBatch::decode(batch.data()).second.size() == DomBatch::maxOperations); - requireThrows([&] { batch.add({DomOp::remove, 1}); }); - auto raw = std::vector(batch.data().begin(), batch.data().end()); - raw.push_back(std::byte(DomOp::remove)); - raw.push_back(std::byte{1}); - require(raw.size() < DomBatch::maxBytes); - requireThrows([&] { DomBatch::decode(raw); }); - }); - }); -}}; + given("a batch containing exactly the maximum number of minimum-sized operations", [&] { + DomBatch batch(1); + for (std::size_t i = 0; i < DomBatch::maxOperations; ++i) + batch.add({DomOp::remove, 1}); + then("the exact boundary decodes, and both codecs reject one additional operation", [&] { + require(DomBatch::decode(batch.data()).second.size() == DomBatch::maxOperations); + requireThrows([&] { + batch.add({DomOp::remove, 1}); + }); + auto raw = std::vector(batch.data().begin(), batch.data().end()); + raw.push_back(std::byte(DomOp::remove)); + raw.push_back(std::byte{1}); + require(raw.size() < DomBatch::maxBytes); + requireThrows([&] { + DomBatch::decode(raw); + }); + }); + }); + }}; diff --git a/test/unit/DomDocumentTests.cpp b/test/unit/DomDocumentTests.cpp index f27b1603..872203f7 100644 --- a/test/unit/DomDocumentTests.cpp +++ b/test/unit/DomDocumentTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include using namespace webfront::bdd; @@ -14,139 +14,161 @@ struct Browser { } // namespace const Scenario dOMDocuments{"DOM documents batch writes and preserve node identity", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - std::vector sent; - unsigned batches{}, wakes{}; - state->send = [&](const msg::DomBatch& batch) { - ++batches; - sent = msg::DomBatch::decode(batch.data()).second; - }; - state->schedule = [&] { - ++wakes; - }; - given("writes before the interpreter connects", [&] { - auto root = doc.island(); - auto element = doc.element("p"); - auto text = doc.text("été 🌍"); - element.append(text); - root.append(element); - doc.flush(); - require(batches == 0); - require(wakes == 0); - when("the interpreter connects", [&] { - state->ready = true; - state->wake(); - text.setText("updated"); - doc.flush(); - then("one batch contains the names once and all writes", [&] { - require(wakes == 1); - require(batches == 1); - require(sent.size() == 8); - require(sent[0].code == msg::DomOp::name); - require(sent[0].value == "root"); - require(sent.back().code == msg::DomOp::setText); - require(sent.back().value == "updated"); - doc.flush(); - require(batches == 1); - }); - }); - when("the application attempts to replace element children through setText", [&] { - requireThrows([&] { element.setText("replacement"); }); - require(text.valid()); - }); - when("a subtree is removed", [&] { - element.remove(); - require(!element.valid()); - require(!text.valid()); - require(root.valid()); - requireThrows([&] { text.setText("stale"); }); - }); - when("structure would create a cycle or move an island", [&] { - requireThrows([&] { element.append(root); }); - requireThrows([&] { text.append(element); }); - auto child = doc.element("div"); - element.append(child); - requireThrows([&] { child.append(element); }); - }); - }); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + std::vector sent; + unsigned batches{}, wakes{}; + state->send = [&](const msg::DomBatch& batch) { + ++batches; + sent = msg::DomBatch::decode(batch.data()).second; + }; + state->schedule = [&] { + ++wakes; + }; + given("writes before the interpreter connects", [&] { + auto root = doc.island(); + auto element = doc.element("p"); + auto text = doc.text("été 🌍"); + element.append(text); + root.append(element); + doc.flush(); + require(batches == 0); + require(wakes == 0); + when("the interpreter connects", [&] { + state->ready = true; + state->wake(); + text.setText("updated"); + doc.flush(); + then("one batch contains the names once and all writes", [&] { + require(wakes == 1); + require(batches == 1); + require(sent.size() == 8); + require(sent[0].code == msg::DomOp::name); + require(sent[0].value == "root"); + require(sent.back().code == msg::DomOp::setText); + require(sent.back().value == "updated"); + doc.flush(); + require(batches == 1); + }); + }); + when("the application attempts to replace element children through setText", [&] { + requireThrows([&] { + element.setText("replacement"); + }); + require(text.valid()); + }); + when("a subtree is removed", [&] { + element.remove(); + require(!element.valid()); + require(!text.valid()); + require(root.valid()); + requireThrows([&] { + text.setText("stale"); + }); + }); + when("structure would create a cycle or move an island", [&] { + requireThrows([&] { + element.append(root); + }); + requireThrows([&] { + text.append(element); + }); + auto child = doc.element("div"); + element.append(child); + requireThrows([&] { + child.append(element); + }); + }); + }); + }}; const Scenario dOMEvents{"DOM events and island revocation release callbacks", {"dom"}, [] { - auto state = std::make_shared(); - state->ready = true; - state->send = [](const auto&) { }; - dom::Document doc{Browser{state}}; - auto root = doc.island("panel"); - auto other = doc.island("other"); - auto button = doc.element("button"); - root.append(button); - int calls{}; - button.listen("click", - [&](std::string value) { - require(value.empty()); - ++calls; - button.unlisten("click"); - }, - {true, true}); - auto event = state->names.at("click"); - doc.flush(); - state->event(button.id(), event, ""); - state->event(button.id(), event, ""); - require(calls == 1); - doc.flush(); - const auto oldRootId = root.id(); - state->revoke("panel"); - require(!root.valid()); - require(!button.valid()); - require(other.valid()); - auto newRoot = doc.island("panel"); - require(newRoot.id() != oldRootId); - requireThrows([&] { root.id(); }); -}}; + auto state = std::make_shared(); + state->ready = true; + state->send = [](const auto&) {}; + dom::Document doc{Browser{state}}; + auto root = doc.island("panel"); + auto other = doc.island("other"); + auto button = doc.element("button"); + root.append(button); + int calls{}; + button.listen("click", + [&](std::string value) { + require(value.empty()); + ++calls; + button.unlisten("click"); + }, + {true, true}); + auto event = state->names.at("click"); + doc.flush(); + state->event(button.id(), event, ""); + state->event(button.id(), event, ""); + require(calls == 1); + doc.flush(); + const auto oldRootId = root.id(); + state->revoke("panel"); + require(!root.valid()); + require(!button.valid()); + require(other.valid()); + auto newRoot = doc.island("panel"); + require(newRoot.id() != oldRootId); + requireThrows([&] { + root.id(); + }); + }}; const Scenario dOMConnections{"DOM connections have separate lifetimes and closed handles remain safe", {"dom"}, [] { - auto first = std::make_shared(); - auto second = std::make_shared(); - dom::Document a{Browser{first}}, b{Browser{second}}; - auto node = a.text("first"); - auto other = b.element("div"); - requireThrows([&] { other.append(node); }); - bool rejected{}; - a.onError([&](std::uint32_t id, std::string reason) { - rejected = id == 1 && reason == "rejected"; - }); - first->reject(1, "rejected"); - require(rejected); - require(!a.valid()); - require(!node.valid()); - require(other.valid()); - requireThrows([&] { a.text("late"); }); - second->close(); // Same invalidation used on disconnect and shutdown. - require(!other.valid()); - requireThrows([&] { other.remove(); }); -}}; + auto first = std::make_shared(); + auto second = std::make_shared(); + dom::Document a{Browser{first}}, b{Browser{second}}; + auto node = a.text("first"); + auto other = b.element("div"); + requireThrows([&] { + other.append(node); + }); + bool rejected{}; + a.onError([&](std::uint32_t id, std::string reason) { + rejected = id == 1 && reason == "rejected"; + }); + first->reject(1, "rejected"); + require(rejected); + require(!a.valid()); + require(!node.valid()); + require(other.valid()); + requireThrows([&] { + a.text("late"); + }); + second->close(); // Same invalidation used on disconnect and shutdown. + require(!other.valid()); + requireThrows([&] { + other.remove(); + }); + }}; const Scenario dOMRejects{"DOM rejects off-thread access and retains a bounded pending batch on errors", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - bool rejected{}; - std::thread thread([&] { - try { - doc.text("wrong thread"); - } catch (const std::logic_error&) { - rejected = true; - } - }); - thread.join(); - require(rejected); - auto text = doc.text("kept"); - const auto size = state->pending.data().size(); - requireThrows([&] { text.setText(std::string(msg::DomBatch::maxBytes, 'x')); }); - require(state->pending.data().size() == size); - require(text.valid()); - requireThrows([&] { doc.element(std::string(1025, 'x')); }); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + bool rejected{}; + std::thread thread([&] { + try { + doc.text("wrong thread"); + } catch (const std::logic_error&) { + rejected = true; + } + }); + thread.join(); + require(rejected); + auto text = doc.text("kept"); + const auto size = state->pending.data().size(); + requireThrows([&] { + text.setText(std::string(msg::DomBatch::maxBytes, 'x')); + }); + require(state->pending.data().size() == size); + require(text.valid()); + requireThrows([&] { + doc.element(std::string(1025, 'x')); + }); + }}; namespace { struct ReadBrowser : Browser { @@ -165,202 +187,224 @@ struct ReadBrowser : Browser { }; } // namespace const Scenario dOMGrouped{"DOM grouped read results are bounded and structurally exact", {"dom"}, [] { - auto state = std::make_shared(); - state->ready = true; - state->send = [](const auto&) { }; - ReadBrowser browser{ - {state}, - {3, 0, 0, 0, 'o', 'n', 'e', 0, 0, 0, 0} - }; - dom::Document doc{browser}; - auto first = doc.text("one"), second = doc.text(""); - auto sender = doc.read({ - { first, dom::Read::text}, - {second, dom::Read::text} - }); - const auto result = networking::ex::sync_wait(std::move(sender)); - require(std::get<0>(*result) == std::vector{"one", ""}); - for (auto bytes : std::vector>{ - {}, - {1, 0, 0}, - {5, 0, 0, 0, 'a'}, - {0, 0, 0, 0, 1}, - {2, 0, 0, 0, 0xc0, 0x80} - }) { - browser.result = bytes; - dom::Document malformed{browser}; - requireThrows([&] { networking::ex::sync_wait(malformed.read({ - {first, dom::Read::text} - })); }); - } - requireThrows([&] { doc.read({}); }); - state->close(); - requireThrows([&] { networking::ex::sync_wait(doc.read({ - {first, dom::Read::text} - })); }); -}}; + auto state = std::make_shared(); + state->ready = true; + state->send = [](const auto&) {}; + ReadBrowser browser{ + {state}, + {3, 0, 0, 0, 'o', 'n', 'e', 0, 0, 0, 0} + }; + dom::Document doc{browser}; + auto first = doc.text("one"), second = doc.text(""); + auto sender = doc.read({ + { first, dom::Read::text}, + {second, dom::Read::text} + }); + const auto result = networking::ex::sync_wait(std::move(sender)); + require(std::get<0>(*result) == std::vector{"one", ""}); + for (auto bytes : std::vector>{ + {}, + {1, 0, 0}, + {5, 0, 0, 0, 'a'}, + {0, 0, 0, 0, 1}, + {2, 0, 0, 0, 0xc0, 0x80} + }) { + browser.result = bytes; + dom::Document malformed{browser}; + requireThrows([&] { + networking::ex::sync_wait(malformed.read({ + {first, dom::Read::text} + })); + }); + } + requireThrows([&] { + doc.read({}); + }); + state->close(); + requireThrows([&] { + networking::ex::sync_wait(doc.read({ + {first, dom::Read::text} + })); + }); + }}; const Scenario dOMRejectsElement{"DOM rejects element-only operations before changing a pending batch", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - auto text = doc.text("text"), island = doc.island(); - for (const auto& node : {text, island}) { - const auto size = state->pending.data().size(); - const auto names = state->names.size(); - requireThrows([&] { node.attribute("title", "value"); }); - requireThrows([&] { node.unsetAttribute("title"); }); - requireThrows([&] { node.property("value", "value"); }); - requireThrows([&] { node.listen("click", [](std::string) { }); }); - requireThrows([&] { node.unlisten("click"); }); - require(state->pending.data().size() == size); - require(state->names.size() == names); - require(state->listeners.empty()); - require(node.valid()); - } - require(doc.valid()); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + auto text = doc.text("text"), island = doc.island(); + for (const auto& node : {text, island}) { + const auto size = state->pending.data().size(); + const auto names = state->names.size(); + requireThrows([&] { + node.attribute("title", "value"); + }); + requireThrows([&] { + node.unsetAttribute("title"); + }); + requireThrows([&] { + node.property("value", "value"); + }); + requireThrows([&] { + node.listen("click", [](std::string) {}); + }); + requireThrows([&] { + node.unlisten("click"); + }); + require(state->pending.data().size() == size); + require(state->names.size() == names); + require(state->listeners.empty()); + require(node.valid()); + } + require(doc.valid()); + }}; const Scenario dOMReports{"DOM reports batch identifier exhaustion exactly once", {"dom"}, [] { - auto state = std::make_shared(); - state->batchId = std::numeric_limits::max(); - state->pending = msg::DomBatch(state->batchId); - state->ready = true; - unsigned sent{}, errors{}; - state->send = [&](const msg::DomBatch& batch) { - require(msg::DomBatch::decode(batch.data()).first == state->batchId); - ++sent; - }; - dom::Document doc{Browser{state}}; - doc.onError([&](std::uint32_t id, std::string reason) { - require(id == std::numeric_limits::max()); - require(reason == "DOM batch identifiers exhausted"); - ++errors; - }); - auto node = doc.text("last batch"); - requireThrows([&] { doc.flush(); }); - require(sent == 1); - require(errors == 1); - require(!doc.valid()); - require(!node.valid()); -}}; + auto state = std::make_shared(); + state->batchId = std::numeric_limits::max(); + state->pending = msg::DomBatch(state->batchId); + state->ready = true; + unsigned sent{}, errors{}; + state->send = [&](const msg::DomBatch& batch) { + require(msg::DomBatch::decode(batch.data()).first == state->batchId); + ++sent; + }; + dom::Document doc{Browser{state}}; + doc.onError([&](std::uint32_t id, std::string reason) { + require(id == std::numeric_limits::max()); + require(reason == "DOM batch identifiers exhausted"); + ++errors; + }); + auto node = doc.text("last batch"); + requireThrows([&] { + doc.flush(); + }); + require(sent == 1); + require(errors == 1); + require(!doc.valid()); + require(!node.valid()); + }}; const Scenario insertingDOM{"Inserting a DOM node before itself preserves its identity and pending batch", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - auto parent = doc.element("div"), child = doc.text("child"); - parent.append(child); - const auto size = state->pending.data().size(); - parent.insertBefore(child, child); - require(state->pending.data().size() == size); - require(child.valid()); - require(state->get(child.id()).parent == parent.id()); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + auto parent = doc.element("div"), child = doc.text("child"); + parent.append(child); + const auto size = state->pending.data().size(); + parent.insertBefore(child, child); + require(state->pending.data().size() == size); + require(child.valid()); + require(state->get(child.id()).parent == parent.id()); + }}; const Scenario dOMValidity{"DOM validity predicates are nonthrowing and agree about the calling thread", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - auto node = doc.text("valid"); - static_assert(noexcept(doc.valid())); - static_assert(noexcept(node.valid())); - require(doc.valid()); - require(node.valid()); - bool nodeValid = true, documentValid = true, threw = false; - std::thread caller([&] { - try { - nodeValid = node.valid(); - documentValid = doc.valid(); - } catch (...) { - threw = true; - } - }); - caller.join(); - require(!threw); - require(!nodeValid); - require(!documentValid); - require(doc.valid()); - require(node.valid()); - node.remove(); - require(!node.valid()); - require(doc.valid()); - auto moved = std::move(doc); - require(!doc.valid()); - require(moved.valid()); - state->close(); - require(!doc.valid()); - require(!moved.valid()); - require(!node.valid()); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + auto node = doc.text("valid"); + static_assert(noexcept(doc.valid())); + static_assert(noexcept(node.valid())); + require(doc.valid()); + require(node.valid()); + bool nodeValid = true, documentValid = true, threw = false; + std::thread caller([&] { + try { + nodeValid = node.valid(); + documentValid = doc.valid(); + } catch (...) { + threw = true; + } + }); + caller.join(); + require(!threw); + require(!nodeValid); + require(!documentValid); + require(doc.valid()); + require(node.valid()); + node.remove(); + require(!node.valid()); + require(doc.valid()); + auto moved = std::move(doc); + require(!doc.valid()); + require(moved.valid()); + state->close(); + require(!doc.valid()); + require(!moved.valid()); + require(!node.valid()); + }}; const Scenario dOMRejectsEmpty{"DOM rejects empty event callbacks without changing subscriptions or pending names", {"dom"}, [] { - auto state = std::make_shared(); - dom::Document doc{Browser{state}}; - auto button = doc.element("button"); - unsigned calls{}; - button.listen("click", [&](std::string) { - ++calls; - }); - const auto size = state->pending.data().size(); - const auto names = state->names.size(); - requireThrows([&] { button.listen("keydown", {}); }); - requireThrows([&] { button.listen("click", {}); }); - require(state->pending.data().size() == size); - require(state->names.size() == names); - require(state->listeners.size() == 1); - state->event(button.id(), state->names.at("click"), ""); - require(calls == 1); -}}; + auto state = std::make_shared(); + dom::Document doc{Browser{state}}; + auto button = doc.element("button"); + unsigned calls{}; + button.listen("click", [&](std::string) { + ++calls; + }); + const auto size = state->pending.data().size(); + const auto names = state->names.size(); + requireThrows([&] { + button.listen("keydown", {}); + }); + requireThrows([&] { + button.listen("click", {}); + }); + require(state->pending.data().size() == size); + require(state->names.size() == names); + require(state->listeners.size() == 1); + state->event(button.id(), state->names.at("click"), ""); + require(calls == 1); + }}; const Scenario islandUnmount{"An island unmount with pending writes closes the entire document once", {"dom"}, [] { - auto state = std::make_shared(); - state->ready = true; - state->send = [](const auto&) { }; - dom::Document doc{Browser{state}}; - auto first = doc.island("first"), second = doc.island("second"); - auto text = doc.text("second island"); - second.append(text); - doc.flush(); - unsigned errors{}; - doc.onError([&](std::uint32_t, std::string reason) { - require(reason == "DOM island revoked with pending writes"); - ++errors; - }); - text.setText("pending in a different island"); - state->revoke("first"); - require(errors == 1); - require(!doc.valid()); - require(!first.valid()); - require(!second.valid()); - require(!text.valid()); -}}; + auto state = std::make_shared(); + state->ready = true; + state->send = [](const auto&) {}; + dom::Document doc{Browser{state}}; + auto first = doc.island("first"), second = doc.island("second"); + auto text = doc.text("second island"); + second.append(text); + doc.flush(); + unsigned errors{}; + doc.onError([&](std::uint32_t, std::string reason) { + require(reason == "DOM island revoked with pending writes"); + ++errors; + }); + text.setText("pending in a different island"); + state->revoke("first"); + require(errors == 1); + require(!doc.valid()); + require(!first.valid()); + require(!second.valid()); + require(!text.valid()); + }}; const Scenario creatingGrouped{"Creating a grouped DOM read flushes writes even when its lazy read sender is discarded", {"dom"}, [] { - auto state = std::make_shared(); - state->ready = true; - unsigned writes{}; - state->send = [&](const auto&) { - ++writes; - }; - ReadBrowser browser{ - {state}, - {0, 0, 0, 0} - }; - dom::Document doc{browser}; - auto text = doc.text("pending write"); - require(writes == 0); - static_cast(doc.read({ - {text, dom::Read::text} - })); - require(writes == 1); - require(*browser.starts == 0); - auto sender = doc.read({ - {text, dom::Read::text} - }); - require(writes == 1); - require(*browser.starts == 0); - require(networking::ex::sync_wait(std::move(sender)).has_value()); - require(*browser.starts == 1); -}}; + auto state = std::make_shared(); + state->ready = true; + unsigned writes{}; + state->send = [&](const auto&) { + ++writes; + }; + ReadBrowser browser{ + {state}, + {0, 0, 0, 0} + }; + dom::Document doc{browser}; + auto text = doc.text("pending write"); + require(writes == 0); + static_cast(doc.read({ + {text, dom::Read::text} + })); + require(writes == 1); + require(*browser.starts == 0); + auto sender = doc.read({ + {text, dom::Read::text} + }); + require(writes == 1); + require(*browser.starts == 0); + require(networking::ex::sync_wait(std::move(sender)).has_value()); + require(*browser.starts == 1); + }}; namespace { namespace ex = networking::ex; @@ -405,217 +449,223 @@ struct ReadyDocument { dom::Document doc{Browser{state}}; ReadyDocument() { state->ready = true; - state->send = [](const auto&) { }; + state->send = [](const auto&) {}; } }; } // namespace const Scenario awaitedDOM{"An awaited DOM event subscribes when started and delivers one value", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto input = document.doc.element("input"); - document.doc.island().append(input); - document.doc.flush(); - given("a sender of the next input event", [&] { - auto sender = input.next("input", {.preventDefault = true, .stopPropagation = false}); - then("creating it subscribes nothing", [&] { - require(pendingCodes(*state).empty()); - require(state->waiters.empty()); - }); - when("it is started", [&] { - Awaited awaited; - auto operation = ex::connect(sender, EventReceiver{&awaited, {}}); - ex::start(operation); - const auto name = state->names.at("input"); - then("the browser subscription carries the flags declared by next()", [&] { - const auto operations = msg::DomBatch::decode(state->pending.data()).second; - require(operations.back().code == msg::DomOp::listen); - require(operations.back().a == input.id()); - require(operations.back().b == name); - require(operations.back().c == 1); - require(awaited.completions == 0); - }); - andWhen("the event arrives twice", [&] { - document.doc.flush(); - state->event(input.id(), name, "first"); - state->event(input.id(), name, "second"); - then("only the first completes the wait, which unsubscribes", [&] { - require(awaited.completions == 1); - require(awaited.value == "first"); - require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten}); - require(state->waiters.empty()); - }); - andThen("the same sender waits again for a later event", [&] { - Awaited again; - auto next = ex::connect(sender, EventReceiver{&again, {}}); - ex::start(next); - state->event(input.id(), name, "third"); - require(again.value == "third"); - require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten, msg::DomOp::listen, msg::DomOp::unlisten}); - }); - }); - }); - }); -}}; + ReadyDocument document; + auto& state = document.state; + auto input = document.doc.element("input"); + document.doc.island().append(input); + document.doc.flush(); + given("a sender of the next input event", [&] { + auto sender = input.next("input", {.preventDefault = true, .stopPropagation = false}); + then("creating it subscribes nothing", [&] { + require(pendingCodes(*state).empty()); + require(state->waiters.empty()); + }); + when("it is started", [&] { + Awaited awaited; + auto operation = ex::connect(sender, EventReceiver{&awaited, {}}); + ex::start(operation); + const auto name = state->names.at("input"); + then("the browser subscription carries the flags declared by next()", [&] { + const auto operations = msg::DomBatch::decode(state->pending.data()).second; + require(operations.back().code == msg::DomOp::listen); + require(operations.back().a == input.id()); + require(operations.back().b == name); + require(operations.back().c == 1); + require(awaited.completions == 0); + }); + andWhen("the event arrives twice", [&] { + document.doc.flush(); + state->event(input.id(), name, "first"); + state->event(input.id(), name, "second"); + then("only the first completes the wait, which unsubscribes", [&] { + require(awaited.completions == 1); + require(awaited.value == "first"); + require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten}); + require(state->waiters.empty()); + }); + andThen("the same sender waits again for a later event", [&] { + Awaited again; + auto next = ex::connect(sender, EventReceiver{&again, {}}); + ex::start(next); + state->event(input.id(), name, "third"); + require(again.value == "third"); + require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten, msg::DomOp::listen, msg::DomOp::unlisten}); + }); + }); + }); + }); + }}; const Scenario awaitedDOMEvent{"An awaited DOM event completes stopped when it can no longer occur", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto island = document.doc.island("panel"); - auto button = document.doc.element("button"); - island.append(button); - document.doc.flush(); - Awaited awaited; - auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, {}}); - ex::start(operation); - require(awaited.completions == 0); - when("the application unsubscribes the event", [&] { - button.unlisten("click"); - then("the wait stops", [&] { - require(awaited.stopped); - }); - }); - when("the node is removed", [&] { - button.remove(); - then("the wait stops", [&] { - require(awaited.stopped); - }); - }); - when("the page revokes the island", [&] { - state->revoke("panel"); - then("the wait stops", [&] { - require(awaited.stopped); - require(!button.valid()); - }); - }); - when("the browser disconnects", [&] { - state->close(); - then("the wait stops", [&] { - require(awaited.stopped); - }); - }); - when("the browser rejects a batch", [&] { - bool reported{}; - document.doc.onError([&](std::uint32_t, std::string) { - reported = awaited.stopped; - }); - state->reject(1, "rejected"); - then("the wait stops before the error is reported", [&] { - require(awaited.stopped); - require(reported); - }); - }); - require(awaited.completions == 1); -}}; + ReadyDocument document; + auto& state = document.state; + auto island = document.doc.island("panel"); + auto button = document.doc.element("button"); + island.append(button); + document.doc.flush(); + Awaited awaited; + auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, {}}); + ex::start(operation); + require(awaited.completions == 0); + when("the application unsubscribes the event", [&] { + button.unlisten("click"); + then("the wait stops", [&] { + require(awaited.stopped); + }); + }); + when("the node is removed", [&] { + button.remove(); + then("the wait stops", [&] { + require(awaited.stopped); + }); + }); + when("the page revokes the island", [&] { + state->revoke("panel"); + then("the wait stops", [&] { + require(awaited.stopped); + require(!button.valid()); + }); + }); + when("the browser disconnects", [&] { + state->close(); + then("the wait stops", [&] { + require(awaited.stopped); + }); + }); + when("the browser rejects a batch", [&] { + bool reported{}; + document.doc.onError([&](std::uint32_t, std::string) { + reported = awaited.stopped; + }); + state->reject(1, "rejected"); + then("the wait stops before the error is reported", [&] { + require(awaited.stopped); + require(reported); + }); + }); + require(awaited.completions == 1); + }}; const Scenario awaitedDOMEventCancelled{"An awaited DOM event is cancelled through its stop token", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto button = document.doc.element("button"); - ex::inplace_stop_source source; - Awaited awaited; - given("a stop requested before start", [&] { - source.request_stop(); - auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, source.get_token()}); - ex::start(operation); - then("it completes stopped without subscribing", [&] { - require(awaited.stopped); - require(awaited.completions == 1); - require(state->waiters.empty()); - require(!state->names.contains("click")); - }); - }); - given("a stop requested from another thread while waiting", [&] { - auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, source.get_token()}); - ex::start(operation); - std::thread([&] { - source.request_stop(); - }).join(); - require(awaited.stopped); - const auto name = state->names.at("click"); - when("the event arrives afterwards", [&] { - state->event(button.id(), name, ""); - then("the obsolete subscription is released without a second completion", [&] { - require(awaited.completions == 1); - require(state->waiters.empty()); - require(pendingCodes(*state).back() == msg::DomOp::unlisten); - }); - }); - when("a new wait or a callback subscribes the same event", [&] { - Awaited again; - auto next = ex::connect(button.next("click"), EventReceiver{&again, {}}); - ex::start(next); - state->event(button.id(), name, ""); - require(again.value == ""); - button.listen("click", [](std::string) { }); - then("the obsolete wait does not conflict", [&] { - require(again.completions == 1); - require(state->listeners.size() == 1); - }); - }); - }); -}}; + ReadyDocument document; + auto& state = document.state; + auto button = document.doc.element("button"); + ex::inplace_stop_source source; + Awaited awaited; + given("a stop requested before start", [&] { + source.request_stop(); + auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, source.get_token()}); + ex::start(operation); + then("it completes stopped without subscribing", [&] { + require(awaited.stopped); + require(awaited.completions == 1); + require(state->waiters.empty()); + require(!state->names.contains("click")); + }); + }); + given("a stop requested from another thread while waiting", [&] { + auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, source.get_token()}); + ex::start(operation); + std::thread([&] { + source.request_stop(); + }).join(); + require(awaited.stopped); + const auto name = state->names.at("click"); + when("the event arrives afterwards", [&] { + state->event(button.id(), name, ""); + then("the obsolete subscription is released without a second completion", [&] { + require(awaited.completions == 1); + require(state->waiters.empty()); + require(pendingCodes(*state).back() == msg::DomOp::unlisten); + }); + }); + when("a new wait or a callback subscribes the same event", [&] { + Awaited again; + auto next = ex::connect(button.next("click"), EventReceiver{&again, {}}); + ex::start(next); + state->event(button.id(), name, ""); + require(again.value == ""); + button.listen("click", [](std::string) {}); + then("the obsolete wait does not conflict", [&] { + require(again.completions == 1); + require(state->listeners.size() == 1); + }); + }); + }); + }}; const Scenario awaitedDOMEventRejects{"An awaited DOM event rejects conflicting subscriptions and invalid nodes", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto button = document.doc.element("button"); - auto text = document.doc.text("text"); - requireThrows([&] { (void)text.next("click"); }); - requireThrows([&] { (void)document.doc.island().next("click"); }); - Awaited first; - auto operation = ex::connect(button.next("click"), EventReceiver{&first, {}}); - ex::start(operation); - const auto size = state->pending.data().size(); - when("a second wait starts for the same event", [&] { - Awaited second; - auto other = ex::connect(button.next("click"), EventReceiver{&second, {}}); - ex::start(other); - then("only the second fails, without changing the pending batch", [&] { - require(second.error == "DOM event is already awaited"); - require(first.completions == 0); - require(state->pending.data().size() == size); - }); - }); - when("a callback subscribes the awaited event", [&] { - requireThrows([&] { button.listen("click", [](std::string) { }); }); - then("the wait still receives it", [&] { - require(state->pending.data().size() == size); - state->event(button.id(), state->names.at("click"), ""); - require(first.value == ""); - }); - }); - when("a wait starts for an event with a callback", [&] { - button.listen("keydown", [](std::string) { }); - Awaited second; - auto other = ex::connect(button.next("keydown"), EventReceiver{&second, {}}); - ex::start(other); - then("it fails", [&] { - require(second.error == "DOM event already has a listener"); - }); - }); - when("a wait starts on another thread", [&] { - Awaited second; - auto other = ex::connect(button.next("input"), EventReceiver{&second, {}}); - std::thread([&] { - ex::start(other); - }).join(); - then("it fails without touching the document", [&] { - require(second.error == "DOM document requires the server thread"); - require(!state->names.contains("input")); - }); - }); - when("the node is removed before a wait starts", [&] { - auto sender = button.next("input"); - button.remove(); - Awaited second; - auto other = ex::connect(sender, EventReceiver{&second, {}}); - ex::start(other); - then("it fails", [&] { - require(second.error == "DOM node is invalid"); - }); - }); -}}; + ReadyDocument document; + auto& state = document.state; + auto button = document.doc.element("button"); + auto text = document.doc.text("text"); + requireThrows([&] { + (void)text.next("click"); + }); + requireThrows([&] { + (void)document.doc.island().next("click"); + }); + Awaited first; + auto operation = ex::connect(button.next("click"), EventReceiver{&first, {}}); + ex::start(operation); + const auto size = state->pending.data().size(); + when("a second wait starts for the same event", [&] { + Awaited second; + auto other = ex::connect(button.next("click"), EventReceiver{&second, {}}); + ex::start(other); + then("only the second fails, without changing the pending batch", [&] { + require(second.error == "DOM event is already awaited"); + require(first.completions == 0); + require(state->pending.data().size() == size); + }); + }); + when("a callback subscribes the awaited event", [&] { + requireThrows([&] { + button.listen("click", [](std::string) {}); + }); + then("the wait still receives it", [&] { + require(state->pending.data().size() == size); + state->event(button.id(), state->names.at("click"), ""); + require(first.value == ""); + }); + }); + when("a wait starts for an event with a callback", [&] { + button.listen("keydown", [](std::string) {}); + Awaited second; + auto other = ex::connect(button.next("keydown"), EventReceiver{&second, {}}); + ex::start(other); + then("it fails", [&] { + require(second.error == "DOM event already has a listener"); + }); + }); + when("a wait starts on another thread", [&] { + Awaited second; + auto other = ex::connect(button.next("input"), EventReceiver{&second, {}}); + std::thread([&] { + ex::start(other); + }).join(); + then("it fails without touching the document", [&] { + require(second.error == "DOM document requires the server thread"); + require(!state->names.contains("input")); + }); + }); + when("the node is removed before a wait starts", [&] { + auto sender = button.next("input"); + button.remove(); + Awaited second; + auto other = ex::connect(sender, EventReceiver{&second, {}}); + ex::start(other); + then("it fails", [&] { + require(second.error == "DOM node is invalid"); + }); + }); + }}; namespace { Task wizard(dom::Node next, dom::Node back, std::vector& steps) { @@ -634,33 +684,33 @@ Task clicks(std::shared_ptr state, std::vector steps; - std::vector> sequence{ - {back, "ignored"}, - {next, "1"}, - {back, "2"}, - {next, "3"} - }; + ReadyDocument document; + auto next = document.doc.element("button"); + auto back = document.doc.element("button"); + std::vector steps; + std::vector> sequence{ + {back, "ignored"}, + {next, "1"}, + {back, "2"}, + {next, "3"} + }; #if defined(_MSC_VER) && _MSC_VER >= 1952 - // MSVC 19.52 rejects stdexec's when_all with two coroutine task senders. - // Exercise both coroutines on the server's shared scheduler instead. - ::stdnet::io_context context; - networking::TaskScope scope; - const auto scheduler = context.get_scheduler(); - const bool wizardStarted = networking::Spawn(scope, scheduler, wizard(next, back, steps)); - const bool clicksStarted = networking::Spawn(scope, scheduler, clicks(document.state, std::move(sequence))); - context.run(); - scope.drain(context); - require(wizardStarted && clicksStarted); + // MSVC 19.52 rejects stdexec's when_all with two coroutine task senders. + // Exercise both coroutines on the server's shared scheduler instead. + ::stdnet::io_context context; + networking::TaskScope scope; + const auto scheduler = context.get_scheduler(); + const bool wizardStarted = networking::Spawn(scope, scheduler, wizard(next, back, steps)); + const bool clicksStarted = networking::Spawn(scope, scheduler, clicks(document.state, std::move(sequence))); + context.run(); + scope.drain(context); + require(wizardStarted && clicksStarted); #else ex::sync_wait(ex::when_all(wizard(next, back, steps), clicks(document.state, std::move(sequence)))); #endif - require(steps == std::vector{"name: 1", "back: 2", "done: 3"}); - require(document.state->waiters.empty()); -}}; + require(steps == std::vector{"name: 1", "back: 2", "done: 3"}); + require(document.state->waiters.empty()); + }}; namespace { // Fills the pending batch until not even an unsubscription fits. @@ -668,134 +718,136 @@ void fillBatch(dom::detail::State& state, std::uint32_t node) { try { for (;;) state.add({msg::DomOp::unlisten, node, 0}); - } catch (const std::length_error&) { } + } catch (const std::length_error&) {} } } // namespace const Scenario cancelledDOM{"A cancelled DOM event wait releases its browser subscription", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto button = document.doc.element("button"); - ex::inplace_stop_source source; - Awaited awaited; - auto operation = ex::connect(button.next("click", {.preventDefault = true, .stopPropagation = true}), EventReceiver{&awaited, source.get_token()}); - ex::start(operation); - const auto name = state->names.at("click"); - document.doc.flush(); - given("a stop requested on the server thread", [&] { - source.request_stop(); - then("the wait stops and its browser listener is removed at once", [&] { - require(awaited.stopped); - require(state->waiters.empty()); - const auto operations = msg::DomBatch::decode(state->pending.data()).second; - require(operations.size() == 1); - require(operations[0].code == msg::DomOp::unlisten); - require(operations[0].a == button.id()); - require(operations[0].b == name); - }); - andWhen("the event was already on its way", [&] { - state->event(button.id(), name, ""); - then("it is ignored", [&] { - require(awaited.completions == 1); - require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten}); - }); - }); - }); - given("stops requested from another thread", [&] { - unsigned posts{}; - state->post = [&] { - ++posts; - }; - ex::inplace_stop_source otherSource; - Awaited other; - auto second = ex::connect(button.next("keydown"), EventReceiver{&other, otherSource.get_token()}); - ex::start(second); - document.doc.flush(); - std::thread([&] { - source.request_stop(); - otherSource.request_stop(); - }).join(); - then("one release is posted to the server context", [&] { - require(awaited.stopped); - require(other.stopped); - require(posts == 1); - require(pendingCodes(*state).empty()); - }); - andWhen("the server context runs it", [&] { - state->sweep(); - then("both browser listeners are removed", [&] { - require(state->waiters.empty()); - require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten, msg::DomOp::unlisten}); - }); - }); - andWhen("a new wait subscribes the same event before it runs", [&] { - Awaited again; - auto next = ex::connect(button.next("click"), EventReceiver{&again, {}}); - ex::start(next); - state->sweep(); - then("the new subscription is kept", [&] { - require(pendingCodes(*state) == std::vector{msg::DomOp::listen, msg::DomOp::unlisten}); - state->event(button.id(), name, "later"); - require(again.value == "later"); - }); - }); - }); - given("a document closed before a stop from another thread", [&] { - unsigned posts{}; - state->post = [&] { - ++posts; - }; - state->close(); - then("the wait stopped with the document and nothing is posted", [&] { - require(awaited.stopped); - std::thread([&] { - source.request_stop(); - }).join(); - require(posts == 0); - require(awaited.completions == 1); - }); - }); -}}; + ReadyDocument document; + auto& state = document.state; + auto button = document.doc.element("button"); + ex::inplace_stop_source source; + Awaited awaited; + auto operation = ex::connect(button.next("click", {.preventDefault = true, .stopPropagation = true}), + EventReceiver{&awaited, source.get_token()}); + ex::start(operation); + const auto name = state->names.at("click"); + document.doc.flush(); + given("a stop requested on the server thread", [&] { + source.request_stop(); + then("the wait stops and its browser listener is removed at once", [&] { + require(awaited.stopped); + require(state->waiters.empty()); + const auto operations = msg::DomBatch::decode(state->pending.data()).second; + require(operations.size() == 1); + require(operations[0].code == msg::DomOp::unlisten); + require(operations[0].a == button.id()); + require(operations[0].b == name); + }); + andWhen("the event was already on its way", [&] { + state->event(button.id(), name, ""); + then("it is ignored", [&] { + require(awaited.completions == 1); + require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten}); + }); + }); + }); + given("stops requested from another thread", [&] { + unsigned posts{}; + state->post = [&] { + ++posts; + }; + ex::inplace_stop_source otherSource; + Awaited other; + auto second = ex::connect(button.next("keydown"), EventReceiver{&other, otherSource.get_token()}); + ex::start(second); + document.doc.flush(); + std::thread([&] { + source.request_stop(); + otherSource.request_stop(); + }).join(); + then("one release is posted to the server context", [&] { + require(awaited.stopped); + require(other.stopped); + require(posts == 1); + require(pendingCodes(*state).empty()); + }); + andWhen("the server context runs it", [&] { + state->sweep(); + then("both browser listeners are removed", [&] { + require(state->waiters.empty()); + require(pendingCodes(*state) == std::vector{msg::DomOp::unlisten, msg::DomOp::unlisten}); + }); + }); + andWhen("a new wait subscribes the same event before it runs", [&] { + Awaited again; + auto next = ex::connect(button.next("click"), EventReceiver{&again, {}}); + ex::start(next); + state->sweep(); + then("the new subscription is kept", [&] { + require(pendingCodes(*state) == std::vector{msg::DomOp::listen, msg::DomOp::unlisten}); + state->event(button.id(), name, "later"); + require(again.value == "later"); + }); + }); + }); + given("a document closed before a stop from another thread", [&] { + unsigned posts{}; + state->post = [&] { + ++posts; + }; + state->close(); + then("the wait stopped with the document and nothing is posted", [&] { + require(awaited.stopped); + std::thread([&] { + source.request_stop(); + }).join(); + require(posts == 0); + require(awaited.completions == 1); + }); + }); + }}; const Scenario dOMUnsubscription{"A DOM unsubscription that does not fit a full batch opens the next one", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto button = document.doc.element("button"); - ex::inplace_stop_source source; - Awaited awaited; - auto operation = ex::connect(button.next("click", {.preventDefault = true, .stopPropagation = false}), EventReceiver{&awaited, source.get_token()}); - ex::start(operation); - const auto name = state->names.at("click"); - document.doc.flush(); - fillBatch(*state, button.id()); - when("the awaited event arrives", [&] { - state->event(button.id(), name, "value"); - require(awaited.value == "value"); - }); - when("the wait is cancelled", [&] { - source.request_stop(); - require(awaited.stopped); - }); - require(state->waiters.empty()); - document.doc.flush(); - const auto operations = msg::DomBatch::decode(state->pending.data()).second; - require(operations.size() == 1); - require(operations[0].code == msg::DomOp::unlisten); - require(operations[0].a == button.id()); - require(operations[0].b == name); -}}; + ReadyDocument document; + auto& state = document.state; + auto button = document.doc.element("button"); + ex::inplace_stop_source source; + Awaited awaited; + auto operation = ex::connect(button.next("click", {.preventDefault = true, .stopPropagation = false}), + EventReceiver{&awaited, source.get_token()}); + ex::start(operation); + const auto name = state->names.at("click"); + document.doc.flush(); + fillBatch(*state, button.id()); + when("the awaited event arrives", [&] { + state->event(button.id(), name, "value"); + require(awaited.value == "value"); + }); + when("the wait is cancelled", [&] { + source.request_stop(); + require(awaited.stopped); + }); + require(state->waiters.empty()); + document.doc.flush(); + const auto operations = msg::DomBatch::decode(state->pending.data()).second; + require(operations.size() == 1); + require(operations[0].code == msg::DomOp::unlisten); + require(operations[0].a == button.id()); + require(operations[0].b == name); + }}; const Scenario dOMEvent{"A DOM event wait that cannot be queued subscribes nothing", {"dom"}, [] { - ReadyDocument document; - auto& state = document.state; - auto button = document.doc.element("button"); - state->intern("click"); - fillBatch(*state, button.id()); - Awaited awaited; - auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, {}}); - ex::start(operation); - then("it fails without a waiter", [&] { - require(!awaited.error.empty()); - require(state->waiters.empty()); - }); -}}; + ReadyDocument document; + auto& state = document.state; + auto button = document.doc.element("button"); + state->intern("click"); + fillBatch(*state, button.id()); + Awaited awaited; + auto operation = ex::connect(button.next("click"), EventReceiver{&awaited, {}}); + ex::start(operation); + then("it fails without a waiter", [&] { + require(!awaited.error.empty()); + require(state->waiters.empty()); + }); + }}; diff --git a/test/unit/DownloadsTests.cpp b/test/unit/DownloadsTests.cpp index d3ab5012..8b4f6748 100644 --- a/test/unit/DownloadsTests.cpp +++ b/test/unit/DownloadsTests.cpp @@ -1,8 +1,8 @@ -#include #include +#include -#include #include +#include #include #include #include @@ -14,149 +14,149 @@ using webfront::frontend::detail::DownloadReservations; using webfront::frontend::detail::uniqueDownloadPath; const Scenario downloadStaging{"Download staging preserves a destination created while a download runs", [] { - std::random_device random; - const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); - require(std::filesystem::create_directory(folder)); - const auto target = folder / "target.txt"; - given("another process creates the destination during the download", [&] { - when("the completed download is installed without permission to replace", [&] { - std::filesystem::path stagingPath; - bool installed = false; - { - webfront::frontend::detail::DownloadStaging staging(folder); - stagingPath = staging.path(); - std::ofstream(stagingPath) << "download"; - std::ofstream(target) << "other file"; - installed = staging.finish(target, false); - } - then("the other file survives and the private staging directory is removed", [&] { - require(!installed); - std::ifstream stream(target); - require(std::string(std::istreambuf_iterator(stream), {}) == "other file"); - require(!std::filesystem::exists(stagingPath.parent_path())); - }); - }); - }); - given("the destination is free", [&] { - when("the completed download is installed", [&] { - std::filesystem::path stagingPath; - bool installed = false; - { - webfront::frontend::detail::DownloadStaging staging(folder); - stagingPath = staging.path(); - std::ofstream(stagingPath) << "completed"; - installed = staging.finish(target, false); - } - then("the destination holds the completed bytes and staging is removed", [&] { - require(installed); - std::ifstream completed(target); - require(std::string(std::istreambuf_iterator(completed), {}) == "completed"); - require(!std::filesystem::exists(stagingPath.parent_path())); - }); - }); - }); - std::filesystem::remove(target); - std::filesystem::remove(folder); -}}; + std::random_device random; + const auto folder = std::filesystem::temp_directory_path() / ("webfront-download-staging-unit-" + std::to_string(random())); + require(std::filesystem::create_directory(folder)); + const auto target = folder / "target.txt"; + given("another process creates the destination during the download", [&] { + when("the completed download is installed without permission to replace", [&] { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "download"; + std::ofstream(target) << "other file"; + installed = staging.finish(target, false); + } + then("the other file survives and the private staging directory is removed", [&] { + require(!installed); + std::ifstream stream(target); + require(std::string(std::istreambuf_iterator(stream), {}) == "other file"); + require(!std::filesystem::exists(stagingPath.parent_path())); + }); + }); + }); + given("the destination is free", [&] { + when("the completed download is installed", [&] { + std::filesystem::path stagingPath; + bool installed = false; + { + webfront::frontend::detail::DownloadStaging staging(folder); + stagingPath = staging.path(); + std::ofstream(stagingPath) << "completed"; + installed = staging.finish(target, false); + } + then("the destination holds the completed bytes and staging is removed", [&] { + require(installed); + std::ifstream completed(target); + require(std::string(std::istreambuf_iterator(completed), {}) == "completed"); + require(!std::filesystem::exists(stagingPath.parent_path())); + }); + }); + }); + std::filesystem::remove(target); + std::filesystem::remove(folder); + }}; const Scenario downloadName{"A download name suggested by a page stays inside the download folder", [] { - const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-unit"; - std::filesystem::remove_all(folder); - std::filesystem::create_directories(folder); - given("names that try to leave the folder or name nothing", [&] { - then("only the last component is kept, and an empty name becomes \"download\"", [&] { - require(uniqueDownloadPath(folder, "report.txt") == folder / "report.txt"); - require(uniqueDownloadPath(folder, "../../etc/passwd") == folder / "passwd"); - require(uniqueDownloadPath(folder, "a/b/c.bin") == folder / "c.bin"); - for (const auto* name : {"", ".", "..", "dir/.."}) { - auto scope = info(name); - require(uniqueDownloadPath(folder, name) == folder / "download"); - } - }); - }); - given("files that already exist", [&] { - std::ofstream(folder / "report.txt") << "1"; - then("the name is numbered rather than overwritten", [&] { - require(uniqueDownloadPath(folder, "report.txt") == folder / "report (1).txt"); - std::ofstream(folder / "report (1).txt") << "2"; - require(uniqueDownloadPath(folder, "report.txt") == folder / "report (2).txt"); - }); - }); - given("every candidate is reserved by another download", [&] { - then("exhaustion is reported instead of returning an occupied path", [&] { - std::size_t probes = 0; - requireThrows([&] { uniqueDownloadPath(folder, - "report.txt", - [&](const auto&) { - ++probes; - return true; - }); }); - require(probes == 10'000); - }); - }); - given("only the last candidate is available", [&] { - then("that candidate can still be used", [&] { - require(uniqueDownloadPath(folder, - "report.txt", - [&](const auto& path) { - return path.filename() != "report (9999).txt"; - }) - == folder / "report (9999).txt"); - }); - }); - std::filesystem::remove_all(folder); -}}; + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-unit"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + given("names that try to leave the folder or name nothing", [&] { + then("only the last component is kept, and an empty name becomes \"download\"", [&] { + require(uniqueDownloadPath(folder, "report.txt") == folder / "report.txt"); + require(uniqueDownloadPath(folder, "../../etc/passwd") == folder / "passwd"); + require(uniqueDownloadPath(folder, "a/b/c.bin") == folder / "c.bin"); + for (const auto* name : {"", ".", "..", "dir/.."}) { + auto scope = info(name); + require(uniqueDownloadPath(folder, name) == folder / "download"); + } + }); + }); + given("files that already exist", [&] { + std::ofstream(folder / "report.txt") << "1"; + then("the name is numbered rather than overwritten", [&] { + require(uniqueDownloadPath(folder, "report.txt") == folder / "report (1).txt"); + std::ofstream(folder / "report (1).txt") << "2"; + require(uniqueDownloadPath(folder, "report.txt") == folder / "report (2).txt"); + }); + }); + given("every candidate is reserved by another download", [&] { + then("exhaustion is reported instead of returning an occupied path", [&] { + std::size_t probes = 0; + requireThrows([&] { + uniqueDownloadPath(folder, "report.txt", [&](const auto&) { + ++probes; + return true; + }); + }); + require(probes == 10'000); + }); + }); + given("only the last candidate is available", [&] { + then("that candidate can still be used", [&] { + require(uniqueDownloadPath(folder, + "report.txt", + [&](const auto& path) { + return path.filename() != "report (9999).txt"; + }) + == folder / "report (9999).txt"); + }); + }); + std::filesystem::remove_all(folder); + }}; const Scenario downloadsAsk{"Downloads that ask for the same name before their files exist get different destinations", [] { - const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-reserved"; - std::filesystem::remove_all(folder); - std::filesystem::create_directories(folder); - DownloadReservations reservations; - given("two downloads suggesting report.txt, neither file created yet", [&] { - const auto first = reservations.reserve(folder, "report.txt"); - const auto second = reservations.reserve(folder, "report.txt"); - then("the second one is numbered", [&] { - require(first == folder / "report.txt"); - require(second == folder / "report (1).txt"); - require(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); - }); - andWhen("the first download ends without creating a file", [&] { - reservations.release(first); - then("its name is available again", [&] { - require(reservations.reserve(folder, "report.txt") == first); - }); - }); - andWhen("a file appears under a released name", [&] { - reservations.release(first); - std::ofstream(first) << "done"; - then("it is the existing file that keeps the name taken", [&] { - require(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); - }); - }); - }); - given("many threads asking for the same name at once", [&] { - static constexpr std::size_t threads = 16; - std::vector granted(threads); - std::vector workers; - for (std::size_t index = 0; index < threads; ++index) - workers.emplace_back([&, index] { - granted[index] = reservations.reserve(folder, "same.bin"); - }); - for (auto& worker : workers) - worker.join(); - then("every destination is distinct", [&] { - require(std::set(granted.begin(), granted.end()).size() == threads); - }); - }); - given("released reservations", [&] { - const auto path = reservations.reserve(folder, "once.txt"); - reservations.release(path); - then("nothing stays reserved", [&] { - DownloadReservations other; - const auto again = other.reserve(folder, "x"); - other.release(again); - require(other.empty()); - }); - }); - std::filesystem::remove_all(folder); -}}; + const auto folder = std::filesystem::temp_directory_path() / "webfront-downloads-reserved"; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + DownloadReservations reservations; + given("two downloads suggesting report.txt, neither file created yet", [&] { + const auto first = reservations.reserve(folder, "report.txt"); + const auto second = reservations.reserve(folder, "report.txt"); + then("the second one is numbered", [&] { + require(first == folder / "report.txt"); + require(second == folder / "report (1).txt"); + require(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + }); + andWhen("the first download ends without creating a file", [&] { + reservations.release(first); + then("its name is available again", [&] { + require(reservations.reserve(folder, "report.txt") == first); + }); + }); + andWhen("a file appears under a released name", [&] { + reservations.release(first); + std::ofstream(first) << "done"; + then("it is the existing file that keeps the name taken", [&] { + require(reservations.reserve(folder, "report.txt") == folder / "report (2).txt"); + }); + }); + }); + given("many threads asking for the same name at once", [&] { + static constexpr std::size_t threads = 16; + std::vector granted(threads); + std::vector workers; + for (std::size_t index = 0; index < threads; ++index) + workers.emplace_back([&, index] { + granted[index] = reservations.reserve(folder, "same.bin"); + }); + for (auto& worker : workers) + worker.join(); + then("every destination is distinct", [&] { + require(std::set(granted.begin(), granted.end()).size() == threads); + }); + }); + given("released reservations", [&] { + const auto path = reservations.reserve(folder, "once.txt"); + reservations.release(path); + then("nothing stays reserved", [&] { + DownloadReservations other; + const auto again = other.reserve(folder, "x"); + other.release(again); + require(other.empty()); + }); + }); + std::filesystem::remove_all(folder); + }}; diff --git a/test/unit/EmbeddedAssetChecks.hpp b/test/unit/EmbeddedAssetChecks.hpp index bb3fd978..c7949fdc 100644 --- a/test/unit/EmbeddedAssetChecks.hpp +++ b/test/unit/EmbeddedAssetChecks.hpp @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include #include diff --git a/test/unit/EmbeddedCoreAssetsTests.cpp b/test/unit/EmbeddedCoreAssetsTests.cpp index f80d69f7..48b9b15f 100644 --- a/test/unit/EmbeddedCoreAssetsTests.cpp +++ b/test/unit/EmbeddedCoreAssetsTests.cpp @@ -1,11 +1,11 @@ -#include #include #include +#include #include #include #include #include -#include +#include #include #include @@ -47,21 +47,23 @@ void requireHeaderMatchesSource(std::string_view source) { require(embedded.size() >= expected.size()); require(embedded.size() - expected.size() < 8); require(std::string_view(embedded).substr(0, expected.size()) == expected); - require(std::ranges::all_of(std::string_view(embedded).substr(expected.size()), [](char c) { return c == '\0'; })); + require(std::ranges::all_of(std::string_view(embedded).substr(expected.size()), [](char c) { + return c == '\0'; + })); } } // namespace const Scenario embeddedAssets{"The embedded assets of the core are the readable sources they are generated from", [] { - given("The generated headers of include/webfront/system and the sources of js/core", [&] { - then("Each header embeds exactly the bytes of its source, without compression and with zero padding only", [&] { - requireHeaderMatchesSource("js/core/dom-interpreter.mjs"); - requireHeaderMatchesSource("js/core/WebFront.js"); - requireHeaderMatchesSource("js/core/fallback/index.html"); - requireHeaderMatchesSource("js/core/fallback/webfront-fallback.mjs"); - requireHeaderMatchesSource("js/core/favicon.ico"); - requireHeaderMatchesSource("js/core/bootstrap/index.html"); - requireHeaderMatchesSource("js/core/bootstrap/bootstrap.bundle.mjs"); - }); - }); -}}; + given("The generated headers of include/webfront/system and the sources of js/core", [&] { + then("Each header embeds exactly the bytes of its source, without compression and with zero padding only", [&] { + requireHeaderMatchesSource("js/core/dom-interpreter.mjs"); + requireHeaderMatchesSource("js/core/WebFront.js"); + requireHeaderMatchesSource("js/core/fallback/index.html"); + requireHeaderMatchesSource("js/core/fallback/webfront-fallback.mjs"); + requireHeaderMatchesSource("js/core/favicon.ico"); + requireHeaderMatchesSource("js/core/bootstrap/index.html"); + requireHeaderMatchesSource("js/core/bootstrap/bootstrap.bundle.mjs"); + }); + }); + }}; diff --git a/test/unit/EncodingsTests.cpp b/test/unit/EncodingsTests.cpp index 41c53b17..0777bd51 100644 --- a/test/unit/EncodingsTests.cpp +++ b/test/unit/EncodingsTests.cpp @@ -1,5 +1,4 @@ #include - #include #include @@ -10,149 +9,151 @@ using namespace webfront; using namespace std; const Scenario uRLEncoding{"URL encoding", [] { - require(uri::encode("mango & pineapple") == "mango%20%26%20pineapple"); - require(uri::encode("AZaz09-_.~") == "AZaz09-_.~"); - - given("non-ASCII bytes", [&] { - then("each byte is percent-encoded", [&] { - require(uri::encode("\xC3\xA9") == "%C3%A9"); // é in UTF-8 - require(uri::encode("caf\xC3\xA9 \xE2\x82\xAC") == "caf%C3%A9%20%E2%82%AC"); - require(uri::encode(string_view("\x00\x7F\x80\xFF", 4)) == "%00%7F%80%FF"); - }); - }); - - given("every byte value", [&] { - string all; - for (int byte = 0; byte < 256; ++byte) - all += static_cast(byte); - then("decoding the encoded string restores it", [&] { - require(uri::decode(uri::encode(all)) == all); - }); - }); -}}; + require(uri::encode("mango & pineapple") == "mango%20%26%20pineapple"); + require(uri::encode("AZaz09-_.~") == "AZaz09-_.~"); + + given("non-ASCII bytes", [&] { + then("each byte is percent-encoded", [&] { + require(uri::encode("\xC3\xA9") == "%C3%A9"); // é in UTF-8 + require(uri::encode("caf\xC3\xA9 \xE2\x82\xAC") == "caf%C3%A9%20%E2%82%AC"); + require(uri::encode(string_view("\x00\x7F\x80\xFF", 4)) == "%00%7F%80%FF"); + }); + }); + + given("every byte value", [&] { + string all; + for (int byte = 0; byte < 256; ++byte) + all += static_cast(byte); + then("decoding the encoded string restores it", [&] { + require(uri::decode(uri::encode(all)) == all); + }); + }); + }}; const Scenario uRIDecoding{"URI decoding", [] { - require(uri::decode("http://path%25name%2F%25%23%21%25") == "http://path%name/%#!%"); - require(uri::decode("http://ABC12345zef") == "http://ABC12345zef"); - require(uri::decode("%20%RQabcABV") == " %RQabcABV"); - require(uri::decode("%c3%a9") == "\xC3\xA9"); - require(uri::decode("%\xC3\xA9%E9") == "%\xC3\xA9\xE9"); // Non-ASCII bytes after '%' are kept as they are -}}; + require(uri::decode("http://path%25name%2F%25%23%21%25") == "http://path%name/%#!%"); + require(uri::decode("http://ABC12345zef") == "http://ABC12345zef"); + require(uri::decode("%20%RQabcABV") == " %RQabcABV"); + require(uri::decode("%c3%a9") == "\xC3\xA9"); + require(uri::decode("%\xC3\xA9%E9") == "%\xC3\xA9\xE9"); // Non-ASCII bytes after '%' are kept as they are + }}; const Scenario uRIParsing{"URI parsing", [] { - given("An URI with no userinfo nor fragment", [&] { - uri::URI u0("http://localhost:80/foo.html?&q=1:2:3"); - when("decoded", [&] { - require(u0.scheme == "http"); - require(u0.userinfo.empty()); - require(u0.host == "localhost"); - require(u0.port == "80"); - require(u0.path == "/foo.html"); - require(u0.authority == "localhost:80"); - require(u0.query == "&q=1:2:3"); - require(u0.fragment.empty()); - }); - }); - - given("A complete URI", [&] { - uri::URI u1("https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top"); - when("decoded", [&] { - require(u1.scheme == "https"); - require(u1.userinfo == "john.doe"); - require(u1.host == "www.example.com"); - require(u1.port == "123"); - require(u1.path == "/forum/questions/"); - require(u1.authority == "john.doe@www.example.com:123"); - require(u1.query == "tag=networking&order=newest"); - require(u1.fragment == "top"); - }); - }); - - given("A Relative URI", [&] { - uri::URI u2("/forum/questions/?tag=networking&order=newest#top"); - when("decoded", [&] { - require(u2.scheme.empty()); - require(u2.userinfo.empty()); - require(u2.host.empty()); - require(u2.port.empty()); - require(u2.path == "/forum/questions/"); - require(u2.authority.empty()); - require(u2.query == "tag=networking&order=newest"); - require(u2.fragment == "top"); - }); - }); - - given("A function which returns an URI from a string", [&] { - auto parse = [](std::string text) { return uri::URI(text); }; - - when("parsing URI without userinfo", [&] { - auto u = parse("https://www.example.com:123/forum/questions/?tag=networking&order=newest#top"); - then("fields should be", [&] { - require(u.scheme == "https"); - require(u.userinfo.empty()); - require(u.host == "www.example.com"); - require(u.port == "123"); - require(u.path == "/forum/questions/"); - require(u.authority == "www.example.com:123"); - require(u.query == "tag=networking&order=newest"); - require(u.fragment == "top"); - }); - }); - - when("parsing URI without userinfo nor port", [&] { - auto u = parse("https://www.example.com/forum/questions/?tag=networking&order=newest#top"); - then("fields should be", [&] { - require(u.scheme == "https"); - require(u.userinfo.empty()); - require(u.host == "www.example.com"); - require(u.port.empty()); - require(u.path == "/forum/questions/"); - require(u.authority == "www.example.com"); - require(u.query == "tag=networking&order=newest"); - require(u.fragment == "top"); - }); - }); - - when("parsing URI without userinfo nor port or query", [&] { - auto u = parse("https://www.example.com/forum/questions/"); - then("fields should be", [&] { - require(u.scheme == "https"); - require(u.userinfo.empty()); - require(u.host == "www.example.com"); - require(u.port.empty()); - require(u.path == "/forum/questions/"); - require(u.authority == "www.example.com"); - require(u.query.empty()); - require(u.fragment.empty()); - }); - }); - }); -}}; + given("An URI with no userinfo nor fragment", [&] { + uri::URI u0("http://localhost:80/foo.html?&q=1:2:3"); + when("decoded", [&] { + require(u0.scheme == "http"); + require(u0.userinfo.empty()); + require(u0.host == "localhost"); + require(u0.port == "80"); + require(u0.path == "/foo.html"); + require(u0.authority == "localhost:80"); + require(u0.query == "&q=1:2:3"); + require(u0.fragment.empty()); + }); + }); + + given("A complete URI", [&] { + uri::URI u1("https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top"); + when("decoded", [&] { + require(u1.scheme == "https"); + require(u1.userinfo == "john.doe"); + require(u1.host == "www.example.com"); + require(u1.port == "123"); + require(u1.path == "/forum/questions/"); + require(u1.authority == "john.doe@www.example.com:123"); + require(u1.query == "tag=networking&order=newest"); + require(u1.fragment == "top"); + }); + }); + + given("A Relative URI", [&] { + uri::URI u2("/forum/questions/?tag=networking&order=newest#top"); + when("decoded", [&] { + require(u2.scheme.empty()); + require(u2.userinfo.empty()); + require(u2.host.empty()); + require(u2.port.empty()); + require(u2.path == "/forum/questions/"); + require(u2.authority.empty()); + require(u2.query == "tag=networking&order=newest"); + require(u2.fragment == "top"); + }); + }); + + given("A function which returns an URI from a string", [&] { + auto parse = [](std::string text) { + return uri::URI(text); + }; + + when("parsing URI without userinfo", [&] { + auto u = parse("https://www.example.com:123/forum/questions/?tag=networking&order=newest#top"); + then("fields should be", [&] { + require(u.scheme == "https"); + require(u.userinfo.empty()); + require(u.host == "www.example.com"); + require(u.port == "123"); + require(u.path == "/forum/questions/"); + require(u.authority == "www.example.com:123"); + require(u.query == "tag=networking&order=newest"); + require(u.fragment == "top"); + }); + }); + + when("parsing URI without userinfo nor port", [&] { + auto u = parse("https://www.example.com/forum/questions/?tag=networking&order=newest#top"); + then("fields should be", [&] { + require(u.scheme == "https"); + require(u.userinfo.empty()); + require(u.host == "www.example.com"); + require(u.port.empty()); + require(u.path == "/forum/questions/"); + require(u.authority == "www.example.com"); + require(u.query == "tag=networking&order=newest"); + require(u.fragment == "top"); + }); + }); + + when("parsing URI without userinfo nor port or query", [&] { + auto u = parse("https://www.example.com/forum/questions/"); + then("fields should be", [&] { + require(u.scheme == "https"); + require(u.userinfo.empty()); + require(u.host == "www.example.com"); + require(u.port.empty()); + require(u.path == "/forum/questions/"); + require(u.authority == "www.example.com"); + require(u.query.empty()); + require(u.fragment.empty()); + }); + }); + }); + }}; const Scenario webSocketSec{"WebSocket Sec Key coding", [] { - std::string key = "x3JJHMbDL1EzLkh9GBhXDw=="; - require(base64::encodeInNetworkOrder(crypto::sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) == - "HSmrc0sMlYUkAGmm5OPpG2HaGWk="); + std::string key = "x3JJHMbDL1EzLkh9GBhXDw=="; + require(base64::encodeInNetworkOrder(crypto::sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) + == "HSmrc0sMlYUkAGmm5OPpG2HaGWk="); - key = "dGhlIHNhbXBsZSBub25jZQ=="; - require(base64::encodeInNetworkOrder(crypto::sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) == - "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); -}}; + key = "dGhlIHNhbXBsZSBub25jZQ=="; + require(base64::encodeInNetworkOrder(crypto::sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) + == "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); + }}; const Scenario base64Encoding{"Base64 encoding", [] { - require(base64::encode(std::string{}) == ""); - require(base64::encode(std::string{"f"}) == "Zg=="); - require(base64::encode(std::string{"fo"}) == "Zm8="); - require(base64::encode(std::string{"foo"}) == "Zm9v"); - require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy dog")) == - "L9ThxnotKPzthJ7hu3bnORuT6xI="); - require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy cog")) == - "3p8sf9JeGzr60+haC9F9mxANtLM="); - require(base64::encodeInNetworkOrder(crypto::sha1("")) == "2jmj7l5rSw0yVb/vlWAYkK/YBwk="); -}}; + require(base64::encode(std::string{}) == ""); + require(base64::encode(std::string{"f"}) == "Zg=="); + require(base64::encode(std::string{"fo"}) == "Zm8="); + require(base64::encode(std::string{"foo"}) == "Zm9v"); + require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy dog")) + == "L9ThxnotKPzthJ7hu3bnORuT6xI="); + require(base64::encodeInNetworkOrder(crypto::sha1("The quick brown fox jumps over the lazy cog")) + == "3p8sf9JeGzr60+haC9F9mxANtLM="); + require(base64::encodeInNetworkOrder(crypto::sha1("")) == "2jmj7l5rSw0yVb/vlWAYkK/YBwk="); + }}; const Scenario sHA1Hashing{"SHA1 hashing", [] { - require(crypto::sha1String("The quick brown fox jumps over the lazy dog") == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); - require(crypto::sha1String("The quick brown fox jumps over the lazy cog") == "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"); - require(crypto::sha1String("") == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); -}}; \ No newline at end of file + require(crypto::sha1String("The quick brown fox jumps over the lazy dog") == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); + require(crypto::sha1String("The quick brown fox jumps over the lazy cog") == "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"); + require(crypto::sha1String("") == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + }}; \ No newline at end of file diff --git a/test/unit/FileSystemTests.cpp b/test/unit/FileSystemTests.cpp index 598e7177..16fc7b02 100644 --- a/test/unit/FileSystemTests.cpp +++ b/test/unit/FileSystemTests.cpp @@ -1,7 +1,6 @@ +#include "Mocks.hpp" #include - #include -#include "Mocks.hpp" #include #include @@ -27,104 +26,106 @@ struct MixNames { using MockIndexFS = MockFileSystem; using MockJsLibFS = MockFileSystem; -using MockMixFS = MockFileSystem; +using MockMixFS = MockFileSystem; const Scenario filesystemMulti{"filesystem::Multi can combine multiple FileSystems", [] { - given("IndexFS", [&] { - MockIndexFS indexFS("."); - when("opening known filenames", [&] { - then("should return corresponding File objects", [&] { - require(indexFS.open("index.html").has_value()); - require(indexFS.open("WebFront.js").has_value()); - require(indexFS.open("favicon.ico").has_value()); - }); - }); - when("opening unknown filenames", [&] { - then("should return nothing", [&] { - require(!indexFS.open("lib.js").has_value()); - require(!indexFS.open("bootstrap.js").has_value()); - require(!indexFS.open("dummy.file").has_value()); - }); - }); - }); - - given("JsLibFS", [&] { - MockJsLibFS jsFS("."); - when("opening known filenames", [&] { - then("should return file objects", [&] { - require(jsFS.open("lib.js").has_value()); - require(jsFS.open("bootstrap.js").has_value()); - }); - }); - when("opening unknown filenames", [&] { - then("should return nothing", [&] { - require(!jsFS.open("index.html").has_value()); - require(!jsFS.open("WebFront.js").has_value()); - require(!jsFS.open("favicon.ico").has_value()); - require(!jsFS.open("dummy.file").has_value()); - }); - }); - }); - - given("A Multi filesystem combining IndexFS and JsLibFS", [&] { - using MockIndexJsFS = fs::Multi; - MockIndexJsFS indexJsFS("."); - - when("opening known filenames", [&] { - then("should return file objects", [&] { - require(indexJsFS.open("lib.js").has_value()); - require(indexJsFS.open("bootstrap.js").has_value()); - require(indexJsFS.open("index.html").has_value()); - require(indexJsFS.open("WebFront.js").has_value()); - require(indexJsFS.open("favicon.ico").has_value()); - }); - }); - when("opening unknown filenames", [&] { - then("should return nothing", [&] { require(!indexJsFS.open("dummy.file").has_value()); }); - }); - }); - - given("A Multi filesystem combining IndexFS, JsLibFS and MixFS with names which can be served by multiple filesystems", [&] { - using FS = fs::Multi; - FS fs("testPath"); - MockIndexFS::openingsCounter = 0; - MockJsLibFS::openingsCounter = 0; - MockMixFS::openingsCounter = 0; - - require(MockIndexFS::root == "testPath"); - require(MockJsLibFS::root == "testPath"); - require(MockMixFS::root == "testPath"); - - when("opening ambiguous filenames", [&] { - then("First FS in the parameter list should serve the file", [&] { - require(fs.open("lib.js").has_value()); - require(MockIndexFS::openingsCounter == 0); - require(MockJsLibFS::openingsCounter == 1); - require(MockMixFS::openingsCounter == 0); - require(fs.open("lib2.js").has_value()); - require(MockIndexFS::openingsCounter == 0); - require(MockJsLibFS::openingsCounter == 1); - require(MockMixFS::openingsCounter == 1); - require(fs.open("bootstrap.js").has_value()); - require(MockIndexFS::openingsCounter == 0); - require(MockJsLibFS::openingsCounter == 2); - require(MockMixFS::openingsCounter == 1); - require(fs.open("index.html").has_value()); - require(MockIndexFS::openingsCounter == 1); - require(MockJsLibFS::openingsCounter == 2); - require(MockMixFS::openingsCounter == 1); - require(fs.open("WebFront.js").has_value()); - require(MockIndexFS::openingsCounter == 2); - require(MockJsLibFS::openingsCounter == 2); - require(MockMixFS::openingsCounter == 1); - require(fs.open("favicon.ico").has_value()); - require(MockIndexFS::openingsCounter == 3); - require(MockJsLibFS::openingsCounter == 2); - require(MockMixFS::openingsCounter == 1); - }); - }); - }); -}}; + given("IndexFS", [&] { + MockIndexFS indexFS("."); + when("opening known filenames", [&] { + then("should return corresponding File objects", [&] { + require(indexFS.open("index.html").has_value()); + require(indexFS.open("WebFront.js").has_value()); + require(indexFS.open("favicon.ico").has_value()); + }); + }); + when("opening unknown filenames", [&] { + then("should return nothing", [&] { + require(!indexFS.open("lib.js").has_value()); + require(!indexFS.open("bootstrap.js").has_value()); + require(!indexFS.open("dummy.file").has_value()); + }); + }); + }); + + given("JsLibFS", [&] { + MockJsLibFS jsFS("."); + when("opening known filenames", [&] { + then("should return file objects", [&] { + require(jsFS.open("lib.js").has_value()); + require(jsFS.open("bootstrap.js").has_value()); + }); + }); + when("opening unknown filenames", [&] { + then("should return nothing", [&] { + require(!jsFS.open("index.html").has_value()); + require(!jsFS.open("WebFront.js").has_value()); + require(!jsFS.open("favicon.ico").has_value()); + require(!jsFS.open("dummy.file").has_value()); + }); + }); + }); + + given("A Multi filesystem combining IndexFS and JsLibFS", [&] { + using MockIndexJsFS = fs::Multi; + MockIndexJsFS indexJsFS("."); + + when("opening known filenames", [&] { + then("should return file objects", [&] { + require(indexJsFS.open("lib.js").has_value()); + require(indexJsFS.open("bootstrap.js").has_value()); + require(indexJsFS.open("index.html").has_value()); + require(indexJsFS.open("WebFront.js").has_value()); + require(indexJsFS.open("favicon.ico").has_value()); + }); + }); + when("opening unknown filenames", [&] { + then("should return nothing", [&] { + require(!indexJsFS.open("dummy.file").has_value()); + }); + }); + }); + + given("A Multi filesystem combining IndexFS, JsLibFS and MixFS with names which can be served by multiple filesystems", [&] { + using FS = fs::Multi; + FS fs("testPath"); + MockIndexFS::openingsCounter = 0; + MockJsLibFS::openingsCounter = 0; + MockMixFS::openingsCounter = 0; + + require(MockIndexFS::root == "testPath"); + require(MockJsLibFS::root == "testPath"); + require(MockMixFS::root == "testPath"); + + when("opening ambiguous filenames", [&] { + then("First FS in the parameter list should serve the file", [&] { + require(fs.open("lib.js").has_value()); + require(MockIndexFS::openingsCounter == 0); + require(MockJsLibFS::openingsCounter == 1); + require(MockMixFS::openingsCounter == 0); + require(fs.open("lib2.js").has_value()); + require(MockIndexFS::openingsCounter == 0); + require(MockJsLibFS::openingsCounter == 1); + require(MockMixFS::openingsCounter == 1); + require(fs.open("bootstrap.js").has_value()); + require(MockIndexFS::openingsCounter == 0); + require(MockJsLibFS::openingsCounter == 2); + require(MockMixFS::openingsCounter == 1); + require(fs.open("index.html").has_value()); + require(MockIndexFS::openingsCounter == 1); + require(MockJsLibFS::openingsCounter == 2); + require(MockMixFS::openingsCounter == 1); + require(fs.open("WebFront.js").has_value()); + require(MockIndexFS::openingsCounter == 2); + require(MockJsLibFS::openingsCounter == 2); + require(MockMixFS::openingsCounter == 1); + require(fs.open("favicon.ico").has_value()); + require(MockIndexFS::openingsCounter == 3); + require(MockJsLibFS::openingsCounter == 2); + require(MockMixFS::openingsCounter == 1); + }); + }); + }); + }}; // "0123456789abcdefghi" packed like the generated asset headers: big-endian 64-bit words, the last // one padded with zeros. @@ -142,11 +143,11 @@ static string readAll(fs::File file, size_t bufferSize) { } const Scenario embeddedFile{"An embedded file reads the same bytes whatever the buffer size", [] { - for (const size_t bufferSize : array{1, 3, 7, 8, 13, 4096}) { - given("A buffer of " + to_string(bufferSize) + " bytes", [&] { - then("Embedded data reads back unchanged, across its 64-bit words", [&] { - require(readAll(fs::File{DigitsAndLetters{}}, bufferSize) == "0123456789abcdefghi"); - }); - }); - } -}}; + for (const size_t bufferSize : array{1, 3, 7, 8, 13, 4096}) { + given("A buffer of " + to_string(bufferSize) + " bytes", [&] { + then("Embedded data reads back unchanged, across its 64-bit words", [&] { + require(readAll(fs::File{DigitsAndLetters{}}, bufferSize) == "0123456789abcdefghi"); + }); + }); + } + }}; diff --git a/test/unit/FormsReflectionTests.cpp b/test/unit/FormsReflectionTests.cpp index 63e84d48..c7d31ce0 100644 --- a/test/unit/FormsReflectionTests.cpp +++ b/test/unit/FormsReflectionTests.cpp @@ -2,9 +2,9 @@ // descriptors that describe() reflects from annotations must equal the hand-written C++23 ones. #include "FormsHarness.hpp" #include "FormsSettings.hpp" -#include #include #include +#include #include #include @@ -36,56 +36,64 @@ struct Settings { }; } // namespace reflected -const Scenario reflectionProduces{"Reflection produces the descriptors written by hand", {"forms", "reflection"}, [] { - const auto reflectedDescription = forms::describe(); - const auto handWritten = forms_fixture::settingsDescription(); - then("names, labels, kinds, bounds and choices match, private members aside", [&] { - require(reflectedDescription.name == handWritten.name); - require(reflectedDescription.fields.size() == handWritten.fields.size()); - for (std::size_t i = 0; i < handWritten.fields.size(); ++i) { - const auto& r = reflectedDescription.fields[i]; - const auto& h = handWritten.fields[i]; - require(r.name == h.name); - require(r.label == h.label); - require(r.kind == h.kind); - require(r.range.has_value() == h.range.has_value()); - if (h.range) { - require(r.range->min == h.range->min); - require(r.range->max == h.range->max); +const Scenario reflectionProduces{ + "Reflection produces the descriptors written by hand", + {"forms", "reflection"}, + [] { + const auto reflectedDescription = forms::describe(); + const auto handWritten = forms_fixture::settingsDescription(); + then("names, labels, kinds, bounds and choices match, private members aside", [&] { + require(reflectedDescription.name == handWritten.name); + require(reflectedDescription.fields.size() == handWritten.fields.size()); + for (std::size_t i = 0; i < handWritten.fields.size(); ++i) { + const auto& r = reflectedDescription.fields[i]; + const auto& h = handWritten.fields[i]; + require(r.name == h.name); + require(r.label == h.label); + require(r.kind == h.kind); + require(r.range.has_value() == h.range.has_value()); + if (h.range) { + require(r.range->min == h.range->min); + require(r.range->max == h.range->max); + } + require(r.choices == h.choices); } - require(r.choices == h.choices); - } - }); - then("the TypeScript declaration is the one wf check verifies", [&] { - require(forms::typescriptDeclaration(reflectedDescription) == forms_fixture::settingsDeclaration); - }); - then("the accessors format and parse like the hand-written ones", [&] { - reflected::Settings settings; - auto& speed = reflectedDescription.fields[0]; - require(speed.read(settings) == "5"); - require(!speed.write(settings, "11")); - require(speed.write(settings, "10")); - require(settings.speed == 10); - require(reflectedDescription.fields[1].read(settings) == "0.25"); - require(reflectedDescription.fields[3].write(settings, "pulsar")); - require(settings.pattern == reflected::Pattern::pulsar); - }); -}}; + }); + then("the TypeScript declaration is the one wf check verifies", [&] { + require(forms::typescriptDeclaration(reflectedDescription) == forms_fixture::settingsDeclaration); + }); + then("the accessors format and parse like the hand-written ones", [&] { + reflected::Settings settings; + auto& speed = reflectedDescription.fields[0]; + require(speed.read(settings) == "5"); + require(!speed.write(settings, "11")); + require(speed.write(settings, "10")); + require(settings.speed == 10); + require(reflectedDescription.fields[1].read(settings) == "0.25"); + require(reflectedDescription.fields[3].write(settings, "pulsar")); + require(settings.pattern == reflected::Pattern::pulsar); + }); + } +}; -const Scenario reflectedForm{"A reflected form is the hand-written form", {"forms", "reflection", "dom"}, [] { - forms_fixture::Recorder byHand, byReflection; - auto handSettings = std::make_shared(); - auto reflectedSettings = std::make_shared(); - forms::form(byHand.doc, byHand.doc.island(), handSettings, forms_fixture::settingsDescription()); - auto form = forms::form(byReflection.doc, byReflection.doc.island(), reflectedSettings, forms::describe()); - then("both send the same batch", [&] { - require(byReflection.take() == byHand.take()); - }); - when("the browser edits the reflected form", [&] { - byReflection.event(form.control("density"), "input", "0.75"); - byReflection.event(form.control("density"), "input", "2"); - then("valid values reach the member and refused ones do not", [&] { - require(reflectedSettings->density == 0.75); +const Scenario reflectedForm{ + "A reflected form is the hand-written form", + {"forms", "reflection", "dom"}, + [] { + forms_fixture::Recorder byHand, byReflection; + auto handSettings = std::make_shared(); + auto reflectedSettings = std::make_shared(); + forms::form(byHand.doc, byHand.doc.island(), handSettings, forms_fixture::settingsDescription()); + auto form = forms::form(byReflection.doc, byReflection.doc.island(), reflectedSettings, forms::describe()); + then("both send the same batch", [&] { + require(byReflection.take() == byHand.take()); }); - }); -}}; + when("the browser edits the reflected form", [&] { + byReflection.event(form.control("density"), "input", "0.75"); + byReflection.event(form.control("density"), "input", "2"); + then("valid values reach the member and refused ones do not", [&] { + require(reflectedSettings->density == 0.75); + }); + }); + } +}; diff --git a/test/unit/FormsTests.cpp b/test/unit/FormsTests.cpp index b7170392..f395b679 100644 --- a/test/unit/FormsTests.cpp +++ b/test/unit/FormsTests.cpp @@ -1,7 +1,7 @@ #include "FormsHarness.hpp" #include "FormsSettings.hpp" -#include #include +#include // Without C++26 reflection the optional layer compiles to nothing. #include @@ -47,480 +47,510 @@ forms::Field& fieldNamed(forms::Description& description, st } // namespace const Scenario handWrittenDescriptors{"Hand-written descriptors parse and format the values of the browser", {"forms"}, [] { - auto description = forms_fixture::settingsDescription(); - Settings settings; - given("the descriptor of each member kind", [&] { - then("names, labels, kinds, bounds and choices are those written", [&] { - require(description.fields.size() == 5); - const auto& speed = fieldNamed(description, "speed"); - require(speed.label == "Speed"); - require(speed.kind == forms::Kind::integer); - require(speed.range->min == 1); - require(speed.range->max == 10); - require(fieldNamed(description, "density").kind == forms::Kind::number); - require(fieldNamed(description, "wrap").kind == forms::Kind::boolean); - require(fieldNamed(description, "pattern").kind == forms::Kind::choice); - require(fieldNamed(description, "pattern").choices == std::vector{"glider", "pulsar", "random"}); - require(fieldNamed(description, "pattern").label == "pattern"); - require(fieldNamed(description, "title").kind == forms::Kind::text); - requireNothrow([&] { forms::validate(description); }); - }); - then("read formats each member as the browser shows it, independently of the standard", [&] { - settings.density = 1.0; - require(fieldNamed(description, "speed").read(settings) == "5"); - require(fieldNamed(description, "density").read(settings) == "1"); - require(fieldNamed(description, "wrap").read(settings) == "true"); - require(fieldNamed(description, "pattern").read(settings) == "glider"); - require(fieldNamed(description, "title").read(settings) == "Life"); - }); - then("write accepts the values within bounds and choices", [&] { - require(fieldNamed(description, "speed").write(settings, "10")); - require(fieldNamed(description, "density").write(settings, "1e-1")); - require(fieldNamed(description, "wrap").write(settings, "false")); - require(fieldNamed(description, "pattern").write(settings, "pulsar")); - require(fieldNamed(description, "title").write(settings, "été")); - require(settings.speed == 10); - require(settings.density == 0.1); - require(!settings.wrap); - require(settings.pattern == Pattern::pulsar); - require(settings.title == "été"); - }); - then("write refuses malformed, out-of-range or unknown values and keeps the member", [&] { - for (auto text : {"11", "0", "7.5", "", "abc", "5 ", "99999999999999999999"}) - require(!fieldNamed(description, "speed").write(settings, text)); - for (auto text : {"1.5", "-0.1", "nan", "inf", "", "0,5", "1e400"}) - require(!fieldNamed(description, "density").write(settings, text)); - require(!fieldNamed(description, "wrap").write(settings, "on")); - require(!fieldNamed(description, "pattern").write(settings, "Glider")); - require(settings.speed == 5); - require(settings.density == 0.25); - require(settings.wrap); - require(settings.pattern == Pattern::glider); - }); - then("an integer accepts the other forms that an integer input reports", [&] { - require(fieldNamed(description, "speed").write(settings, "1e1")); - require(settings.speed == 10); - require(fieldNamed(description, "speed").write(settings, "5.0")); - require(settings.speed == 5); - for (auto text : {"5.5", "1e-1", "1e400", "-1e20"}) - require(!fieldNamed(description, "speed").write(settings, text)); - }); - }); - given("numbers that need every significant digit, and 64-bit integers beyond 2^53", [&] { - struct Precise { - double ratio{0.12345678901234567}; - std::int64_t count{}; - }; - static constexpr double ratioMax = 0.1234567890123456; - forms::Description precise{ - .name = "Precise", - .fields = {forms::field("ratio", &Precise::ratio, "Ratio", forms::Bounds{0, 0.5}), - forms::field("count", &Precise::count, "Count", forms::Bounds{0, 9007199254740992.0})} - }; - Precise object; - then("formatted values read back as the same number", [&] { - require(std::stod(precise.fields[0].read(object)) == object.ratio); - require(forms::detail::formatNumber(ratioMax) == "0.1234567890123456"); - require(forms::detail::formatNumber(0.1) == "0.1"); - require(forms::detail::formatNumber(0.1f) == "0.1"); - }); - then("an integer is compared exactly with its bounds", [&] { - require(precise.fields[1].write(object, "9007199254740992")); - require(!precise.fields[1].write(object, "9007199254740993")); - require(object.count == 9007199254740992); - require(!precise.fields[1].write(object, "-1")); - }); - then("a value that underflows is refused whatever the standard library, and an exact zero is accepted", [&] { - for (auto text : {"1e-320", "1e-400", "-2.5e-310"}) - require(!precise.fields[0].write(object, text)); - require(object.ratio == 0.12345678901234567); - require(precise.fields[0].write(object, "0e-400")); - require(object.ratio == 0); - }); - }); - given("float members whose decimal bounds are not exact in binary", [&] { - struct Gains { - float gain{}; - float wide{}; - }; - forms::Description gains{ - .name = "Gains", - .fields = {forms::field("gain", &Gains::gain, "Gain", forms::Bounds{0.1, 0.3}), - forms::field("wide", &Gains::wide, "Wide", forms::Bounds{-1e300, 1e300})} - }; - Gains object; - then("the bounds the form shows are accepted, and only what lies beyond them is refused", [&] { - require(gains.fields[0].write(object, "0.1")); - require(object.gain == 0.1f); - require(gains.fields[0].write(object, "0.3")); - require(object.gain == 0.3f); - for (auto text : {"0.0999", "0.3001", "1e-40"}) - require(!gains.fields[0].write(object, text)); - require(object.gain == 0.3f); - }); - then("bounds beyond the range of float accept every finite float", [&] { - require(gains.fields[1].write(object, "-3e38")); - require(gains.fields[1].write(object, "3e38")); - require(!gains.fields[1].write(object, "4e38")); - }); - }); -}}; + auto description = forms_fixture::settingsDescription(); + Settings settings; + given("the descriptor of each member kind", [&] { + then("names, labels, kinds, bounds and choices are those written", [&] { + require(description.fields.size() == 5); + const auto& speed = fieldNamed(description, "speed"); + require(speed.label == "Speed"); + require(speed.kind == forms::Kind::integer); + require(speed.range->min == 1); + require(speed.range->max == 10); + require(fieldNamed(description, "density").kind == forms::Kind::number); + require(fieldNamed(description, "wrap").kind == forms::Kind::boolean); + require(fieldNamed(description, "pattern").kind == forms::Kind::choice); + require(fieldNamed(description, "pattern").choices == std::vector{"glider", "pulsar", "random"}); + require(fieldNamed(description, "pattern").label == "pattern"); + require(fieldNamed(description, "title").kind == forms::Kind::text); + requireNothrow([&] { + forms::validate(description); + }); + }); + then("read formats each member as the browser shows it, independently of the standard", [&] { + settings.density = 1.0; + require(fieldNamed(description, "speed").read(settings) == "5"); + require(fieldNamed(description, "density").read(settings) == "1"); + require(fieldNamed(description, "wrap").read(settings) == "true"); + require(fieldNamed(description, "pattern").read(settings) == "glider"); + require(fieldNamed(description, "title").read(settings) == "Life"); + }); + then("write accepts the values within bounds and choices", [&] { + require(fieldNamed(description, "speed").write(settings, "10")); + require(fieldNamed(description, "density").write(settings, "1e-1")); + require(fieldNamed(description, "wrap").write(settings, "false")); + require(fieldNamed(description, "pattern").write(settings, "pulsar")); + require(fieldNamed(description, "title").write(settings, "été")); + require(settings.speed == 10); + require(settings.density == 0.1); + require(!settings.wrap); + require(settings.pattern == Pattern::pulsar); + require(settings.title == "été"); + }); + then("write refuses malformed, out-of-range or unknown values and keeps the member", [&] { + for (auto text : {"11", "0", "7.5", "", "abc", "5 ", "99999999999999999999"}) + require(!fieldNamed(description, "speed").write(settings, text)); + for (auto text : {"1.5", "-0.1", "nan", "inf", "", "0,5", "1e400"}) + require(!fieldNamed(description, "density").write(settings, text)); + require(!fieldNamed(description, "wrap").write(settings, "on")); + require(!fieldNamed(description, "pattern").write(settings, "Glider")); + require(settings.speed == 5); + require(settings.density == 0.25); + require(settings.wrap); + require(settings.pattern == Pattern::glider); + }); + then("an integer accepts the other forms that an integer input reports", [&] { + require(fieldNamed(description, "speed").write(settings, "1e1")); + require(settings.speed == 10); + require(fieldNamed(description, "speed").write(settings, "5.0")); + require(settings.speed == 5); + for (auto text : {"5.5", "1e-1", "1e400", "-1e20"}) + require(!fieldNamed(description, "speed").write(settings, text)); + }); + }); + given("numbers that need every significant digit, and 64-bit integers beyond 2^53", [&] { + struct Precise { + double ratio{0.12345678901234567}; + std::int64_t count{}; + }; + static constexpr double ratioMax = 0.1234567890123456; + forms::Description precise{ + .name = "Precise", + .fields = {forms::field("ratio", &Precise::ratio, "Ratio", forms::Bounds{0, 0.5}), + forms::field("count", &Precise::count, "Count", forms::Bounds{0, 9007199254740992.0})} + }; + Precise object; + then("formatted values read back as the same number", [&] { + require(std::stod(precise.fields[0].read(object)) == object.ratio); + require(forms::detail::formatNumber(ratioMax) == "0.1234567890123456"); + require(forms::detail::formatNumber(0.1) == "0.1"); + require(forms::detail::formatNumber(0.1f) == "0.1"); + }); + then("an integer is compared exactly with its bounds", [&] { + require(precise.fields[1].write(object, "9007199254740992")); + require(!precise.fields[1].write(object, "9007199254740993")); + require(object.count == 9007199254740992); + require(!precise.fields[1].write(object, "-1")); + }); + then("a value that underflows is refused whatever the standard library, and an exact zero is accepted", [&] { + for (auto text : {"1e-320", "1e-400", "-2.5e-310"}) + require(!precise.fields[0].write(object, text)); + require(object.ratio == 0.12345678901234567); + require(precise.fields[0].write(object, "0e-400")); + require(object.ratio == 0); + }); + }); + given("float members whose decimal bounds are not exact in binary", [&] { + struct Gains { + float gain{}; + float wide{}; + }; + forms::Description gains{ + .name = "Gains", + .fields = {forms::field("gain", &Gains::gain, "Gain", forms::Bounds{0.1, 0.3}), + forms::field("wide", &Gains::wide, "Wide", forms::Bounds{-1e300, 1e300})} + }; + Gains object; + then("the bounds the form shows are accepted, and only what lies beyond them is refused", [&] { + require(gains.fields[0].write(object, "0.1")); + require(object.gain == 0.1f); + require(gains.fields[0].write(object, "0.3")); + require(object.gain == 0.3f); + for (auto text : {"0.0999", "0.3001", "1e-40"}) + require(!gains.fields[0].write(object, text)); + require(object.gain == 0.3f); + }); + then("bounds beyond the range of float accept every finite float", [&] { + require(gains.fields[1].write(object, "-3e38")); + require(gains.fields[1].write(object, "3e38")); + require(!gains.fields[1].write(object, "4e38")); + }); + }); + }}; const Scenario descriptorsValidated{"Descriptors are validated before generation", {"forms"}, [] { - auto description = forms_fixture::settingsDescription(); - when("a name is not an identifier or is repeated", [&] { - auto badType = description; - badType.name = "Settings type"; - requireThrows([&] { forms::validate(badType); }); - auto badField = description; - badField.fields[0].name = "1speed"; - requireThrows([&] { forms::validate(badField); }); - auto repeated = description; - repeated.fields[1].name = "speed"; - requireThrows([&] { forms::typescriptDeclaration(repeated); }); - }); - when("the type name is one TypeScript refuses for an interface", [&] { - for (auto name : {"number", "string", "any", "boolean", "var", "let", "interface", "eval", "arguments"}) { - auto reserved = description; - reserved.name = name; - requireThrows([&] { forms::validate(reserved); }); - } - }); - when("an integer has fractional bounds, which would shift the browser's steps", [&] { - auto fractional = description; - fractional.fields[0].range = forms::Bounds{0.5, 10}; - requireThrows([&] { forms::validate(fractional); }); - auto number = description; - number.fields[1].range = forms::Bounds{0.5, 0.75}; - requireNothrow([&] { forms::validate(number); }); - }); - when("bounds are inverted, not finite or on a member that is not a number", [&] { - auto inverted = description; - inverted.fields[0].range = forms::Bounds{10, 1}; - requireThrows([&] { forms::validate(inverted); }); - auto infinite = description; - infinite.fields[0].range = forms::Bounds{0, std::numeric_limits::infinity()}; - requireThrows([&] { forms::validate(infinite); }); - auto text = description; - text.fields[4].range = forms::Bounds{0, 1}; - requireThrows([&] { forms::validate(text); }); - }); - when("choices are missing, repeated or given to another kind, or an accessor is missing", [&] { - auto none = description; - none.fields[3].choices = {}; - requireThrows([&] { forms::validate(none); }); - auto repeated = description; - repeated.fields[3].choices = {"glider", "glider"}; - requireThrows([&] { forms::validate(repeated); }); - auto stray = description; - stray.fields[4].choices = {"a"}; - requireThrows([&] { forms::validate(stray); }); - auto unreadable = description; - unreadable.fields[2].read = {}; - requireThrows([&] { forms::validate(unreadable); }); - }); -}}; + auto description = forms_fixture::settingsDescription(); + when("a name is not an identifier or is repeated", [&] { + auto badType = description; + badType.name = "Settings type"; + requireThrows([&] { + forms::validate(badType); + }); + auto badField = description; + badField.fields[0].name = "1speed"; + requireThrows([&] { + forms::validate(badField); + }); + auto repeated = description; + repeated.fields[1].name = "speed"; + requireThrows([&] { + forms::typescriptDeclaration(repeated); + }); + }); + when("the type name is one TypeScript refuses for an interface", [&] { + for (auto name : {"number", "string", "any", "boolean", "var", "let", "interface", "eval", "arguments"}) { + auto reserved = description; + reserved.name = name; + requireThrows([&] { + forms::validate(reserved); + }); + } + }); + when("an integer has fractional bounds, which would shift the browser's steps", [&] { + auto fractional = description; + fractional.fields[0].range = forms::Bounds{0.5, 10}; + requireThrows([&] { + forms::validate(fractional); + }); + auto number = description; + number.fields[1].range = forms::Bounds{0.5, 0.75}; + requireNothrow([&] { + forms::validate(number); + }); + }); + when("bounds are inverted, not finite or on a member that is not a number", [&] { + auto inverted = description; + inverted.fields[0].range = forms::Bounds{10, 1}; + requireThrows([&] { + forms::validate(inverted); + }); + auto infinite = description; + infinite.fields[0].range = forms::Bounds{0, std::numeric_limits::infinity()}; + requireThrows([&] { + forms::validate(infinite); + }); + auto text = description; + text.fields[4].range = forms::Bounds{0, 1}; + requireThrows([&] { + forms::validate(text); + }); + }); + when("choices are missing, repeated or given to another kind, or an accessor is missing", [&] { + auto none = description; + none.fields[3].choices = {}; + requireThrows([&] { + forms::validate(none); + }); + auto repeated = description; + repeated.fields[3].choices = {"glider", "glider"}; + requireThrows([&] { + forms::validate(repeated); + }); + auto stray = description; + stray.fields[4].choices = {"a"}; + requireThrows([&] { + forms::validate(stray); + }); + auto unreadable = description; + unreadable.fields[2].read = {}; + requireThrows([&] { + forms::validate(unreadable); + }); + }); + }}; -const Scenario descriptionGenerates{"A description generates the TypeScript declaration of its type", {"forms"}, [] { - given("the hand-written settings", [&] { - then("numbers, booleans, strings and the union of the choices are declared, with labels and bounds", [&] { - require(forms::typescriptDeclaration(forms_fixture::settingsDescription()) == forms_fixture::settingsDeclaration); +const Scenario descriptionGenerates{ + "A description generates the TypeScript declaration of its type", + {"forms"}, + [] { + given("the hand-written settings", [&] { + then("numbers, booleans, strings and the union of the choices are declared, with labels and bounds", [&] { + require(forms::typescriptDeclaration(forms_fixture::settingsDescription()) == forms_fixture::settingsDeclaration); + }); }); - }); - given("labels and choices that would break out of a comment or a string", [&] { - struct Odd { - int value{}; - bool flag{}; - }; - enum class Quote { plain, quoted }; - struct Choice { - Quote quote{}; - }; - forms::Description odd{ - .name = "Odd", - .fields = {forms::field("value", &Odd::value, "a */ b\nc"), forms::field("flag", &Odd::flag)} - }; - forms::Description choice{ - .name = "Choice", - .fields = {forms::choice("quote", &Choice::quote, {{"plain", Quote::plain}, {"say \"hi\"\\", Quote::quoted}})} - }; - then("comments and strings stay closed", [&] { - require(forms::typescriptDeclaration(odd) - == "export interface Odd {\n /** a *\\/ b c */\n readonly value: number;\n readonly flag: boolean;\n}\n"); - require(forms::typescriptDeclaration(choice) == "export interface Choice {\n readonly quote: \"plain\" | \"say \\\"hi\\\"\\\\\";\n}\n"); + given("labels and choices that would break out of a comment or a string", [&] { + struct Odd { + int value{}; + bool flag{}; + }; + enum class Quote { plain, quoted }; + struct Choice { + Quote quote{}; + }; + forms::Description odd{ + .name = "Odd", + .fields = {forms::field("value", &Odd::value, "a */ b\nc"), forms::field("flag", &Odd::flag)} + }; + forms::Description choice{ + .name = "Choice", + .fields = {forms::choice("quote", &Choice::quote, {{"plain", Quote::plain}, {"say \"hi\"\\", Quote::quoted}})} + }; + then("comments and strings stay closed", [&] { + require(forms::typescriptDeclaration(odd) + == "export interface Odd {\n /** a *\\/ b c */\n readonly value: number;\n readonly flag: boolean;\n}\n"); + require(forms::typescriptDeclaration(choice) == "export interface Choice {\n readonly quote: \"plain\" | \"say \\\"hi\\\"\\\\\";\n}\n"); + }); }); - }); -}}; + }}; -const Scenario formBuilt{"A form is built in a document and writes the object from browser events", {"forms", "dom"}, [] { - Recorder recorder; - auto settings = std::make_shared(); - auto root = recorder.doc.island(); - auto form = forms::form(recorder.doc, root, settings, forms_fixture::settingsDescription()); - auto ops = recorder.take(); - then("one batch holds a labelled input per member, with its value, type and bounds", [&] { - require(count(recorder, ops, "form") == 1); - require(count(recorder, ops, "label") == 5); - require(count(recorder, ops, "input") == 4); - require(count(recorder, ops, "select") == 1); - require(count(recorder, ops, "option") == 3); - using Attributes = std::map; - require(on(recorder, ops, form.control("speed"), msg::DomOp::attribute) - == Attributes{ - {"type", "number"}, - {"step", "1"}, - { "min", "1"}, - { "max", "10"}, - {"name", "speed"} - }); - require(on(recorder, ops, form.control("density"), msg::DomOp::attribute) - == Attributes{ - {"type", "number"}, - {"step", "any"}, - { "min", "0"}, - { "max", "1"}, - {"name", "density"} - }); - require(on(recorder, ops, form.control("wrap"), msg::DomOp::attribute) - == Attributes{ - {"type", "checkbox"}, - {"name", "wrap"} - }); - require(on(recorder, ops, form.control("title"), msg::DomOp::attribute) - == Attributes{ - {"type", "text"}, - {"name", "title"} - }); - require(on(recorder, ops, form.control("pattern"), msg::DomOp::attribute) - == Attributes{ - {"name", "pattern"} - }); - // The values are shown through the same properties as refresh(). - require(on(recorder, ops, form.control("speed"), msg::DomOp::property) - == Attributes{ - {"value", "5"} - }); - require(on(recorder, ops, form.control("density"), msg::DomOp::property) - == Attributes{ - {"value", "0.25"} - }); - require(on(recorder, ops, form.control("wrap"), msg::DomOp::property) - == Attributes{ - {"checked", "true"} - }); - require(on(recorder, ops, form.control("title"), msg::DomOp::property) - == Attributes{ - {"value", "Life"} - }); - require(on(recorder, ops, form.control("pattern"), msg::DomOp::property) - == Attributes{ - {"selectedIndex", "0"} - }); - require(on(recorder, ops, form.node(), msg::DomOp::listen) - == Attributes{ - {"submit", "1"} - }); - require(on(recorder, ops, form.control("speed"), msg::DomOp::listen) - == Attributes{ - {"input", "0"} - }); - require(on(recorder, ops, form.control("wrap"), msg::DomOp::listen) - == Attributes{ - {"change", "0"} - }); - require(on(recorder, ops, form.control("pattern"), msg::DomOp::listen) - == Attributes{ - {"change", "0"} +const Scenario formBuilt{ + "A form is built in a document and writes the object from browser events", + {"forms", "dom"}, + [] { + Recorder recorder; + auto settings = std::make_shared(); + auto root = recorder.doc.island(); + auto form = forms::form(recorder.doc, root, settings, forms_fixture::settingsDescription()); + auto ops = recorder.take(); + then("one batch holds a labelled input per member, with its value, type and bounds", [&] { + require(count(recorder, ops, "form") == 1); + require(count(recorder, ops, "label") == 5); + require(count(recorder, ops, "input") == 4); + require(count(recorder, ops, "select") == 1); + require(count(recorder, ops, "option") == 3); + using Attributes = std::map; + require(on(recorder, ops, form.control("speed"), msg::DomOp::attribute) + == Attributes{ + {"type", "number"}, + {"step", "1"}, + {"min", "1"}, + {"max", "10"}, + {"name", "speed"}}); + require(on(recorder, ops, form.control("density"), msg::DomOp::attribute) + == Attributes{ + {"type", "number"}, + {"step", "any"}, + {"min", "0"}, + {"max", "1"}, + {"name", "density"}}); + require(on(recorder, ops, form.control("wrap"), msg::DomOp::attribute) + == Attributes{ + {"type", "checkbox"}, + {"name", "wrap"}}); + require(on(recorder, ops, form.control("title"), msg::DomOp::attribute) + == Attributes{ + {"type", "text"}, + {"name", "title"}}); + require(on(recorder, ops, form.control("pattern"), msg::DomOp::attribute) + == Attributes{ + {"name", "pattern"}}); + // The values are shown through the same properties as refresh(). + require(on(recorder, ops, form.control("speed"), msg::DomOp::property) + == Attributes{ + {"value", "5"}}); + require(on(recorder, ops, form.control("density"), msg::DomOp::property) + == Attributes{ + {"value", "0.25"}}); + require(on(recorder, ops, form.control("wrap"), msg::DomOp::property) + == Attributes{ + {"checked", "true"}}); + require(on(recorder, ops, form.control("title"), msg::DomOp::property) + == Attributes{ + {"value", "Life"}}); + require(on(recorder, ops, form.control("pattern"), msg::DomOp::property) + == Attributes{ + {"selectedIndex", "0"}}); + require(on(recorder, ops, form.node(), msg::DomOp::listen) + == Attributes{ + {"submit", "1"}}); + require(on(recorder, ops, form.control("speed"), msg::DomOp::listen) + == Attributes{ + {"input", "0"}}); + require(on(recorder, ops, form.control("wrap"), msg::DomOp::listen) + == Attributes{ + {"change", "0"}}); + require(on(recorder, ops, form.control("pattern"), msg::DomOp::listen) + == Attributes{ + {"change", "0"}}); + require(ops.back().code == msg::DomOp::append); + require(ops.back().a == root.id()); + require(ops.back().b == form.node().id()); + }); + when("the browser sends valid values", [&] { + std::vector changed; + form.onChange([&](std::string_view name) { + changed.emplace_back(name); + }); + recorder.event(form.control("speed"), "input", "8"); + recorder.event(form.control("wrap"), "change", "false"); + recorder.event(form.control("pattern"), "change", "random"); + recorder.event(form.control("title"), "input", "Gosper"); + then("the members change and the application is told which", [&] { + require(settings->speed == 8); + require(!settings->wrap); + require(settings->pattern == Pattern::random); + require(settings->title == "Gosper"); + require(changed == std::vector{"speed", "wrap", "pattern", "title"}); + require(recorder.take().empty()); + }); }); - require(ops.back().code == msg::DomOp::append); - require(ops.back().a == root.id()); - require(ops.back().b == form.node().id()); - }); - when("the browser sends valid values", [&] { - std::vector changed; - form.onChange([&](std::string_view name) { - changed.emplace_back(name); + when("the change callback replaces itself while it runs", [&] { + std::vector changed; + auto tag = std::make_shared("first"); + form.onChange([&, tag](std::string_view name) { + form.onChange([&](std::string_view next) { + changed.emplace_back("second:" + std::string(next)); + }); + // The replaced callback still runs, with its captures alive. + changed.emplace_back(*tag + ":" + std::string(name)); + }); + recorder.event(form.control("speed"), "input", "8"); + recorder.event(form.control("speed"), "input", "7"); + then("the first call completes and the next change reaches the new callback", [&] { + require(changed == std::vector{"first:speed", "second:speed"}); + }); }); - recorder.event(form.control("speed"), "input", "8"); - recorder.event(form.control("wrap"), "change", "false"); - recorder.event(form.control("pattern"), "change", "random"); - recorder.event(form.control("title"), "input", "Gosper"); - then("the members change and the application is told which", [&] { - require(settings->speed == 8); - require(!settings->wrap); - require(settings->pattern == Pattern::random); - require(settings->title == "Gosper"); - require(changed == std::vector{"speed", "wrap", "pattern", "title"}); - require(recorder.take().empty()); + when("the browser sends a refused value, then a valid one", [&] { + recorder.event(form.control("speed"), "input", "42"); + auto refused = recorder.take(); + recorder.event(form.control("speed"), "input", "42"); + auto repeated = recorder.take(); + recorder.event(form.control("speed"), "input", "3"); + auto accepted = recorder.take(); + then("the member keeps its value while the input is marked invalid", [&] { + require(on(recorder, refused, form.control("speed"), msg::DomOp::attribute) + == std::map{ + {"aria-invalid", "true"}}); + require(repeated.empty()); + require(accepted.size() == 1); + require(accepted[0].code == msg::DomOp::unsetAttribute); + require(recorder.name(accepted[0].b) == "aria-invalid"); + require(settings->speed == 3); + }); }); - }); - when("the change callback replaces itself while it runs", [&] { - std::vector changed; - auto tag = std::make_shared("first"); - form.onChange([&, tag](std::string_view name) { - form.onChange([&](std::string_view next) { - changed.emplace_back("second:" + std::string(next)); + when("C++ changes the object and refreshes the form", [&] { + settings->speed = 9; + settings->wrap = false; + settings->pattern = Pattern::pulsar; + settings->density = 0.5; + form.refresh(); + auto refreshed = recorder.take(); + then("each input shows the new value through its property", [&] { + using Properties = std::map; + require(on(recorder, refreshed, form.control("speed"), msg::DomOp::property) + == Properties{ + {"value", "9"}}); + require(on(recorder, refreshed, form.control("density"), msg::DomOp::property) + == Properties{ + {"value", "0.5"}}); + require(on(recorder, refreshed, form.control("wrap"), msg::DomOp::property) + == Properties{ + {"checked", "false"}}); + require(on(recorder, refreshed, form.control("pattern"), msg::DomOp::property) + == Properties{ + {"selectedIndex", "1"}}); }); - // The replaced callback still runs, with its captures alive. - changed.emplace_back(*tag + ":" + std::string(name)); }); - recorder.event(form.control("speed"), "input", "8"); - recorder.event(form.control("speed"), "input", "7"); - then("the first call completes and the next change reaches the new callback", [&] { - require(changed == std::vector{"first:speed", "second:speed"}); + when("the form is removed after its handle is gone", [&] { + auto other = std::make_shared(); + dom::Node node; + { + auto second = forms::form(recorder.doc, root, other, forms_fixture::settingsDescription()); + node = second.node(); + } + require(other.use_count() == 2); // The listeners keep the form, and the object, alive. + node.remove(); + then("its listeners, and their share of the object, are released", [&] { + require(other.use_count() == 1); + require(!node.valid()); + }); }); - }); - when("the browser sends a refused value, then a valid one", [&] { - recorder.event(form.control("speed"), "input", "42"); - auto refused = recorder.take(); - recorder.event(form.control("speed"), "input", "42"); - auto repeated = recorder.take(); - recorder.event(form.control("speed"), "input", "3"); - auto accepted = recorder.take(); - then("the member keeps its value while the input is marked invalid", [&] { - require(on(recorder, refused, form.control("speed"), msg::DomOp::attribute) - == std::map{ - {"aria-invalid", "true"} + when("a choice member holds a value missing from its choices", [&] { + auto unlisted = std::make_shared(); + unlisted->pattern = static_cast(42); + auto other = forms::form(recorder.doc, root, unlisted, forms_fixture::settingsDescription()); + auto built = recorder.take(); + then("no option is selected, as after a refresh, instead of the first one", [&] { + require(std::ranges::none_of(built, [&](const auto& op) { + return op.code == msg::DomOp::attribute && recorder.name(op.b) == "selected"; + })); + require(on(recorder, built, other.control("pattern"), msg::DomOp::property) + == std::map{ + {"selectedIndex", "-1"}}); }); - require(repeated.empty()); - require(accepted.size() == 1); - require(accepted[0].code == msg::DomOp::unsetAttribute); - require(recorder.name(accepted[0].b) == "aria-invalid"); - require(settings->speed == 3); }); - }); - when("C++ changes the object and refreshes the form", [&] { - settings->speed = 9; - settings->wrap = false; - settings->pattern = Pattern::pulsar; - settings->density = 0.5; - form.refresh(); - auto refreshed = recorder.take(); - then("each input shows the new value through its property", [&] { - using Properties = std::map; - require(on(recorder, refreshed, form.control("speed"), msg::DomOp::property) - == Properties{ - {"value", "9"} + when("an accessor throws while a form is built", [&] { + auto failing = forms_fixture::settingsDescription(); + failing.fields[2].read = [](const Settings&) -> std::string { + throw std::runtime_error("unreadable"); + }; + const auto nodes = recorder.state->nodes.size(); + const auto listeners = recorder.state->listeners.size(); + auto other = std::make_shared(); + requireThrows([&] { + forms::form(recorder.doc, root, other, failing); }); - require(on(recorder, refreshed, form.control("density"), msg::DomOp::property) - == Properties{ - {"value", "0.5"} + then("the elements already created are removed with their listeners and their share of the object", [&] { + require(recorder.state->nodes.size() == nodes); + require(recorder.state->listeners.size() == listeners); + require(other.use_count() == 1); }); - require(on(recorder, refreshed, form.control("wrap"), msg::DomOp::property) - == Properties{ - {"checked", "false"} + }); + when("onChange is called from another thread", [&] { + bool refused = false; + std::thread worker([&] { + try { + form.onChange([](std::string_view) {}); + } catch (const std::logic_error&) { + refused = true; + } }); - require(on(recorder, refreshed, form.control("pattern"), msg::DomOp::property) - == Properties{ - {"selectedIndex", "1"} + worker.join(); + then("it throws like the other methods instead of racing with event dispatch", [&] { + require(refused); }); }); - }); - when("the form is removed after its handle is gone", [&] { - auto other = std::make_shared(); - dom::Node node; - { - auto second = forms::form(recorder.doc, root, other, forms_fixture::settingsDescription()); - node = second.node(); - } - require(other.use_count() == 2); // The listeners keep the form, and the object, alive. - node.remove(); - then("its listeners, and their share of the object, are released", [&] { - require(other.use_count() == 1); - require(!node.valid()); - }); - }); - when("a choice member holds a value missing from its choices", [&] { - auto unlisted = std::make_shared(); - unlisted->pattern = static_cast(42); - auto other = forms::form(recorder.doc, root, unlisted, forms_fixture::settingsDescription()); - auto built = recorder.take(); - then("no option is selected, as after a refresh, instead of the first one", [&] { - require(std::ranges::none_of(built, [&](const auto& op) { - return op.code == msg::DomOp::attribute && recorder.name(op.b) == "selected"; - })); - require(on(recorder, built, other.control("pattern"), msg::DomOp::property) - == std::map{ - {"selectedIndex", "-1"} + when("a field name is unknown or the description is invalid", [&] { + requireThrows([&] { + form.control("missing"); }); + auto invalid = forms_fixture::settingsDescription(); + invalid.name = ""; + recorder.take(); + requireThrows([&] { + forms::form(recorder.doc, root, settings, invalid); + }); + requireThrows([&] { + forms::form(recorder.doc, root, std::shared_ptr{}, forms_fixture::settingsDescription()); + }); + require(recorder.take().empty()); }); - }); - when("an accessor throws while a form is built", [&] { - auto failing = forms_fixture::settingsDescription(); - failing.fields[2].read = [](const Settings&) -> std::string { - throw std::runtime_error("unreadable"); - }; - const auto nodes = recorder.state->nodes.size(); - const auto listeners = recorder.state->listeners.size(); - auto other = std::make_shared(); - requireThrows([&] { forms::form(recorder.doc, root, other, failing); }); - then("the elements already created are removed with their listeners and their share of the object", [&] { - require(recorder.state->nodes.size() == nodes); - require(recorder.state->listeners.size() == listeners); - require(other.use_count() == 1); - }); - }); - when("onChange is called from another thread", [&] { - bool refused = false; - std::thread worker([&] { - try { - form.onChange([](std::string_view) { }); - } catch (const std::logic_error&) { - refused = true; - } - }); - worker.join(); - then("it throws like the other methods instead of racing with event dispatch", [&] { - require(refused); - }); - }); - when("a field name is unknown or the description is invalid", [&] { - requireThrows([&] { form.control("missing"); }); - auto invalid = forms_fixture::settingsDescription(); - invalid.name = ""; - recorder.take(); - requireThrows([&] { forms::form(recorder.doc, root, settings, invalid); }); - requireThrows([&] { forms::form(recorder.doc, root, std::shared_ptr{}, forms_fixture::settingsDescription()); }); - require(recorder.take().empty()); - }); -}}; + } +}; -const Scenario inspectorShows{"An inspector shows an object and updates only what changed", {"forms", "dom"}, [] { - Recorder recorder; - auto settings = std::make_shared(); - auto inspector = forms::inspector(recorder.doc, recorder.doc.island(), settings, forms_fixture::settingsDescription()); - auto ops = recorder.take(); - then("a table row per member holds its label and its value as text", [&] { - require(count(recorder, ops, "table") == 1); - require(count(recorder, ops, "tr") == 5); - std::vector texts; - for (const auto& op : ops) - if (op.code == msg::DomOp::text) - texts.push_back(op.value); - require(texts == std::vector{"Speed", "5", "Initial density", "0.25", "Wrap around edges", "true", "pattern", "glider", "title", "Life"}); - }); - when("C++ changes one member and refreshes twice", [&] { - settings->title = "Gun"; - inspector.refresh(); - auto first = recorder.take(); - inspector.refresh(); - then("one text changes once", [&] { - require(first.size() == 1); - require(first[0].code == msg::DomOp::setText); - require(first[0].a == inspector.value("title").id()); - require(first[0].value == "Gun"); - require(recorder.take().empty()); +const Scenario inspectorShows{ + "An inspector shows an object and updates only what changed", + {"forms", "dom"}, + [] { + Recorder recorder; + auto settings = std::make_shared(); + auto inspector = forms::inspector(recorder.doc, recorder.doc.island(), settings, forms_fixture::settingsDescription()); + auto ops = recorder.take(); + then("a table row per member holds its label and its value as text", [&] { + require(count(recorder, ops, "table") == 1); + require(count(recorder, ops, "tr") == 5); + std::vector texts; + for (const auto& op : ops) + if (op.code == msg::DomOp::text) + texts.push_back(op.value); + require(texts + == std::vector{"Speed", "5", "Initial density", "0.25", "Wrap around edges", "true", "pattern", "glider", "title", "Life"}); + }); + when("C++ changes one member and refreshes twice", [&] { + settings->title = "Gun"; + inspector.refresh(); + auto first = recorder.take(); + inspector.refresh(); + then("one text changes once", [&] { + require(first.size() == 1); + require(first[0].code == msg::DomOp::setText); + require(first[0].a == inspector.value("title").id()); + require(first[0].value == "Gun"); + require(recorder.take().empty()); + }); }); - }); - when("an accessor throws while another inspector is built", [&] { - auto failing = forms_fixture::settingsDescription(); - failing.fields[3].read = [](const Settings&) -> std::string { - throw std::runtime_error("unreadable"); - }; - const auto nodes = recorder.state->nodes.size(); - requireThrows([&] { forms::inspector(recorder.doc, recorder.doc.island(), settings, failing); }); - then("its elements are removed", [&] { - require(recorder.state->nodes.size() == nodes); + when("an accessor throws while another inspector is built", [&] { + auto failing = forms_fixture::settingsDescription(); + failing.fields[3].read = [](const Settings&) -> std::string { + throw std::runtime_error("unreadable"); + }; + const auto nodes = recorder.state->nodes.size(); + requireThrows([&] { + forms::inspector(recorder.doc, recorder.doc.island(), settings, failing); + }); + then("its elements are removed", [&] { + require(recorder.state->nodes.size() == nodes); + }); }); - }); -}}; + } +}; diff --git a/test/unit/FrontendContractTests.cpp b/test/unit/FrontendContractTests.cpp index 31adfd39..a23a739f 100644 --- a/test/unit/FrontendContractTests.cpp +++ b/test/unit/FrontendContractTests.cpp @@ -1,7 +1,7 @@ #include "Mocks.hpp" -#include #include "TemporaryDirectory.hpp" #include +#include #include #include @@ -13,8 +13,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -75,12 +75,12 @@ class ContractIoContext { state->stopped = true; state->changed.notify_all(); } - void restart() { } + void restart() {} }; struct ContractAcceptor : networking::SocketBaseMock { - explicit ContractAcceptor(const ContractIoContext&) { } - void open(auto) { } + explicit ContractAcceptor(const ContractIoContext&) {} + void open(auto) {} bool is_open() const { return true; } @@ -96,7 +96,7 @@ enum class Failure { none, standard, nonStandard, beforeWindow }; template struct ContractFrontend { static constexpr frontend::Action action = onReturn; - static void initialize() { } + static void initialize() {} static void open(std::string_view, std::string_view) { const auto state = ContractIoContext::current; std::unique_lock lock(state->mutex); @@ -122,7 +122,7 @@ struct ContractFrontend { template void checkSession() { using ContractApp = BasicWFWithFrontend, ContractFrontend>; - ContractApp app; + ContractApp app; const auto state = ContractIoContext::current; std::exception_ptr error; std::jthread caller([&] { @@ -169,18 +169,28 @@ void checkSession() { } else { require(error); if constexpr (failure == Failure::standard) - checkThrows([&] { std::rethrow_exception(error); }, equals("frontend startup failed")); + checkThrows( + [&] { + std::rethrow_exception(error); + }, + equals("frontend startup failed")); else - checkThrows([&] { std::rethrow_exception(error); }); + checkThrows([&] { + std::rethrow_exception(error); + }); } } template void checkStartupFailure() { using ContractApp = BasicWFWithFrontend, ContractFrontend>; - ContractApp app; - const auto state = ContractIoContext::current; - requireThrows([&] { app.show(); }, equals("frontend failed before window creation")); + ContractApp app; + const auto state = ContractIoContext::current; + requireThrows( + [&] { + app.show(); + }, + equals("frontend failed before window creation")); std::lock_guard lock(state->mutex); check(state->frontendEntered); check(!state->windowCreated); @@ -193,77 +203,77 @@ void checkStartupFailure() { } // namespace const Scenario embeddedFrontend{"An embedded frontend blocks show until closure and completes the server loop", [] { - given("a window held open while its server loop runs", [&] { - when("show opens the window and the window is closed", [&] { - then("show runs open on its calling thread and waits for shutdown after closure", [&] { - checkSession(); - }); - }); - }); -}}; + given("a window held open while its server loop runs", [&] { + when("show opens the window and the window is closed", [&] { + then("show runs open on its calling thread and waits for shutdown after closure", [&] { + checkSession(); + }); + }); + }); + }}; const Scenario launchingFrontend{"A launching frontend leaves the server loop running after show returns", [] { - given("a frontend with keepServerRunning", [&] { - when("show opens the frontend and open returns", [&] { - then("the server remains active until explicitly stopped", [&] { - checkSession(); - }); - }); - }); -}}; + given("a frontend with keepServerRunning", [&] { + when("show opens the frontend and open returns", [&] { + then("the server remains active until explicitly stopped", [&] { + checkSession(); + }); + }); + }); + }}; const Scenario frontendExceptions{"Frontend exceptions propagate only after the server loop completes", [] { - given("an embedded frontend that throws", [&] { - when("open fails during window cleanup", [&] { - then("the original diagnostic survives shutdown", [&] { - checkSession(); - }); - }); - }); - given("a launching frontend that throws", [&] { - when("open fails before returning", [&] { - then("its action does not prevent shutdown", [&] { - checkSession(); - }); - }); - }); - given("a frontend throwing a non-standard exception", [&] { - when("open throws during window cleanup", [&] { - then("shutdown also precedes propagation of that exception", [&] { - checkSession(); - }); - }); - }); -}}; + given("an embedded frontend that throws", [&] { + when("open fails during window cleanup", [&] { + then("the original diagnostic survives shutdown", [&] { + checkSession(); + }); + }); + }); + given("a launching frontend that throws", [&] { + when("open fails before returning", [&] { + then("its action does not prevent shutdown", [&] { + checkSession(); + }); + }); + }); + given("a frontend throwing a non-standard exception", [&] { + when("open throws during window cleanup", [&] { + then("shutdown also precedes propagation of that exception", [&] { + checkSession(); + }); + }); + }); + }}; const Scenario frontendStartup{"A frontend startup failure before window creation completes the server loop", [] { - given("a frontend that fails before creating a window", [&] { - when("show selects an embedded frontend", [&] { - then("the server stops before the startup error propagates", [&] { - checkStartupFailure(); - }); - }); - when("show selects a launching frontend", [&] { - then("the same shutdown guarantee holds", [&] { - checkStartupFailure(); - }); - }); - }); -}}; + given("a frontend that fails before creating a window", [&] { + when("show selects an embedded frontend", [&] { + then("the server stops before the startup error propagates", [&] { + checkStartupFailure(); + }); + }); + when("show selects a launching frontend", [&] { + then("the same shutdown guarantee holds", [&] { + checkStartupFailure(); + }); + }); + }); + }}; namespace { struct WindowRecorder { - static inline WindowOptions received; + static inline WindowOptions received; static constexpr frontend::Action action = frontend::Action::keepServerRunning; - static void initialize() { } - static void open(std::string_view, std::string_view) { } - static void open(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions& window) { + static void initialize() {} + static void open(std::string_view, std::string_view) {} + static void open(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions& window) { received = window; } }; WindowOptions windowReceivedBy(WebFrontConfig config) { - using ContractApp = BasicWFWithFrontend, WindowRecorder>; + using ContractApp = BasicWFWithFrontend, WindowRecorder>; WindowRecorder::received = {.title = "unset", .width = -1, .height = -1}; ContractApp app(std::move(config)); app.show(); @@ -289,100 +299,103 @@ WindowOptions windowReceivedByDeveloperApp(WebFrontConfig config) { } // namespace const Scenario developerBackground{"The developer environment gives its own dark colour to a window that has none", [] { - given("a developer application without a window colour", [&] { - then("the view does not flash its toolkit's white between the bootstrap and the project's page", [&] { - check(windowReceivedByDeveloperApp({}).background == "#141821"); - }); - }); - given("a developer application with a window colour", [&] { - then("the application's colour is kept", [&] { - check(windowReceivedByDeveloperApp({.window = {.background = "#ffffff"}}).background == "#ffffff"); - }); - }); -}}; + given("a developer application without a window colour", [&] { + then("the view does not flash its toolkit's white between the bootstrap and the project's page", [&] { + check(windowReceivedByDeveloperApp({}).background == "#141821"); + }); + }); + given("a developer application with a window colour", [&] { + then("the application's colour is kept", [&] { + check(windowReceivedByDeveloperApp({.window = {.background = "#ffffff"}}).background == "#ffffff"); + }); + }); + }}; const Scenario windowBackground{"The window background is a CSS hexadecimal colour that is never guessed", [] { - given("valid colours", [&] { - then("short, long and translucent forms are read", [&] { - const auto white = frontend::detail::parseBackground("#fff"); - const auto navy = frontend::detail::parseBackground("#101c1d"); - const auto clear = frontend::detail::parseBackground("#00000080"); - require(white && navy && clear); - check((*white)[0] == 1.0f && (*white)[3] == 1.0f); - check((*navy)[0] == 16.0f / 255.0f && (*navy)[1] == 28.0f / 255.0f && (*navy)[2] == 29.0f / 255.0f && (*navy)[3] == 1.0f); - check((*clear)[3] == 128.0f / 255.0f); - }); - }); - given("a translucent colour for CEF", [&] { - then("any non-zero alpha is opaque and only a zero alpha stays transparent, the two values CEF accepts", [&] { - check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d80")) == 0xFF101C1Du); - check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d01")) == 0xFF101C1Du); - check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d")) == 0xFF101C1Du); - check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d00")) == 0x00101C1Du); - }); - }); - given("invalid or empty text", [&] { - then("nothing is returned, so the toolkit's default stays", [&] { - check(!frontend::detail::parseBackground("")); - check(!frontend::detail::parseBackground("red")); - check(!frontend::detail::parseBackground("#12")); - check(!frontend::detail::parseBackground("#12345")); - check(!frontend::detail::parseBackground("#ggg")); - }); - }); - given("a default configuration", [&] { - then("the page keeps its media; an application without media opts out to skip GStreamer's initialization", [&] { - check(WindowOptions{}.media); - check(!windowReceivedBy({.window = {.media = false}}).media); - }); - }); - given("a configuration with a background", [&] { - const auto window = windowReceivedBy({.window = {.background = "#101c1d"}}); - then("the frontend receives it unchanged", [&] { - check(window.background == "#101c1d"); - }); - }); -}}; + given("valid colours", [&] { + then("short, long and translucent forms are read", [&] { + const auto white = frontend::detail::parseBackground("#fff"); + const auto navy = frontend::detail::parseBackground("#101c1d"); + const auto clear = frontend::detail::parseBackground("#00000080"); + require(white && navy && clear); + check((*white)[0] == 1.0f && (*white)[3] == 1.0f); + check((*navy)[0] == 16.0f / 255.0f && (*navy)[1] == 28.0f / 255.0f && (*navy)[2] == 29.0f / 255.0f + && (*navy)[3] == 1.0f); + check((*clear)[3] == 128.0f / 255.0f); + }); + }); + given("a translucent colour for CEF", [&] { + then("any non-zero alpha is opaque and only a zero alpha stays transparent, the two values CEF accepts", [&] { + check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d80")) == 0xFF101C1Du); + check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d01")) == 0xFF101C1Du); + check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d")) == 0xFF101C1Du); + check(frontend::detail::cefBackground(*frontend::detail::parseBackground("#101c1d00")) == 0x00101C1Du); + }); + }); + given("invalid or empty text", [&] { + then("nothing is returned, so the toolkit's default stays", [&] { + check(!frontend::detail::parseBackground("")); + check(!frontend::detail::parseBackground("red")); + check(!frontend::detail::parseBackground("#12")); + check(!frontend::detail::parseBackground("#12345")); + check(!frontend::detail::parseBackground("#ggg")); + }); + }); + given("a default configuration", [&] { + then("the page keeps its media; an application without media opts out to skip GStreamer's initialization", [&] { + check(WindowOptions{}.media); + check(!windowReceivedBy({.window = {.media = false}}).media); + }); + }); + given("a configuration with a background", [&] { + const auto window = windowReceivedBy({.window = {.background = "#101c1d"}}); + then("the frontend receives it unchanged", [&] { + check(window.background == "#101c1d"); + }); + }); + }}; const Scenario applicationChooses{"The application chooses the title and the size of the embedded window", [] { - given("a configuration with a window title and size", [&] { - const auto window = windowReceivedBy({.window = {.title = "SiliconForge", .width = 640, .height = 480}}); - then("the frontend receives them unchanged", [&] { - check(window.title == "SiliconForge"); - check(window.width == 640); - check(window.height == 480); - }); - }); - given("a default configuration", [&] { - const auto window = windowReceivedBy({}); - then("the frontend receives an empty title and the default size", [&] { - check(window.title.empty()); - check(window.width == 1200); - check(window.height == 800); - }); - then("the effective title is the executable's name, never the former constant", [&] { - const auto effective = frontend::detail::resolveWindow(window); - check(!effective.title.empty()); - check(effective.title != "WebFront Application"); - }); - }); - given("an invalid size and an explicit title", [&] { - const auto effective = frontend::detail::resolveWindow({.title = "T", .width = 0, .height = -5}); - then("the title is kept and the size falls back to the default", [&] { - check(effective.title == "T"); - check(effective.width == 1200); - check(effective.height == 800); - }); - }); -}}; + given("a configuration with a window title and size", [&] { + const auto window = windowReceivedBy({ + .window = {.title = "SiliconForge", .width = 640, .height = 480} + }); + then("the frontend receives them unchanged", [&] { + check(window.title == "SiliconForge"); + check(window.width == 640); + check(window.height == 480); + }); + }); + given("a default configuration", [&] { + const auto window = windowReceivedBy({}); + then("the frontend receives an empty title and the default size", [&] { + check(window.title.empty()); + check(window.width == 1200); + check(window.height == 800); + }); + then("the effective title is the executable's name, never the former constant", [&] { + const auto effective = frontend::detail::resolveWindow(window); + check(!effective.title.empty()); + check(effective.title != "WebFront Application"); + }); + }); + given("an invalid size and an explicit title", [&] { + const auto effective = frontend::detail::resolveWindow({.title = "T", .width = 0, .height = -5}); + then("the title is kept and the size falls back to the default", [&] { + check(effective.title == "T"); + check(effective.width == 1200); + check(effective.height == 800); + }); + }); + }}; namespace { struct LaunchRecordingFrontend { static constexpr frontend::Action action = frontend::Action::keepServerRunning; static inline ViewLaunch received{}; static inline int opens = 0; - static void initialize() { } - static void open(std::string_view, std::string_view) { } + static void initialize() {} + static void open(std::string_view, std::string_view) {} static void open(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions&, const ViewLaunch& launch) { received = launch; ++opens; @@ -391,36 +404,36 @@ struct LaunchRecordingFrontend { } // namespace const Scenario frontendAccepts{"A frontend that accepts a view launch receives this application's secret and origin", [] { - given("a frontend with the richest open overload", [&] { - using LaunchApp = BasicWFWithFrontend, LaunchRecordingFrontend>; - LaunchApp first; - LaunchApp second; - when("each application opens its window", [&] { - LaunchRecordingFrontend::opens = 0; - first.openWindow("index.html"); - const auto firstLaunch = LaunchRecordingFrontend::received; - second.openWindow("index.html"); - const auto secondLaunch = LaunchRecordingFrontend::received; - then("the frontend gets a 64-character secret and the origin it must expose it to", [&] { - require(LaunchRecordingFrontend::opens == 2); - check(firstLaunch.secret.size() == 64); - check(firstLaunch.origin == "http://127.0.0.1:" + std::string(first.port())); - }); - then("every application has its own secret", [&] { - check(firstLaunch.secret != secondLaunch.secret); - }); - }); - }); -}}; + given("a frontend with the richest open overload", [&] { + using LaunchApp = BasicWFWithFrontend, LaunchRecordingFrontend>; + LaunchApp first; + LaunchApp second; + when("each application opens its window", [&] { + LaunchRecordingFrontend::opens = 0; + first.openWindow("index.html"); + const auto firstLaunch = LaunchRecordingFrontend::received; + second.openWindow("index.html"); + const auto secondLaunch = LaunchRecordingFrontend::received; + then("the frontend gets a 64-character secret and the origin it must expose it to", [&] { + require(LaunchRecordingFrontend::opens == 2); + check(firstLaunch.secret.size() == 64); + check(firstLaunch.origin == "http://127.0.0.1:" + std::string(first.port())); + }); + then("every application has its own secret", [&] { + check(firstLaunch.secret != secondLaunch.secret); + }); + }); + }); + }}; // Host integration (#567): a launch that returns, a close request from the host and an application on its own thread. namespace { struct LaunchRecorder { - static inline std::string url; - static inline std::thread::id thread; - static inline bool fail = false; + static inline std::string url; + static inline std::thread::id thread; + static inline bool fail = false; static constexpr frontend::Action action = frontend::Action::keepServerRunning; - static void initialize() { } + static void initialize() {} static void open(std::string_view, std::string_view) { throw std::logic_error("start() must not call open()"); } @@ -482,10 +495,10 @@ struct SlowCloseFrontend : ContractFrontend struct SharedWindowFrontend : ContractFrontend { - static inline std::atomic requests = 0; - static inline std::atomic hold = false; - static inline std::atomic waiting = 0; // open() calls kept by `hold`, counted when they start waiting - static inline std::function insideOpen; // run on the interface thread once the session exists + static inline std::atomic requests = 0; + static inline std::atomic hold = false; + static inline std::atomic waiting = 0; // open() calls kept by `hold`, counted when they start waiting + static inline std::function insideOpen; // run on the interface thread once the session exists [[nodiscard]] static frontend::UIExecutor uiExecutor() requires ownsExecutor @@ -500,9 +513,11 @@ struct SharedWindowFrontend : ContractFrontend(); - host.attach([] { }); // throws std::logic_error when another session runs + host.attach([] {}); // throws std::logic_error when another session runs struct Detach { - ~Detach() { frontend::uiExecutorHostOf().close(); } + ~Detach() { + frontend::uiExecutorHostOf().close(); + } } detach; if (insideOpen) insideOpen(); @@ -521,14 +536,20 @@ struct SharedWindowFrontend : ContractFrontend struct HoldGuard { - HoldGuard() { Frontend::hold = true; } - ~HoldGuard() { Frontend::hold = false; } - HoldGuard(const HoldGuard&) = delete; + HoldGuard() { + Frontend::hold = true; + } + ~HoldGuard() { + Frontend::hold = false; + } + HoldGuard(const HoldGuard&) = delete; HoldGuard& operator=(const HoldGuard&) = delete; }; template struct ReleaseHold { - ~ReleaseHold() { Frontend::hold = false; } + ~ReleaseHold() { + Frontend::hold = false; + } }; // A window that ignores every close request, until the test closes it. @@ -578,508 +599,612 @@ static_assert(frontend::endsOnRequest state; - { - HostApp app; - state = ContractIoContext::current; - when("the host starts the application", [&] { - app.start("page.html"); - then("the page was launched on the calling thread and the server loop runs on its own", [&] { - check(LaunchRecorder::thread == std::this_thread::get_id()); - check(LaunchRecorder::url == "http://127.0.0.1:9002/page.html"); - std::unique_lock lock(state->mutex); - check(state->changed.wait_for(lock, coordinationTimeout, [&] { return state->running; })); - check(!state->stopped); - }); - andThen("the frontend has no window to close", [&] { - check(!app.requestClose()); - }); - }); - when("the launch fails", [&] { - LaunchRecorder::fail = true; - then("the server is stopped and joined before the error reaches the host", [&] { - requireThrows([&] { app.start(); }, equals("no browser to launch")); - std::lock_guard lock(state->mutex); - check(state->stopped); - check(state->exited); - check(!state->running); - }); - }); - } - // Destruction is the host's stop: the loop has been left, without waiting for its timeout. - std::lock_guard lock(state->mutex); - check(state->stopped); - check(state->exited); - check(!state->timedOut); - }); -}}; + given("a frontend that can launch without a loop", [&] { + LaunchRecorder::fail = false; + LaunchRecorder::url.clear(); + std::shared_ptr state; + { + HostApp app; + state = ContractIoContext::current; + when("the host starts the application", [&] { + app.start("page.html"); + then("the page was launched on the calling thread and the server loop runs on its own", [&] { + check(LaunchRecorder::thread == std::this_thread::get_id()); + check(LaunchRecorder::url == "http://127.0.0.1:9002/page.html"); + std::unique_lock lock(state->mutex); + check(state->changed.wait_for(lock, coordinationTimeout, [&] { + return state->running; + })); + check(!state->stopped); + }); + andThen("the frontend has no window to close", [&] { + check(!app.requestClose()); + }); + }); + when("the launch fails", [&] { + LaunchRecorder::fail = true; + then("the server is stopped and joined before the error reaches the host", [&] { + requireThrows( + [&] { + app.start(); + }, + equals("no browser to launch")); + std::lock_guard lock(state->mutex); + check(state->stopped); + check(state->exited); + check(!state->running); + }); + }); + } + // Destruction is the host's stop: the loop has been left, without waiting for its timeout. + std::lock_guard lock(state->mutex); + check(state->stopped); + check(state->exited); + check(!state->timedOut); + }); + }}; const Scenario requestCloseEnds{"requestClose() ends show() from another thread", [] { - given("an embedded window shown on one thread", [&] { - HostApp> app; - const auto state = ContractIoContext::current; - check(!app.requestClose()); // nothing is open yet - std::jthread caller([&] { - app.show(); - }); - requireEventually([&] { return windowOpen(state); }); - when("the host asks for the closure from its own thread", [&] { - check(app.requestClose()); - caller.join(); - then("show has returned after stopping the server", [&] { - std::lock_guard lock(state->mutex); - check(state->stopped); - check(state->exited); - }); - }); - }); -}}; + given("an embedded window shown on one thread", [&] { + HostApp> app; + const auto state = ContractIoContext::current; + check(!app.requestClose()); // nothing is open yet + std::jthread caller([&] { + app.show(); + }); + requireEventually([&] { + return windowOpen(state); + }); + when("the host asks for the closure from its own thread", [&] { + check(app.requestClose()); + caller.join(); + then("show has returned after stopping the server", [&] { + std::lock_guard lock(state->mutex); + check(state->stopped); + check(state->exited); + }); + }); + }); + }}; const Scenario uIThreadRuns{"UIThread runs an application on its own thread while the host keeps its thread", [] { - given("a host that starts its interface", [&] { - std::thread::id setupThread; - std::string port; - UIThread>> ui(WebFrontConfig{}, [&](auto& app) { - setupThread = std::this_thread::get_id(); - port = std::string(app.port()); - }); - const auto state = ContractIoContext::current; - then("the constructor returned with the application set up on the interface thread", [&] { - check(setupThread != std::this_thread::get_id()); - check(setupThread != std::thread::id{}); - check(port == "9002"); - check(ui.app().port() == "9002"); - }); - requireEventually([&] { return windowOpen(state); }); - check(ui.running()); - check(!ui.waitFor(0ms)); - { - std::lock_guard lock(state->mutex); - check(state->openThread == setupThread); - } - when("the host stops it", [&] { - requireNothrow([&] { ui.stop(); }); - then("the window closed, the server loop ended and nothing is left running", [&] { - check(!ui.running()); - check(!ui.failure()); - std::lock_guard lock(state->mutex); - check(state->closeWindow); - check(state->stopped); - check(state->exited); - check(!state->timedOut); - }); - andThen("stopping again does nothing", [&] { - requireNothrow([&] { ui.stop(); }); - }); - }); - when("the user closes the window", [&] { - { - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - } - then("the host observes the end and the application stays usable until stop", [&] { - require(ui.waitFor(coordinationTimeout)); - check(!ui.running()); - check(ui.app().port() == "9002"); - requireNothrow([&] { ui.stop(); }); - }); - }); - }); - given("a window that is still opening when the host stops", [&] { - using Late = HostFrontend; - Late::refused = 0; - UIThread> ui(WebFrontConfig{}, [](auto&) { }); - const auto state = ContractIoContext::current; - when("stop is called at once", [&] { - requireNothrow([&] { ui.stop(); }); - then("the request was repeated until the window existed, and the thread was joined", [&] { - check(Late::refused >= 1); - std::lock_guard lock(state->mutex); - check(state->windowCreated); - check(state->exited); - }); - }); - }); -}}; + given("a host that starts its interface", [&] { + std::thread::id setupThread; + std::string port; + UIThread>> ui(WebFrontConfig{}, [&](auto& app) { + setupThread = std::this_thread::get_id(); + port = std::string(app.port()); + }); + const auto state = ContractIoContext::current; + then("the constructor returned with the application set up on the interface thread", [&] { + check(setupThread != std::this_thread::get_id()); + check(setupThread != std::thread::id{}); + check(port == "9002"); + check(ui.app().port() == "9002"); + }); + requireEventually([&] { + return windowOpen(state); + }); + check(ui.running()); + check(!ui.waitFor(0ms)); + { + std::lock_guard lock(state->mutex); + check(state->openThread == setupThread); + } + when("the host stops it", [&] { + requireNothrow([&] { + ui.stop(); + }); + then("the window closed, the server loop ended and nothing is left running", [&] { + check(!ui.running()); + check(!ui.failure()); + std::lock_guard lock(state->mutex); + check(state->closeWindow); + check(state->stopped); + check(state->exited); + check(!state->timedOut); + }); + andThen("stopping again does nothing", [&] { + requireNothrow([&] { + ui.stop(); + }); + }); + }); + when("the user closes the window", [&] { + { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + } + then("the host observes the end and the application stays usable until stop", [&] { + require(ui.waitFor(coordinationTimeout)); + check(!ui.running()); + check(ui.app().port() == "9002"); + requireNothrow([&] { + ui.stop(); + }); + }); + }); + }); + given("a window that is still opening when the host stops", [&] { + using Late = HostFrontend; + Late::refused = 0; + UIThread> ui(WebFrontConfig{}, [](auto&) {}); + const auto state = ContractIoContext::current; + when("stop is called at once", [&] { + requireNothrow([&] { + ui.stop(); + }); + then("the request was repeated until the window existed, and the thread was joined", [&] { + check(Late::refused >= 1); + std::lock_guard lock(state->mutex); + check(state->windowCreated); + check(state->exited); + }); + }); + }); + }}; const Scenario uIThreadReports{"UIThread reports start and opening failures to the host", [] { - given("a setup that throws", [&] { - then("the constructor rethrows it on the host thread", [&] { - using Hosted = UIThread>>; - requireThrows([&] { Hosted(WebFrontConfig{}, [](auto&) { throw std::runtime_error("setup failed"); }); }, equals("setup failed")); - }); - }); - given("a frontend that cannot be initialized on that thread", [&] { - then("the constructor rethrows the initialization error", [&] { - using Hosted = UIThread>; - requireThrows([&] { Hosted(WebFrontConfig{}, [](auto&) { }); }, equals("no display")); - }); - }); - given("a window that fails to open", [&] { - UIThread>> ui(WebFrontConfig{}, [](auto&) { }); - const auto state = ContractIoContext::current; - when("the host waits for the session", [&] { - require(ui.waitFor(coordinationTimeout)); - then("the failure is observable without throwing, then rethrown once by stop", [&] { - check(!ui.running()); - require(ui.failure()); - checkThrows([&] { std::rethrow_exception(ui.failure()); }, equals("frontend failed before window creation")); - requireThrows([&] { ui.stop(); }, equals("frontend failed before window creation")); - requireNothrow([&] { ui.stop(); }); - std::lock_guard lock(state->mutex); - check(state->stopped); - check(state->exited); - }); - }); - }); -}}; + given("a setup that throws", [&] { + then("the constructor rethrows it on the host thread", [&] { + using Hosted = UIThread>>; + requireThrows( + [&] { + Hosted(WebFrontConfig{}, [](auto&) { + throw std::runtime_error("setup failed"); + }); + }, + equals("setup failed")); + }); + }); + given("a frontend that cannot be initialized on that thread", [&] { + then("the constructor rethrows the initialization error", [&] { + using Hosted = UIThread>; + requireThrows( + [&] { + Hosted(WebFrontConfig{}, [](auto&) {}); + }, + equals("no display")); + }); + }); + given("a window that fails to open", [&] { + UIThread>> ui(WebFrontConfig{}, [](auto&) {}); + const auto state = ContractIoContext::current; + when("the host waits for the session", [&] { + require(ui.waitFor(coordinationTimeout)); + then("the failure is observable without throwing, then rethrown once by stop", [&] { + check(!ui.running()); + require(ui.failure()); + checkThrows( + [&] { + std::rethrow_exception(ui.failure()); + }, + equals("frontend failed before window creation")); + requireThrows( + [&] { + ui.stop(); + }, + equals("frontend failed before window creation")); + requireNothrow([&] { + ui.stop(); + }); + std::lock_guard lock(state->mutex); + check(state->stopped); + check(state->exited); + }); + }); + }); + }}; const Scenario startCalled{"start() is called once and replaces show()", [] { - given("an application already started", [&] { - LaunchRecorder::fail = false; - HostApp app; - const auto state = ContractIoContext::current; - app.start(); - LaunchRecorder::url.clear(); - when("start is called again", [&] { - then("it is refused before any launch and the server keeps running", [&] { - requireThrows([&] { app.start(); }); - check(LaunchRecorder::url.empty()); - std::unique_lock lock(state->mutex); - check(state->changed.wait_for(lock, coordinationTimeout, [&] { return state->running; })); - check(!state->stopped); - }); - }); - when("show is called", [&] { - then("it is refused without opening or stopping anything", [&] { - requireThrows([&] { app.show(); }); - std::lock_guard lock(state->mutex); - check(!state->stopped); - }); - }); - }); - given("a frontend that was shown and can also launch", [&] { - struct Both : LaunchRecorder { - static void open(std::string_view, std::string_view) { } - }; - LaunchRecorder::url.clear(); - HostApp app; - const auto state = ContractIoContext::current; - app.show(); - then("a later start is refused and leaves the server of show running", [&] { - requireThrows([&] { app.start(); }); - check(LaunchRecorder::url.empty()); - std::lock_guard lock(state->mutex); - check(!state->stopped); - }); - }); - given("a window frontend that can also launch, shown and closed so that show joined its server", [&] { - struct Window : HostFrontend<> { - static void launch(std::string_view, std::string_view, std::string_view) { - LaunchRecorder::url = "launched"; - } - }; - LaunchRecorder::url.clear(); - HostApp app; - const auto state = ContractIoContext::current; - { - std::jthread host([&] { - if (waitUntil([&] { - return windowOpen(state); - })) - while (!app.requestClose()) - std::this_thread::yield(); - }); - app.show(); - } - then("a later start is refused although no server thread is left to see (#567)", [&] { - requireThrows([&] { app.start(); }); - check(LaunchRecorder::url.empty()); - }); - }); - given("a launch that failed", [&] { - LaunchRecorder::fail = true; - HostApp app; - requireThrows([&] { app.start(); }, equals("no browser to launch")); - LaunchRecorder::fail = false; - then("the server is stopped for good and a new attempt is refused, not served by a dead server", [&] { - requireThrows([&] { app.start(); }); - }); - }); - given("a frontend whose launch takes the content policy", [&] { - PolicyLaunchRecorder::receivedPolicy = false; - HostApp app; - app.start(); - then("start gives it the application's policy", [&] { - check(PolicyLaunchRecorder::receivedPolicy); - }); - }); -}}; + given("an application already started", [&] { + LaunchRecorder::fail = false; + HostApp app; + const auto state = ContractIoContext::current; + app.start(); + LaunchRecorder::url.clear(); + when("start is called again", [&] { + then("it is refused before any launch and the server keeps running", [&] { + requireThrows([&] { + app.start(); + }); + check(LaunchRecorder::url.empty()); + std::unique_lock lock(state->mutex); + check(state->changed.wait_for(lock, coordinationTimeout, [&] { + return state->running; + })); + check(!state->stopped); + }); + }); + when("show is called", [&] { + then("it is refused without opening or stopping anything", [&] { + requireThrows([&] { + app.show(); + }); + std::lock_guard lock(state->mutex); + check(!state->stopped); + }); + }); + }); + given("a frontend that was shown and can also launch", [&] { + struct Both : LaunchRecorder { + static void open(std::string_view, std::string_view) {} + }; + LaunchRecorder::url.clear(); + HostApp app; + const auto state = ContractIoContext::current; + app.show(); + then("a later start is refused and leaves the server of show running", [&] { + requireThrows([&] { + app.start(); + }); + check(LaunchRecorder::url.empty()); + std::lock_guard lock(state->mutex); + check(!state->stopped); + }); + }); + given("a window frontend that can also launch, shown and closed so that show joined its server", [&] { + struct Window : HostFrontend<> { + static void launch(std::string_view, std::string_view, std::string_view) { + LaunchRecorder::url = "launched"; + } + }; + LaunchRecorder::url.clear(); + HostApp app; + const auto state = ContractIoContext::current; + { + std::jthread host([&] { + if (waitUntil([&] { + return windowOpen(state); + })) + while (!app.requestClose()) + std::this_thread::yield(); + }); + app.show(); + } + then("a later start is refused although no server thread is left to see (#567)", [&] { + requireThrows([&] { + app.start(); + }); + check(LaunchRecorder::url.empty()); + }); + }); + given("a launch that failed", [&] { + LaunchRecorder::fail = true; + HostApp app; + requireThrows( + [&] { + app.start(); + }, + equals("no browser to launch")); + LaunchRecorder::fail = false; + then("the server is stopped for good and a new attempt is refused, not served by a dead server", [&] { + requireThrows([&] { + app.start(); + }); + }); + }); + given("a frontend whose launch takes the content policy", [&] { + PolicyLaunchRecorder::receivedPolicy = false; + HostApp app; + app.start(); + then("start gives it the application's policy", [&] { + check(PolicyLaunchRecorder::receivedPolicy); + }); + }); + }}; const Scenario uIThreadWaits{"UIThread waits for a window that takes longer than one retry period to close", [] { - given("a window that accepts the request on its fifth attempt (about forty milliseconds)", [&] { - using Slow = SlowCloseFrontend<5>; - Slow::requests = 0; - then("the destructor waits for it instead of reporting a stall and leaving its thread joinable (#567)", [&] { - std::shared_ptr state; - { - UIThread> ui(WebFrontConfig{}, [](auto&) { }); - state = ContractIoContext::current; - requireEventually([&] { return windowOpen(state); }); - } // an overflowing patience made this throw inside the destructor and terminate the process - std::lock_guard lock(state->mutex); - check(state->closeWindow); - check(state->stopped); // show() returned and the application was destroyed after the window closed - check(Slow::requests >= 5); - }); - }); -}}; + given("a window that accepts the request on its fifth attempt (about forty milliseconds)", [&] { + using Slow = SlowCloseFrontend<5>; + Slow::requests = 0; + then("the destructor waits for it instead of reporting a stall and leaving its thread joinable (#567)", [&] { + std::shared_ptr state; + { + UIThread> ui(WebFrontConfig{}, [](auto&) {}); + state = ContractIoContext::current; + requireEventually([&] { + return windowOpen(state); + }); + } // an overflowing patience made this throw inside the destructor and terminate the process + std::lock_guard lock(state->mutex); + check(state->closeWindow); + check(state->stopped); // show() returned and the application was destroyed after the window closed + check(Slow::requests >= 5); + }); + }); + }}; const Scenario uIThreadJoins{"UIThread joins its thread when a close request throws", [] { - given("a frontend whose first close requests throw", [&] { - using Flaky = SlowCloseFrontend<3, true>; - Flaky::requests = 0; - UIThread> ui(WebFrontConfig{}, [](auto&) { }); - requireEventually([&] { return windowOpen(ContractIoContext::current); }); - when("the host stops the session", [&] { - then("stop repeats the request until the window closes and joins", [&] { - requireNothrow([&] { ui.stop(); }); - check(!ui.running()); - check(Flaky::requests >= 3); - }); - }); - }); - given("a frontend whose close requests throw until the object is destroyed", [&] { - using Flaky = SlowCloseFrontend<4, true>; - Flaky::requests = 0; - then("the destructor still joins", [&] { - requireNothrow([&] { [&] { - UIThread> ui(WebFrontConfig{}, [](auto&) { }); - requireEventually([&] { return windowOpen(ContractIoContext::current); }); - }(); }); - }); - }); -}}; + given("a frontend whose first close requests throw", [&] { + using Flaky = SlowCloseFrontend<3, true>; + Flaky::requests = 0; + UIThread> ui(WebFrontConfig{}, [](auto&) {}); + requireEventually([&] { + return windowOpen(ContractIoContext::current); + }); + when("the host stops the session", [&] { + then("stop repeats the request until the window closes and joins", [&] { + requireNothrow([&] { + ui.stop(); + }); + check(!ui.running()); + check(Flaky::requests >= 3); + }); + }); + }); + given("a frontend whose close requests throw until the object is destroyed", [&] { + using Flaky = SlowCloseFrontend<4, true>; + Flaky::requests = 0; + then("the destructor still joins", [&] { + requireNothrow([&] { + [&] { + UIThread> ui(WebFrontConfig{}, [](auto&) {}); + requireEventually([&] { + return windowOpen(ContractIoContext::current); + }); + }(); + }); + }); + }); + }}; const Scenario applicationCloses{"An application closes only the window that it shows", [] { - given("two applications of the same frontend, the first showing a window", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::hold = false; - HostApp first; - const auto firstState = ContractIoContext::current; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return windowOpen(firstState); }); - HostApp second; // shows nothing - when("the second asks to close", [&] { - then("nothing reaches the frontend: the window is the first application's (#567)", [&] { - check(!second.requestClose()); - check(Shared::requests == 0); - std::lock_guard lock(firstState->mutex); - check(!firstState->closeWindow); - }); - }); - when("the first asks to close", [&] { - then("its own request is forwarded", [&] { - check(first.requestClose()); - check(Shared::requests == 1); - }); - }); - { - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - } - }); - given("a second application whose show() runs while the first owns the interface thread", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::hold = false; - HostApp first; - const auto firstState = ContractIoContext::current; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return windowOpen(firstState); }); - const HoldGuard held; // the second open() would wait before it is refused - HostApp second; - const auto secondState = ContractIoContext::current; - std::exception_ptr refusal; - std::jthread secondShow([&] { - try { - second.show(); - } catch (...) { - refusal = std::current_exception(); - } - }); - const ReleaseHold release; - when("the second asks to close while its open() is pending", [&] { - then("the first application's window is not closed (#567)", [&] { - check(!second.requestClose()); - check(Shared::requests == 0); - }); - }); - Shared::hold = false; - secondShow.join(); - then("its open() was refused, and it still cannot close the first's window", [&] { - check(refusal != nullptr); - check(!second.requestClose()); - check(Shared::requests == 0); - std::lock_guard lock(firstState->mutex); - check(!firstState->closeWindow); - }); - { - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - } - (void)secondState; - }); -}}; + given("two applications of the same frontend, the first showing a window", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::hold = false; + HostApp first; + const auto firstState = ContractIoContext::current; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return windowOpen(firstState); + }); + HostApp second; // shows nothing + when("the second asks to close", [&] { + then("nothing reaches the frontend: the window is the first application's (#567)", [&] { + check(!second.requestClose()); + check(Shared::requests == 0); + std::lock_guard lock(firstState->mutex); + check(!firstState->closeWindow); + }); + }); + when("the first asks to close", [&] { + then("its own request is forwarded", [&] { + check(first.requestClose()); + check(Shared::requests == 1); + }); + }); + { + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + } + }); + given("a second application whose show() runs while the first owns the interface thread", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::hold = false; + HostApp first; + const auto firstState = ContractIoContext::current; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return windowOpen(firstState); + }); + const HoldGuard held; // the second open() would wait before it is refused + HostApp second; + const auto secondState = ContractIoContext::current; + std::exception_ptr refusal; + std::jthread secondShow([&] { + try { + second.show(); + } catch (...) { + refusal = std::current_exception(); + } + }); + const ReleaseHold release; + when("the second asks to close while its open() is pending", [&] { + then("the first application's window is not closed (#567)", [&] { + check(!second.requestClose()); + check(Shared::requests == 0); + }); + }); + Shared::hold = false; + secondShow.join(); + then("its open() was refused, and it still cannot close the first's window", [&] { + check(refusal != nullptr); + check(!second.requestClose()); + check(Shared::requests == 0); + std::lock_guard lock(firstState->mutex); + check(!firstState->closeWindow); + }); + { + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + } + (void)secondState; + }); + }}; const Scenario showCannot{"A show() that cannot own the session is refused before it opens a window", [] { - given("a frontend without an executor, the first application showing", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::waiting = 0; - Shared::hold = false; - HostApp first; - const auto firstState = ContractIoContext::current; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return windowOpen(firstState); }); - HostApp second; - then("the second show() is refused and its close request reaches nothing (#567)", [&] { - requireThrows([&] { second.show(); }); - check(!second.requestClose()); - check(Shared::requests == 0); - }); - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - }); - given("a second show() called from the interface thread of the first", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::waiting = 0; - Shared::hold = false; - HostApp first; - const auto firstState = ContractIoContext::current; - HostApp second; // the frontend reads the state of the latest application: made after `first` captured its own - std::atomic refused{false}; - std::atomic hookDone{false}; - Shared::insideOpen = [&] { - try { - second.show(); // the same thread, inside the first's open() - } catch (const std::logic_error&) { - refused = true; - } - ContractIoContext::current = firstState; // back to the first's state, which its open() is about to read - hookDone = true; - }; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return hookDone.load(); }); - Shared::insideOpen = nullptr; - then("it is refused, cannot close the first's window, and the first can close its own (#567)", [&] { - check(refused); - check(!second.requestClose()); - check(Shared::requests == 0); - requireEventually([&] { return windowOpen(firstState); }); - check(first.requestClose()); - check(Shared::requests == 1); - }); - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - }); - given("an application refused while the first showed, and another that tries after the first ended", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::waiting = 0; - Shared::hold = false; - Shared::insideOpen = nullptr; - HostApp first; - const auto firstState = ContractIoContext::current; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return windowOpen(firstState); }); - { - HostApp refused; // a refused application is finished: its server was stopped with the refusal - requireThrows([&] { refused.show(); }); - } - { - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - } - firstShow.join(); - HostApp second; // the next attempt, as a UIThread makes it: a new application - const auto secondState = ContractIoContext::current; - std::jthread secondShow([&] { second.show(); }); - requireEventually([&] { return windowOpen(secondState); }); - then("it owns its window and the host can close it, instead of a window nobody can close (#567)", [&] { - checkEventually([&] { return second.requestClose(); }); - check(Shared::requests >= 1); - }); - std::lock_guard lock(secondState->mutex); - secondState->closeWindow = true; - secondState->changed.notify_all(); - }); - given("a second show() held before the frontend while the first one ends", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::waiting = 0; - Shared::hold = false; - Shared::insideOpen = nullptr; - HostApp first; - const auto firstState = ContractIoContext::current; - std::jthread firstShow([&] { first.show(); }); - requireEventually([&] { return windowOpen(firstState); }); - std::optional> held{std::in_place}; - HostApp second; - const auto secondState = ContractIoContext::current; - std::atomic refused{false}; - std::jthread secondShow([&] { - try { - second.show(); - } catch (const std::logic_error&) { - refused = true; - } - }); - const ReleaseHold release; - // Refused at once, or (without the ownership rule) held in front of the frontend. - requireEventually([&] { return refused.load() || Shared::waiting == 1; }); - { - std::lock_guard lock(firstState->mutex); - firstState->closeWindow = true; - firstState->changed.notify_all(); - } - firstShow.join(); // the first session is over before the second could attach - held.reset(); - { - std::lock_guard lock(secondState->mutex); // releases a window that opens anyway, so that the test ends - secondState->closeWindow = true; - secondState->changed.notify_all(); - } - secondShow.join(); - then("it never opens a window that the host could not close (#567)", [&] { - check(refused); - }); - }); -}}; + given("a frontend without an executor, the first application showing", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::waiting = 0; + Shared::hold = false; + HostApp first; + const auto firstState = ContractIoContext::current; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return windowOpen(firstState); + }); + HostApp second; + then("the second show() is refused and its close request reaches nothing (#567)", [&] { + requireThrows([&] { + second.show(); + }); + check(!second.requestClose()); + check(Shared::requests == 0); + }); + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + }); + given("a second show() called from the interface thread of the first", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::waiting = 0; + Shared::hold = false; + HostApp first; + const auto firstState = ContractIoContext::current; + HostApp second; // the frontend reads the state of the latest application: made after `first` captured its own + std::atomic refused{false}; + std::atomic hookDone{false}; + Shared::insideOpen = [&] { + try { + second.show(); // the same thread, inside the first's open() + } catch (const std::logic_error&) { + refused = true; + } + ContractIoContext::current = firstState; // back to the first's state, which its open() is about to read + hookDone = true; + }; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return hookDone.load(); + }); + Shared::insideOpen = nullptr; + then("it is refused, cannot close the first's window, and the first can close its own (#567)", [&] { + check(refused); + check(!second.requestClose()); + check(Shared::requests == 0); + requireEventually([&] { + return windowOpen(firstState); + }); + check(first.requestClose()); + check(Shared::requests == 1); + }); + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + }); + given("an application refused while the first showed, and another that tries after the first ended", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::waiting = 0; + Shared::hold = false; + Shared::insideOpen = nullptr; + HostApp first; + const auto firstState = ContractIoContext::current; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return windowOpen(firstState); + }); + { + HostApp refused; // a refused application is finished: its server was stopped with the refusal + requireThrows([&] { + refused.show(); + }); + } + { + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + } + firstShow.join(); + HostApp second; // the next attempt, as a UIThread makes it: a new application + const auto secondState = ContractIoContext::current; + std::jthread secondShow([&] { + second.show(); + }); + requireEventually([&] { + return windowOpen(secondState); + }); + then("it owns its window and the host can close it, instead of a window nobody can close (#567)", [&] { + checkEventually([&] { + return second.requestClose(); + }); + check(Shared::requests >= 1); + }); + std::lock_guard lock(secondState->mutex); + secondState->closeWindow = true; + secondState->changed.notify_all(); + }); + given("a second show() held before the frontend while the first one ends", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::waiting = 0; + Shared::hold = false; + Shared::insideOpen = nullptr; + HostApp first; + const auto firstState = ContractIoContext::current; + std::jthread firstShow([&] { + first.show(); + }); + requireEventually([&] { + return windowOpen(firstState); + }); + std::optional> held{std::in_place}; + HostApp second; + const auto secondState = ContractIoContext::current; + std::atomic refused{false}; + std::jthread secondShow([&] { + try { + second.show(); + } catch (const std::logic_error&) { + refused = true; + } + }); + const ReleaseHold release; + // Refused at once, or (without the ownership rule) held in front of the frontend. + requireEventually([&] { + return refused.load() || Shared::waiting == 1; + }); + { + std::lock_guard lock(firstState->mutex); + firstState->closeWindow = true; + firstState->changed.notify_all(); + } + firstShow.join(); // the first session is over before the second could attach + held.reset(); + { + std::lock_guard lock(secondState->mutex); // releases a window that opens anyway, so that the test ends + secondState->closeWindow = true; + secondState->changed.notify_all(); + } + secondShow.join(); + then("it never opens a window that the host could not close (#567)", [&] { + check(refused); + }); + }); + }}; namespace { // A frontend that offers only the close request that takes a session (no requestClose() without argument). struct SessionOnlyFrontend : ContractFrontend { - static inline std::atomic requests = 0; + static inline std::atomic requests = 0; [[nodiscard]] static frontend::UIExecutor uiExecutor() { return frontend::uiExecutorHostOf().executor(); } static void open(std::string_view port, std::string_view file) { auto& host = frontend::uiExecutorHostOf(); - host.attach([] { }); + host.attach([] {}); struct Detach { - ~Detach() { frontend::uiExecutorHostOf().close(); } + ~Detach() { + frontend::uiExecutorHostOf().close(); + } } detach; ContractFrontend::open(port, file); } @@ -1099,97 +1224,123 @@ static_assert(frontend::endsOnRequest); } // namespace const Scenario secondShowSame{"A second show() on the same application leaves the first one's server and window alone", [] { - given("an application showing a window", [&] { - using Shared = SharedWindowFrontend; - Shared::requests = 0; - Shared::hold = false; - Shared::insideOpen = nullptr; - HostApp app; - const auto state = ContractIoContext::current; - when("show() is called again from another thread", [&] { - std::jthread show([&] { app.show(); }); - requireEventually([&] { return windowOpen(state); }); - then("it is refused and the server keeps running, with its window still closable (#567)", [&] { - requireThrows([&] { app.show(); }); - { - std::lock_guard lock(state->mutex); - check(!state->stopped); - } - checkEventually([&] { return app.requestClose(); }); - }); - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - }); - when("show() is called again from the interface thread, inside open()", [&] { - std::atomic refused{false}; - std::atomic stoppedByRefusal{true}; - std::atomic hookDone{false}; - Shared::insideOpen = [&] { - try { - app.show(); - } catch (const std::logic_error&) { - refused = true; - } - { - std::lock_guard lock(state->mutex); - stoppedByRefusal = state->stopped; - } - hookDone = true; - }; - std::jthread show([&] { app.show(); }); - requireEventually([&] { return hookDone.load(); }); - Shared::insideOpen = nullptr; - then("the nested call is refused without stopping the server of the first (#567)", [&] { - check(refused); - check(!stoppedByRefusal); - requireEventually([&] { return windowOpen(state); }); - checkEventually([&] { return app.requestClose(); }); - }); - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - }); - }); -}}; + given("an application showing a window", [&] { + using Shared = SharedWindowFrontend; + Shared::requests = 0; + Shared::hold = false; + Shared::insideOpen = nullptr; + HostApp app; + const auto state = ContractIoContext::current; + when("show() is called again from another thread", [&] { + std::jthread show([&] { + app.show(); + }); + requireEventually([&] { + return windowOpen(state); + }); + then("it is refused and the server keeps running, with its window still closable (#567)", [&] { + requireThrows([&] { + app.show(); + }); + { + std::lock_guard lock(state->mutex); + check(!state->stopped); + } + checkEventually([&] { + return app.requestClose(); + }); + }); + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + }); + when("show() is called again from the interface thread, inside open()", [&] { + std::atomic refused{false}; + std::atomic stoppedByRefusal{true}; + std::atomic hookDone{false}; + Shared::insideOpen = [&] { + try { + app.show(); + } catch (const std::logic_error&) { + refused = true; + } + { + std::lock_guard lock(state->mutex); + stoppedByRefusal = state->stopped; + } + hookDone = true; + }; + std::jthread show([&] { + app.show(); + }); + requireEventually([&] { + return hookDone.load(); + }); + Shared::insideOpen = nullptr; + then("the nested call is refused without stopping the server of the first (#567)", [&] { + check(refused); + check(!stoppedByRefusal); + requireEventually([&] { + return windowOpen(state); + }); + checkEventually([&] { + return app.requestClose(); + }); + }); + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + }); + }); + }}; const Scenario frontendOffers{"A frontend that offers only the close request with a session can be closed", [] { - given("an application shown through it", [&] { - SessionOnlyFrontend::requests = 0; - HostApp app; - const auto state = ContractIoContext::current; - std::jthread show([&] { app.show(); }); - requireEventually([&] { return windowOpen(state); }); - then("requestClose() reaches it with the session of its show() (#567)", [&] { - checkEventually([&] { return app.requestClose(); }); - check(SessionOnlyFrontend::requests == 1); - }); - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - }); -}}; + given("an application shown through it", [&] { + SessionOnlyFrontend::requests = 0; + HostApp app; + const auto state = ContractIoContext::current; + std::jthread show([&] { + app.show(); + }); + requireEventually([&] { + return windowOpen(state); + }); + then("requestClose() reaches it with the session of its show() (#567)", [&] { + checkEventually([&] { + return app.requestClose(); + }); + check(SessionOnlyFrontend::requests == 1); + }); + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + }); + }}; const Scenario nativeOrBrowserFrontendForwards{"NativeOrBrowserFrontend forwards a close request when its native frontend has no executor", [] { - given("a native frontend that offers only requestClose()", [&] { - using Either = frontend::NativeOrBrowserFrontendFor, DeafFrontend>; - HostApp app; - const auto state = ContractIoContext::current; - check(!Either::publishesUIExecutor()); - std::jthread show([&] { app.show(); }); - requireEventually([&] { return windowOpen(state); }); - then("the empty executor is not taken for a session that is not there (#567)", [&] { - check(app.requestClose()); - }); - }); -}}; + given("a native frontend that offers only requestClose()", [&] { + using Either = frontend::NativeOrBrowserFrontendFor, DeafFrontend>; + HostApp app; + const auto state = ContractIoContext::current; + check(!Either::publishesUIExecutor()); + std::jthread show([&] { + app.show(); + }); + requireEventually([&] { + return windowOpen(state); + }); + then("the empty executor is not taken for a session that is not there (#567)", [&] { + check(app.requestClose()); + }); + }); + }}; namespace { struct SecondaryContractFrontend : SharedWindowFrontend { static inline int opened = 0; static inline int closed = 0; /// Run once, when BasicWF asks for the executor: after it has captured the session of its show(). - static inline std::function beforeExecutor; + static inline std::function beforeExecutor; [[nodiscard]] static frontend::UIExecutor uiExecutor() { if (auto hook = std::exchange(beforeExecutor, {})) hook(); @@ -1203,90 +1354,109 @@ struct SecondaryContractFrontend : SharedWindowFrontend { return true; } }; -} +} // namespace const Scenario secondaryOwnership{"Only the owner can operate secondary windows", [] { - given("two applications sharing a frontend", [&] { - using Shared = SecondaryContractFrontend; - Shared::opened = 0; - Shared::closed = 0; - HostApp owner; - const auto state = ContractIoContext::current; - HostApp other; - std::atomic done{false}; - std::atomic success{false}; - Shared::insideOpen = [&] { - try { - owner.openSecondaryWindow("one.html"); - const bool closed = owner.requestClose("one.html"); - bool refused = false; - try { other.openSecondaryWindow("one.html"); } catch (const std::logic_error&) { refused = true; } - success = closed && refused && !other.requestClose("one.html"); - } catch (...) { } - ContractIoContext::current = state; - done = true; - }; - std::jthread showing([&] { owner.show(); }); - requireEventually([&] { return done.load(); }); - then("only the owning application reaches the frontend", [&] { - check(success); - check(Shared::opened == 1); - check(Shared::closed == 1); - }); - requireEventually([&] { return windowOpen(state); }); - { - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - } - showing.join(); - Shared::insideOpen = nullptr; - }); -}}; + given("two applications sharing a frontend", [&] { + using Shared = SecondaryContractFrontend; + Shared::opened = 0; + Shared::closed = 0; + HostApp owner; + const auto state = ContractIoContext::current; + HostApp other; + std::atomic done{false}; + std::atomic success{false}; + Shared::insideOpen = [&] { + try { + owner.openSecondaryWindow("one.html"); + const bool closed = owner.requestClose("one.html"); + bool refused = false; + try { + other.openSecondaryWindow("one.html"); + } catch (const std::logic_error&) { + refused = true; + } + success = closed && refused && !other.requestClose("one.html"); + } catch (...) {} + ContractIoContext::current = state; + done = true; + }; + std::jthread showing([&] { + owner.show(); + }); + requireEventually([&] { + return done.load(); + }); + then("only the owning application reaches the frontend", [&] { + check(success); + check(Shared::opened == 1); + check(Shared::closed == 1); + }); + requireEventually([&] { + return windowOpen(state); + }); + { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + } + showing.join(); + Shared::insideOpen = nullptr; + }); + }}; const Scenario secondaryStaleSession{"A secondary window is never opened in a session that started after the call did", [] { - given("a call made during the show() of one application, whose show() ends and another starts before it is delivered", [&] { - using Shared = SecondaryContractFrontend; - Shared::opened = 0; - Shared::closed = 0; - HostApp owner; - const auto ownerState = ContractIoContext::current; - HostApp later; - const auto laterState = ContractIoContext::current; - ContractIoContext::current = ownerState; - std::jthread ownerShow([&] { owner.show(); }); - requireEventually([&] { return windowOpen(ownerState); }); - std::jthread laterShow; - Shared::beforeExecutor = [&] { - { - std::lock_guard lock(ownerState->mutex); - ownerState->closeWindow = true; - ownerState->changed.notify_all(); - } - ownerShow.join(); - ContractIoContext::current = laterState; - laterShow = std::jthread([&] { later.show(); }); - requireEventually([&] { return windowOpen(laterState); }); - }; - bool refused = false; - try { - owner.openSecondaryWindow("one.html"); - } catch (const std::logic_error&) { - refused = true; - } - then("the call is refused and the later session received nothing", [&] { - check(refused); - check(Shared::opened == 0); - check(!owner.requestClose("one.html")); - check(Shared::closed == 0); - }); - { - std::lock_guard lock(laterState->mutex); - laterState->closeWindow = true; - laterState->changed.notify_all(); - } - }); -}}; + given("a call made during the show() of one application, whose show() ends and another starts before it is delivered", + [&] { + using Shared = SecondaryContractFrontend; + Shared::opened = 0; + Shared::closed = 0; + HostApp owner; + const auto ownerState = ContractIoContext::current; + HostApp later; + const auto laterState = ContractIoContext::current; + ContractIoContext::current = ownerState; + std::jthread ownerShow([&] { + owner.show(); + }); + requireEventually([&] { + return windowOpen(ownerState); + }); + std::jthread laterShow; + Shared::beforeExecutor = [&] { + { + std::lock_guard lock(ownerState->mutex); + ownerState->closeWindow = true; + ownerState->changed.notify_all(); + } + ownerShow.join(); + ContractIoContext::current = laterState; + laterShow = std::jthread([&] { + later.show(); + }); + requireEventually([&] { + return windowOpen(laterState); + }); + }; + bool refused = false; + try { + owner.openSecondaryWindow("one.html"); + } catch (const std::logic_error&) { + refused = true; + } + then("the call is refused and the later session received nothing", [&] { + check(refused); + check(Shared::opened == 0); + check(!owner.requestClose("one.html")); + check(Shared::closed == 0); + }); + { + std::lock_guard lock(laterState->mutex); + laterState->closeWindow = true; + laterState->changed.notify_all(); + } + }); + }}; namespace { // A frontend whose first window cannot host a second one for its first `refusals` attempts, as WebView2 while its @@ -1302,7 +1472,7 @@ struct NotReadyFrontend : ContractFrontend(); - host.attach([] { }); + host.attach([] {}); struct Detach { ~Detach() { frontend::uiExecutorHostOf().close(); @@ -1321,7 +1491,9 @@ struct NotReadyFrontend : ContractFrontendmutex); - if (state->changed.wait_for(lock, std::chrono::milliseconds(1), [&] { return state->closeWindow; })) + if (state->changed.wait_for(lock, std::chrono::milliseconds(1), [&] { + return state->closeWindow; + })) return; } } @@ -1340,75 +1512,89 @@ struct NotReadyFrontend : ContractFrontend app; - static_assert(HostApp::supportsSecondaryWindow); - const auto state = ContractIoContext::current; - bool refusedOnInterfaceThread = false; - Frontend::insideOpen = [&] { - Frontend::refusals = 1; - try { - app.openSecondaryWindow("one.html"); - } catch (const frontend::WindowNotReady&) { - refusedOnInterfaceThread = true; - } - Frontend::refusals = 3; - }; - // Closes the window on every exit, also by a failed requirement, so that show() returns before the join. - struct CloseWindow { - std::shared_ptr state; - ~CloseWindow() { - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - Frontend::insideOpen = nullptr; - } - }; - std::jthread showing([&] { app.show(); }); - CloseWindow close{state}; - requireEventually([&] { return windowOpen(state); }); - when("another thread asks for a second window", [&] { - app.openSecondaryWindow("one.html"); - then("the call tries again until the window opens; the interface thread, which cannot wait, is refused", [&] { - check(refusedOnInterfaceThread); - check(Frontend::opened == 1); - check(Frontend::attempts == 5); // one on the interface thread, three refused and the one that opened - }); - }); - }); -}}; + given("an application whose first window refuses a second one for its first attempts", [&] { + using Frontend = NotReadyFrontend; + Frontend::attempts = 0; + Frontend::opened = 0; + HostApp app; + static_assert(HostApp::supportsSecondaryWindow); + const auto state = ContractIoContext::current; + bool refusedOnInterfaceThread = false; + Frontend::insideOpen = [&] { + Frontend::refusals = 1; + try { + app.openSecondaryWindow("one.html"); + } catch (const frontend::WindowNotReady&) { + refusedOnInterfaceThread = true; + } + Frontend::refusals = 3; + }; + // Closes the window on every exit, also by a failed requirement, so that show() returns before the join. + struct CloseWindow { + std::shared_ptr state; + ~CloseWindow() { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + Frontend::insideOpen = nullptr; + } + }; + std::jthread showing([&] { + app.show(); + }); + CloseWindow close{state}; + requireEventually([&] { + return windowOpen(state); + }); + when("another thread asks for a second window", [&] { + app.openSecondaryWindow("one.html"); + then("the call tries again until the window opens; the interface thread, which cannot wait, is refused", + [&] { + check(refusedOnInterfaceThread); + check(Frontend::opened == 1); + check(Frontend::attempts + == 5); // one on the interface thread, three refused and the one that opened + }); + }); + }); + }}; const Scenario secondWindowRefused{"A frontend without a second window refuses openSecondaryWindow with an exception", [] { - given("an application whose frontend shows one window", [&] { - HostApp> app; - static_assert(!HostApp>::supportsSecondaryWindow); - then("the call is refused before and while a window is open, and no close request finds a window", [&] { - requireThrows([&] { app.openSecondaryWindow("other.html"); }); - check(!app.requestClose("other.html")); - const auto state = ContractIoContext::current; - std::jthread show([&] { app.show(); }); - requireEventually([&] { return windowOpen(state); }); - requireThrows([&] { app.openSecondaryWindow("other.html"); }); - check(!app.requestClose("other.html")); - check(app.requestClose()); - }); - }); - given("the native-or-browser frontend whose native window cannot show a second one", [&] { - using Either = frontend::NativeOrBrowserFrontendFor, DeafFrontend>; - // It does not claim a capacity its native frontend lacks (#646). - static_assert(!HostApp::supportsSecondaryWindow); - then("the application reports that it cannot show one", [&] { - check(!HostApp::canShowSecondaryWindow()); - }); - }); -}}; + given("an application whose frontend shows one window", [&] { + HostApp> app; + static_assert(!HostApp>::supportsSecondaryWindow); + then("the call is refused before and while a window is open, and no close request finds a window", [&] { + requireThrows([&] { + app.openSecondaryWindow("other.html"); + }); + check(!app.requestClose("other.html")); + const auto state = ContractIoContext::current; + std::jthread show([&] { + app.show(); + }); + requireEventually([&] { + return windowOpen(state); + }); + requireThrows([&] { + app.openSecondaryWindow("other.html"); + }); + check(!app.requestClose("other.html")); + check(app.requestClose()); + }); + }); + given("the native-or-browser frontend whose native window cannot show a second one", [&] { + using Either = frontend::NativeOrBrowserFrontendFor, DeafFrontend>; + // It does not claim a capacity its native frontend lacks (#646). + static_assert(!HostApp::supportsSecondaryWindow); + then("the application reports that it cannot show one", [&] { + check(!HostApp::canShowSecondaryWindow()); + }); + }); + }}; namespace { // Native frontends that can show a second window; the second cannot initialize, so the system browser replaces it. -struct SecondaryNative : NotReadyFrontend { }; +struct SecondaryNative : NotReadyFrontend {}; struct UnavailableSecondaryNative : NotReadyFrontend { static void initialize() { throw std::runtime_error("no display"); @@ -1416,315 +1602,333 @@ struct UnavailableSecondaryNative : NotReadyFrontend { }; } // namespace -const Scenario secondaryAvailability{"Whether a second window can be shown follows the frontend chosen at run time (#646)", [] { - given("a native-or-browser frontend whose native window can show a second one", [&] { - using Native = frontend::NativeOrBrowserFrontendFor; - using Fallback = frontend::NativeOrBrowserFrontendFor; - static_assert(HostApp::supportsSecondaryWindow && HostApp::supportsSecondaryWindow); - Native::initialize(); - Fallback::initialize(); - then("it can when the native window is used, and cannot once it fell back to the system browser", [&] { - check(Native::usesNativeWindow()); - check(HostApp::canShowSecondaryWindow()); - check(!Fallback::usesNativeWindow()); - check(!HostApp::canShowSecondaryWindow()); - requireThrows([&] { Fallback::openSecondaryWindow("127.0.0.1", "9002", "other.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{}); }); - check(!Fallback::closeSecondaryWindow("other.html")); +const Scenario secondaryAvailability{ + "Whether a second window can be shown follows the frontend chosen at run time (#646)", + [] { + given("a native-or-browser frontend whose native window can show a second one", [&] { + using Native = frontend::NativeOrBrowserFrontendFor; + using Fallback = frontend::NativeOrBrowserFrontendFor; + static_assert(HostApp::supportsSecondaryWindow && HostApp::supportsSecondaryWindow); + Native::initialize(); + Fallback::initialize(); + then("it can when the native window is used, and cannot once it fell back to the system browser", [&] { + check(Native::usesNativeWindow()); + check(HostApp::canShowSecondaryWindow()); + check(!Fallback::usesNativeWindow()); + check(!HostApp::canShowSecondaryWindow()); + requireThrows([&] { + Fallback::openSecondaryWindow("127.0.0.1", "9002", "other.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{}); + }); + check(!Fallback::closeSecondaryWindow("other.html")); + }); }); - }); - given("frontends without a choice at run time", [&] { - then("a frontend that shows a second window can, one that cannot does not", [&] { - check(HostApp::canShowSecondaryWindow()); - check(!HostApp>::canShowSecondaryWindow()); + given("frontends without a choice at run time", [&] { + then("a frontend that shows a second window can, one that cannot does not", [&] { + check(HostApp::canShowSecondaryWindow()); + check(!HostApp>::canShowSecondaryWindow()); + }); }); - }); -}}; + }}; const Scenario uIThreadStop{"UIThread::stop reports a window that does not close", [] { - given("a window that ignores close requests", [&] { - UIThread> ui(WebFrontConfig{}, [](auto&) { }); - const auto state = ContractIoContext::current; - requireEventually([&] { return windowOpen(state); }); - when("the host stops it with a bounded patience", [&] { - then("stop throws, and the session is still running and usable", [&] { - requireThrows([&] { ui.stop(20ms); }); - check(ui.running()); - check(ui.app().port() == "9002"); - }); - }); - // The window closes at last (here: the user): stop, and the destructor after it, then return. - { - std::lock_guard lock(state->mutex); - state->closeWindow = true; - state->changed.notify_all(); - } - requireNothrow([&] { ui.stop(); }); - }); -}}; + given("a window that ignores close requests", [&] { + UIThread> ui(WebFrontConfig{}, [](auto&) {}); + const auto state = ContractIoContext::current; + requireEventually([&] { + return windowOpen(state); + }); + when("the host stops it with a bounded patience", [&] { + then("stop throws, and the session is still running and usable", [&] { + requireThrows([&] { + ui.stop(20ms); + }); + check(ui.running()); + check(ui.app().port() == "9002"); + }); + }); + // The window closes at last (here: the user): stop, and the destructor after it, then return. + { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + } + requireNothrow([&] { + ui.stop(); + }); + }); + }}; const Scenario closeRequest{"A close request made for one session never closes the window of a later one", [] { - given("a request prepared for the first loop of a frontend", [&] { - frontend::UIExecutorHost host; - frontend::NativeWindowHost windowHost{host.executor()}; - int firstWindow = 0; - int secondWindow = 0; - int closed = 0; - const auto close = [&](const frontend::NativeWindowHandle& window) { - closed = *static_cast(window.pointer) + 1; - }; - host.attach([] { }); - const auto first = host.executor().session(); - require(first); - windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &firstWindow, .portalParent = {}}); - // The first session ends, as its window closes; another application then opens its own on the same thread, with a - // window of its own. Everything is sequenced here: the request is made after the check of the first session passed. - windowHost.retract(); - host.close(); - host.attach([] { }); - const auto second = host.executor().session(); - require(second); - windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &secondWindow, .portalParent = {}}); - check(first->thread == second->thread); // the same thread does not make it the same session - check(*first != *second); - when("the request names the first session", [&] { - require(frontend::detail::requestWindowClose(host.executor(), windowHost.window(), close, first)); - host.drain(); - then("the second session's window stays open", [&] { - check(closed == 0); - }); - }); - when("the request names the session that runs", [&] { - require(frontend::detail::requestWindowClose(host.executor(), windowHost.window(), close, second)); - host.drain(); - then("its window is closed", [&] { - check(closed == 1); - }); - }); - host.close(); - }); -}}; + given("a request prepared for the first loop of a frontend", [&] { + frontend::UIExecutorHost host; + frontend::NativeWindowHost windowHost{host.executor()}; + int firstWindow = 0; + int secondWindow = 0; + int closed = 0; + const auto close = [&](const frontend::NativeWindowHandle& window) { + closed = *static_cast(window.pointer) + 1; + }; + host.attach([] {}); + const auto first = host.executor().session(); + require(first); + windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &firstWindow, .portalParent = {}}); + // The first session ends, as its window closes; another application then opens its own on the same thread, with a + // window of its own. Everything is sequenced here: the request is made after the check of the first session passed. + windowHost.retract(); + host.close(); + host.attach([] {}); + const auto second = host.executor().session(); + require(second); + windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &secondWindow, .portalParent = {}}); + check(first->thread == second->thread); // the same thread does not make it the same session + check(*first != *second); + when("the request names the first session", [&] { + require(frontend::detail::requestWindowClose(host.executor(), windowHost.window(), close, first)); + host.drain(); + then("the second session's window stays open", [&] { + check(closed == 0); + }); + }); + when("the request names the session that runs", [&] { + require(frontend::detail::requestWindowClose(host.executor(), windowHost.window(), close, second)); + host.drain(); + then("its window is closed", [&] { + check(closed == 1); + }); + }); + host.close(); + }); + }}; const Scenario systemBrowserLoop{"The system browser's loop ignores a close request made for an earlier loop", [] { - given("a session of the first loop, kept after it ended", [&] { - using Browser = frontend::BrowserWithUILoopFrontend; - // The loop's stop state is process-wide and a test before this one may have left a request pending: spend it. - Browser::requestStop(); - Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) { }); - std::optional stale; - { - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - (void)waitUntil([&] { - return executor.available(); - }); - stale = executor.session(); - Browser::requestStop(); - }); - Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) { }); - } - require(stale); - then("a later loop is not ended by it, and its own session ends it", [&] { - bool staleAccepted = true; - bool ownAccepted = false; - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - (void)waitUntil([&] { - return executor.available(); - }); - const auto own = executor.session(); - staleAccepted = Browser::requestClose(stale); - ownAccepted = waitUntil([&] { - return Browser::requestClose(own); - }); - if (!ownAccepted) - Browser::requestStop(); - }); - Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) { }); - client.join(); - check(!staleAccepted); - check(ownAccepted); - }); - }); -}}; + given("a session of the first loop, kept after it ended", [&] { + using Browser = frontend::BrowserWithUILoopFrontend; + // The loop's stop state is process-wide and a test before this one may have left a request pending: spend it. + Browser::requestStop(); + Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) {}); + std::optional stale; + { + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + (void)waitUntil([&] { + return executor.available(); + }); + stale = executor.session(); + Browser::requestStop(); + }); + Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) {}); + } + require(stale); + then("a later loop is not ended by it, and its own session ends it", [&] { + bool staleAccepted = true; + bool ownAccepted = false; + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + (void)waitUntil([&] { + return executor.available(); + }); + const auto own = executor.session(); + staleAccepted = Browser::requestClose(stale); + ownAccepted = waitUntil([&] { + return Browser::requestClose(own); + }); + if (!ownAccepted) + Browser::requestStop(); + }); + Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) {}); + client.join(); + check(!staleAccepted); + check(ownAccepted); + }); + }); + }}; #if !defined(_WIN32) -#if defined(__linux__) || defined(__APPLE__) + #if defined(__linux__) || defined(__APPLE__) const Scenario systemBrowserShowsHttp{"The default browser's show() opens the original HTTP page URL", {"fast"}, [] { - if (browser::isWSL()) { - succeed("WSL uses a PowerShell opener outside PATH"); - return; - } - namespace fs = std::filesystem; - const webfront::test::TemporaryDirectory directory; -#if defined(__APPLE__) - const auto opener = directory.path() / "open"; -#else + if (browser::isWSL()) { + succeed("WSL uses a PowerShell opener outside PATH"); + return; + } + namespace fs = std::filesystem; + const webfront::test::TemporaryDirectory directory; + #if defined(__APPLE__) + const auto opener = directory.path() / "open"; + #else const auto opener = directory.path() / "xdg-open"; -#endif - std::ofstream(opener) << "#!/bin/sh\nprintf '%s\\n' \"$1\" > \"$0.url\"\n"; - fs::permissions(opener, fs::perms::owner_all); - - const auto* currentPath = std::getenv("PATH"); - std::istringstream enter{"\n"}; - struct Restore { - std::optional path; - std::streambuf* input; - ~Restore() { - std::cin.rdbuf(input); - if (path) ::setenv("PATH", path->c_str(), 1); - else ::unsetenv("PATH"); - } - } restore{currentPath ? std::optional{currentPath} : std::nullopt, std::cin.rdbuf(enter.rdbuf())}; - require(::setenv("PATH", directory.path().c_str(), 1) == 0); - - WebFront app({.port = "0"}); - app.show("folder/a b.html?x=1#result"); - app.shutdown(); - then("the opener receives the legacy URL with the bound port, query and fragment", [&] { - std::ifstream capture(opener.string() + ".url"); - std::string url; - require(static_cast(std::getline(capture, url))); - require(url == "http://127.0.0.1:" + std::string(app.port()) + "/folder/a%20b.html?x=1#result"); - }); -}}; -#endif + #endif + std::ofstream(opener) << "#!/bin/sh\nprintf '%s\\n' \"$1\" > \"$0.url\"\n"; + fs::permissions(opener, fs::perms::owner_all); + + const auto* currentPath = std::getenv("PATH"); + std::istringstream enter{"\n"}; + struct Restore { + std::optional path; + std::streambuf* input; + ~Restore() { + std::cin.rdbuf(input); + if (path) + ::setenv("PATH", path->c_str(), 1); + else + ::unsetenv("PATH"); + } + } restore{currentPath ? std::optional{currentPath} : std::nullopt, std::cin.rdbuf(enter.rdbuf())}; + require(::setenv("PATH", directory.path().c_str(), 1) == 0); + + WebFront app({.port = "0"}); + app.show("folder/a b.html?x=1#result"); + app.shutdown(); + then("the opener receives the legacy URL with the bound port, query and fragment", [&] { + std::ifstream capture(opener.string() + ".url"); + std::string url; + require(static_cast(std::getline(capture, url))); + require(url == "http://127.0.0.1:" + std::string(app.port()) + "/folder/a%20b.html?x=1#result"); + }); + }}; + #endif const Scenario systemBrowserLoopUp{"The system browser's loop is up while its opener is still running", [] { - given("an opener that lives longer than the close request", [&] { - namespace fs = std::filesystem; - if (browser::isWSL()) - succeed("WSL opens the page through PowerShell, not through a command this test can replace"); - else { - const auto directory = fs::temp_directory_path() / ("webfront-opener-" + std::to_string(::getpid())); - fs::create_directories(directory); - for (const char* name : {"xdg-open", "open"}) { - std::ofstream script(directory / name); - // The marker tells the test that the shell found this opener. The shell's PATH is this directory alone (below), - // so that, even if it looks the command up after the directory is gone, it finds nothing: it can never fall - // through to the developer's real browser (#628). Absolute path: sleep is not on that PATH. - script << "#!/bin/sh\n: > \"$0.started\"\nexec /bin/sleep 3\n"; - fs::permissions(directory / name, fs::perms::owner_all); - } - const std::string path = directory.string(); - const std::string saved = std::getenv("PATH") ? std::getenv("PATH") : ""; - ::setenv("PATH", path.c_str(), 1); - using Browser = frontend::BrowserWithUILoopFrontend; - Browser::requestStop(); // spend a request that an earlier test may have left pending - Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) { }); - std::atomic closed{false}; - std::jthread host([&] { - // The host's own thread: the loop must be there to receive the request well before the opener ends. - closed = waitUntil([] { - return Browser::requestClose(Browser::uiExecutor().session()); - }); - if (!closed) - Browser::requestStop(); - }); - const auto start = std::chrono::steady_clock::now(); - Browser::open("9002", "index.html"); - const auto elapsed = std::chrono::steady_clock::now() - start; - host.join(); - const bool openerStarted = waitUntil([&] { - return fs::exists(directory / "xdg-open.started") || fs::exists(directory / "open.started"); - }); - ::setenv("PATH", saved.c_str(), 1); - fs::remove_all(directory); - then("the loop ran and ended at the request, not after the opener (#567)", [&] { - check(closed); - check(elapsed < 2500ms); - }); - then("the replaced opener ran, not a browser of the machine (#628)", [&] { - check(openerStarted); - }); - } - }); -}}; + given("an opener that lives longer than the close request", [&] { + namespace fs = std::filesystem; + if (browser::isWSL()) + succeed("WSL opens the page through PowerShell, not through a command this test can replace"); + else { + const auto directory = fs::temp_directory_path() / ("webfront-opener-" + std::to_string(::getpid())); + fs::create_directories(directory); + for (const char* name : {"xdg-open", "open"}) { + std::ofstream script(directory / name); + // The marker tells the test that the shell found this opener. The shell's PATH is this directory alone + // (below), so that, even if it looks the command up after the directory is gone, it finds nothing: it can + // never fall through to the developer's real browser (#628). Absolute path: sleep is not on that PATH. + script << "#!/bin/sh\n: > \"$0.started\"\nexec /bin/sleep 3\n"; + fs::permissions(directory / name, fs::perms::owner_all); + } + const std::string path = directory.string(); + const std::string saved = std::getenv("PATH") ? std::getenv("PATH") : ""; + ::setenv("PATH", path.c_str(), 1); + using Browser = frontend::BrowserWithUILoopFrontend; + Browser::requestStop(); // spend a request that an earlier test may have left pending + Browser::loop("127.0.0.1", "9002", "index.html", +[](const std::string&) {}); + std::atomic closed{false}; + std::jthread host([&] { + // The host's own thread: the loop must be there to receive the request well before the opener ends. + closed = waitUntil([] { + return Browser::requestClose(Browser::uiExecutor().session()); + }); + if (!closed) + Browser::requestStop(); + }); + const auto start = std::chrono::steady_clock::now(); + Browser::open("9002", "index.html"); + const auto elapsed = std::chrono::steady_clock::now() - start; + host.join(); + const bool openerStarted = waitUntil([&] { + return fs::exists(directory / "xdg-open.started") || fs::exists(directory / "open.started"); + }); + ::setenv("PATH", saved.c_str(), 1); + fs::remove_all(directory); + then("the loop ran and ended at the request, not after the opener (#567)", [&] { + check(closed); + check(elapsed < 2500ms); + }); + then("the replaced opener ran, not a browser of the machine (#628)", [&] { + check(openerStarted); + }); + } + }); + }}; const Scenario systemBrowserOpener{"The system browser opener is started without being waited for", [] { - given("a command that lives for two seconds", [&] { - const auto start = std::chrono::steady_clock::now(); - std::mutex mutex; - std::condition_variable ended; - std::optional status; - browser::detail::spawnWithoutWaiting("sleep 2", [&](int value) { - std::lock_guard lock(mutex); - status = value; - ended.notify_all(); - }); - then("the call returns long before it ends, and its end is reported afterwards (#567)", [&] { - check(std::chrono::steady_clock::now() - start < 1s); - std::unique_lock lock(mutex); - check(!status.has_value()); - require(ended.wait_for(lock, 10s, [&] { return status.has_value(); })); - check(*status == 0); - }); - }); - given("a command that fails", [&] { - std::mutex mutex; - std::condition_variable ended; - std::optional status; - browser::detail::spawnWithoutWaiting("exit 3", [&](int value) { - std::lock_guard lock(mutex); - status = value; - ended.notify_all(); - }); - then("the status is reported, not thrown", [&] { - std::unique_lock lock(mutex); - require(ended.wait_for(lock, 10s, [&] { return status.has_value(); })); - check(WIFEXITED(*status)); - check(WEXITSTATUS(*status) == 3); - }); - }); -}}; + given("a command that lives for two seconds", [&] { + const auto start = std::chrono::steady_clock::now(); + std::mutex mutex; + std::condition_variable ended; + std::optional status; + browser::detail::spawnWithoutWaiting("sleep 2", [&](int value) { + std::lock_guard lock(mutex); + status = value; + ended.notify_all(); + }); + then("the call returns long before it ends, and its end is reported afterwards (#567)", [&] { + check(std::chrono::steady_clock::now() - start < 1s); + std::unique_lock lock(mutex); + check(!status.has_value()); + require(ended.wait_for(lock, 10s, [&] { + return status.has_value(); + })); + check(*status == 0); + }); + }); + given("a command that fails", [&] { + std::mutex mutex; + std::condition_variable ended; + std::optional status; + browser::detail::spawnWithoutWaiting("exit 3", [&](int value) { + std::lock_guard lock(mutex); + status = value; + ended.notify_all(); + }); + then("the status is reported, not thrown", [&] { + std::unique_lock lock(mutex); + require(ended.wait_for(lock, 10s, [&] { + return status.has_value(); + })); + check(WIFEXITED(*status)); + check(WEXITSTATUS(*status) == 3); + }); + }); + }}; #endif const Scenario windowCloseScenario{"A window close request is always released by the executor", [] { - given("a close function that holds a resource", [&] { - frontend::UIExecutorHost host; - frontend::NativeWindowHost windowHost{host.executor()}; - const auto resource = std::make_shared(0); - const auto request = [&] { - return frontend::detail::requestWindowClose(host.executor(), windowHost.window(), [resource](const frontend::NativeWindowHandle&) { - ++*resource; - }); - }; - when("no loop is attached", [&] { - then("the request is refused and nothing is kept", [&] { - check(!request()); - check(resource.use_count() == 1); - }); - }); - when("the loop closes with the request pending", [&] { - host.attach([] { }); - require(request()); - check(resource.use_count() == 2); - host.close(); - then("it completes stopped: the window is not closed and the request is freed", [&] { - check(*resource == 0); - check(resource.use_count() == 1); - }); - }); - when("the loop runs the request", [&] { - host.attach([] { }); - andWhen("the window is published", [&] { - int window = 0; - windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &window, .portalParent = {}}); - require(request()); - host.drain(); - then("the close function ran once and the request is freed", [&] { - check(*resource == 1); - check(resource.use_count() == 1); - }); - }); - andWhen("no window is published", [&] { - require(request()); - host.drain(); - then("nothing is closed and the request is freed", [&] { - check(*resource == 0); - check(resource.use_count() == 1); - }); - }); - host.close(); - }); - }); -}}; + given("a close function that holds a resource", [&] { + frontend::UIExecutorHost host; + frontend::NativeWindowHost windowHost{host.executor()}; + const auto resource = std::make_shared(0); + const auto request = [&] { + return frontend::detail::requestWindowClose(host.executor(), + windowHost.window(), + [resource](const frontend::NativeWindowHandle&) { + ++*resource; + }); + }; + when("no loop is attached", [&] { + then("the request is refused and nothing is kept", [&] { + check(!request()); + check(resource.use_count() == 1); + }); + }); + when("the loop closes with the request pending", [&] { + host.attach([] {}); + require(request()); + check(resource.use_count() == 2); + host.close(); + then("it completes stopped: the window is not closed and the request is freed", [&] { + check(*resource == 0); + check(resource.use_count() == 1); + }); + }); + when("the loop runs the request", [&] { + host.attach([] {}); + andWhen("the window is published", [&] { + int window = 0; + windowHost.publish({.kind = frontend::NativeWindowKind::gtk, .pointer = &window, .portalParent = {}}); + require(request()); + host.drain(); + then("the close function ran once and the request is freed", [&] { + check(*resource == 1); + check(resource.use_count() == 1); + }); + }); + andWhen("no window is published", [&] { + require(request()); + host.drain(); + then("nothing is closed and the request is freed", [&] { + check(*resource == 0); + check(resource.use_count() == 1); + }); + }); + host.close(); + }); + }); + }}; diff --git a/test/unit/FrontendUrlTests.cpp b/test/unit/FrontendUrlTests.cpp index 9f938527..573558a0 100644 --- a/test/unit/FrontendUrlTests.cpp +++ b/test/unit/FrontendUrlTests.cpp @@ -1,6 +1,6 @@ -#include #include #include +#include #include #include @@ -22,110 +22,122 @@ void rejectLaunch(const std::string&) { } // namespace const Scenario systemBrowserSession{"The system browser session waits only after a successful launch", [] { - std::istringstream input("\nremaining"); - std::ostringstream output; - given("a successful desktop launcher", [&] { - webfront::browser::open("127.0.0.2", "9002", "index.html?x=1#result", {recordLaunch, input, output}); - require(launchedUrl == "http://127.0.0.2:9002/index.html?x=1#result"); - require(input.peek() == 'r'); - require(output.str().find("Press Enter") != std::string::npos); - }); - given("the legacy two-argument entry point", [&] { - webfront::browser::open("9002", "index.html", {recordLaunch, input, output}); - require(launchedUrl == "http://127.0.0.1:9002/index.html"); - require(input.peek() == 'r'); - }); - given("the page used by the WebView2 path-encoding regression", [&] { - webfront::browser::open("9002", "encoded path %23.html?x=1#example", {recordLaunch, input, output}); - then("the desktop launcher receives the encoded path and the query and fragment intact", [&] { - require(launchedUrl == "http://127.0.0.1:9002/encoded%20path%20%23.html?x=1#example"); - require(input.peek() == 'r'); - }); - }); - given("a failed desktop launcher", [&] { - requireThrows([&] { webfront::browser::open("9002", "index.html", {rejectLaunch, input, output}); }, equals("desktop launcher failed")); - require(input.peek() == '\n'); - require(output.str().empty()); - }); - given("an invalid address", [&] { - requireThrows([&] { webfront::browser::open("bad/address", "9002", "index.html", {recordLaunch, input, output}); }); - require(output.str().empty()); - }); -}}; + std::istringstream input("\nremaining"); + std::ostringstream output; + given("a successful desktop launcher", [&] { + webfront::browser::open("127.0.0.2", "9002", "index.html?x=1#result", {recordLaunch, input, output}); + require(launchedUrl == "http://127.0.0.2:9002/index.html?x=1#result"); + require(input.peek() == 'r'); + require(output.str().find("Press Enter") != std::string::npos); + }); + given("the legacy two-argument entry point", [&] { + webfront::browser::open("9002", "index.html", {recordLaunch, input, output}); + require(launchedUrl == "http://127.0.0.1:9002/index.html"); + require(input.peek() == 'r'); + }); + given("the page used by the WebView2 path-encoding regression", [&] { + webfront::browser::open("9002", "encoded path %23.html?x=1#example", {recordLaunch, input, output}); + then("the desktop launcher receives the encoded path and the query and fragment intact", [&] { + require(launchedUrl == "http://127.0.0.1:9002/encoded%20path%20%23.html?x=1#example"); + require(input.peek() == 'r'); + }); + }); + given("a failed desktop launcher", [&] { + requireThrows( + [&] { + webfront::browser::open("9002", "index.html", {rejectLaunch, input, output}); + }, + equals("desktop launcher failed")); + require(input.peek() == '\n'); + require(output.str().empty()); + }); + given("an invalid address", [&] { + requireThrows([&] { + webfront::browser::open("bad/address", "9002", "index.html", {recordLaunch, input, output}); + }); + require(output.str().empty()); + }); + }}; const Scenario everyFrontend{"Every frontend builds the application URL the same way", [] { - given("plain page paths", [&] { - then("the path is appended to the local origin", [&] { - require(applicationUrl("9002", "index.html") == "http://127.0.0.1:9002/index.html"); - require(applicationUrl("9002", "demos/react.html") == "http://127.0.0.1:9002/demos/react.html"); - require(applicationUrl("9002", "") == "http://127.0.0.1:9002/"); - }); - }); + given("plain page paths", [&] { + then("the path is appended to the local origin", [&] { + require(applicationUrl("9002", "index.html") == "http://127.0.0.1:9002/index.html"); + require(applicationUrl("9002", "demos/react.html") == "http://127.0.0.1:9002/demos/react.html"); + require(applicationUrl("9002", "") == "http://127.0.0.1:9002/"); + }); + }); - given("path separators and a literal backslash", [&] { - then("URL path separators survive and the backslash is percent-encoded", [&] { - require(applicationUrl("9002", "folder/sub folder/page.html") == "http://127.0.0.1:9002/folder/sub%20folder/page.html"); - require(applicationUrl("9002", "folder\\page.html") == "http://127.0.0.1:9002/folder%5Cpage.html"); - }); - }); + given("path separators and a literal backslash", [&] { + then("URL path separators survive and the backslash is percent-encoded", [&] { + require(applicationUrl("9002", "folder/sub folder/page.html") + == "http://127.0.0.1:9002/folder/sub%20folder/page.html"); + require(applicationUrl("9002", "folder\\page.html") == "http://127.0.0.1:9002/folder%5Cpage.html"); + }); + }); - given("a plus sign in a filename, query and fragment", [&] { - then("the path plus survives the server decoder without changing query or fragment syntax", [&] { - require(applicationUrl("9002", "a+b.html?value=a+b#c+d") == "http://127.0.0.1:9002/a%2Bb.html?value=a+b#c+d"); - require(applicationUrl("9002", "a%2Bb.html") == "http://127.0.0.1:9002/a%2Bb.html"); - }); - }); + given("a plus sign in a filename, query and fragment", [&] { + then("the path plus survives the server decoder without changing query or fragment syntax", [&] { + require(applicationUrl("9002", "a+b.html?value=a+b#c+d") == "http://127.0.0.1:9002/a%2Bb.html?value=a+b#c+d"); + require(applicationUrl("9002", "a%2Bb.html") == "http://127.0.0.1:9002/a%2Bb.html"); + }); + }); - given("a UTF-8 path containing URL delimiters", [&] { - then("literal filename delimiters are supplied as percent escapes", [&] { - require(applicationUrl("9002", "folder/a b%23c%3Fd%25\xc3\xa9.html") == "http://127.0.0.1:9002/folder/a%20b%23c%3Fd%25%C3%A9.html"); - require(applicationUrl("9002", "encoded path %23.html") == "http://127.0.0.1:9002/encoded%20path%20%23.html"); - }); - then("quotes and backticks are escaped", [&] { - require(applicationUrl("9002", "a&b;c`d$e\"f'g.html") == "http://127.0.0.1:9002/a&b;c%60d$e%22f%27g.html"); - }); - }); -}}; + given("a UTF-8 path containing URL delimiters", [&] { + then("literal filename delimiters are supplied as percent escapes", [&] { + require(applicationUrl("9002", "folder/a b%23c%3Fd%25\xc3\xa9.html") + == "http://127.0.0.1:9002/folder/a%20b%23c%3Fd%25%C3%A9.html"); + require(applicationUrl("9002", "encoded path %23.html") == "http://127.0.0.1:9002/encoded%20path%20%23.html"); + }); + then("quotes and backticks are escaped", [&] { + require(applicationUrl("9002", "a&b;c`d$e\"f'g.html") == "http://127.0.0.1:9002/a&b;c%60d$e%22f%27g.html"); + }); + }); + }}; const Scenario defaultBrowser{"The default browser opens a quoted, encoded URL", [] { - given("a page whose name contains characters that are special to shells and URLs", [&] { - const auto command = webfront::browser::command("9002", "my page %231&2.html"); + given("a page whose name contains characters that are special to shells and URLs", [&] { + const auto command = webfront::browser::command("9002", "my page %231&2.html"); - then("the URL is the shared encoded URL, enclosed in quotes", [&] { + then("the URL is the shared encoded URL, enclosed in quotes", [&] { #ifdef _WIN32 - require(command, endsWith("\"http://127.0.0.1:9002/my%20page%20%231&2.html\"")); + require(command, endsWith("\"http://127.0.0.1:9002/my%20page%20%231&2.html\"")); #else require(command, endsWith("http://127.0.0.1:9002/my%20page%20%231&2.html'")); #endif - require(command.find(' ', command.find("http://")) == std::string::npos); - }); - }); + require(command.find(' ', command.find("http://")) == std::string::npos); + }); + }); - given("a port that is not a decimal number", [&] { - then("the command is refused instead of reaching a shell", [&] { - requireThrows([&] { webfront::browser::command("9002; touch x", "index.html"); }); - requireThrows([&] { webfront::browser::command("", "index.html"); }); - }); - }); - given("a WSL desktop launch with percent escapes and shell metacharacters", [&] { - const auto url = applicationUrl("9002", "a b c.html?value=$HOME&literal=%25"); - const auto invocation = webfront::browser::wslCommandForUrl(url); - then("PowerShell receives a literal URL without invoking cmd.exe", [&] { - require(invocation.find("cmd.exe") == std::string::npos); - require(invocation.find("powershell.exe -NoProfile -NonInteractive -Command ") != std::string::npos); - require(invocation, endsWith("'Start-Process -FilePath '\\''" + url + "'\\'''")); - require(webfront::browser::shellArgument("a'b$c") == "'a'\\''b$c'"); - }); - }); -}}; + given("a port that is not a decimal number", [&] { + then("the command is refused instead of reaching a shell", [&] { + requireThrows([&] { + webfront::browser::command("9002; touch x", "index.html"); + }); + requireThrows([&] { + webfront::browser::command("", "index.html"); + }); + }); + }); + given("a WSL desktop launch with percent escapes and shell metacharacters", [&] { + const auto url = applicationUrl("9002", "a b c.html?value=$HOME&literal=%25"); + const auto invocation = webfront::browser::wslCommandForUrl(url); + then("PowerShell receives a literal URL without invoking cmd.exe", [&] { + require(invocation.find("cmd.exe") == std::string::npos); + require(invocation.find("powershell.exe -NoProfile -NonInteractive -Command ") != std::string::npos); + require(invocation, endsWith("'Start-Process -FilePath '\\''" + url + "'\\'''")); + require(webfront::browser::shellArgument("a'b$c") == "'a'\\''b$c'"); + }); + }); + }}; const Scenario popupURLs{"Popup URLs remain literal arguments to desktop launchers", [] { - const std::string url = "https://example.com/it's?value=$HOME&x=1"; - require( - webfront::browser::wslCommandForUrl(url).find(webfront::browser::shellArgument("Start-Process -FilePath 'https://example.com/it''s?value=$HOME&x=1'")) - != std::string::npos); + const std::string url = "https://example.com/it's?value=$HOME&x=1"; + require(webfront::browser::wslCommandForUrl(url).find( + webfront::browser::shellArgument("Start-Process -FilePath 'https://example.com/it''s?value=$HOME&x=1'")) + != std::string::npos); #ifndef _WIN32 - require(webfront::browser::commandForUrl(url).find(webfront::browser::shellArgument(url)) != std::string::npos); + require(webfront::browser::commandForUrl(url).find(webfront::browser::shellArgument(url)) != std::string::npos); #else given("a UTF-8 URL passed to the Windows shell", [&] { static std::wstring received; @@ -147,4 +159,4 @@ const Scenario popupURLs{"Popup URLs remain literal arguments to desktop launche }); }); #endif -}}; + }}; diff --git a/test/unit/GzipExecutorTests.cpp b/test/unit/GzipExecutorTests.cpp index 40ea8e83..5d20eb60 100644 --- a/test/unit/GzipExecutorTests.cpp +++ b/test/unit/GzipExecutorTests.cpp @@ -1,7 +1,7 @@ #include "GzipFixtures.hpp" -#include #include #include +#include #include #include @@ -174,418 +174,419 @@ std::string receive(Net::Socket& socket, bool head = false) { } // namespace const Scenario gzipCPU{"Gzip CPU work coalesces revisions and bounds jobs, bytes and response leases", [] { - auto gate = std::make_shared(); - Executor executor({1, 2, 200000, 1000}, {gate}); - Completion first, head, full; - auto a = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768), Receiver{first, {}}); - auto b = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768, true), Receiver{head, {}}); - auto changed = std::string(gzipfixtures::fixed); - changed[4] = 1; - auto c = ex::connect(executor.submit(changed, 23768), Receiver{full, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - require(!executor.statistics().workerStarted); - ex::start(a); - gate->wait(); - ex::start(b); - ex::start(c); - full.wait(); - require(!static_cast(*full.result)); - require(c.encoded.empty()); - require(c.encoded.capacity() < gzipfixtures::fixed.size()); - require(executor.statistics().jobs == 1); - require(executor.statistics().waiters == 2); - require(executor.statistics().bytes <= 200000); - require(executor.statistics().decodes == 1); - gate->release(); - first.wait(); - head.wait(); - require(first.result->valid()); - require(first.result->decoded().size() == 23768); - require(first.result->takeBody().size() == 23768); - require(head.result->takeBody().empty()); - // Reservations survive completion and continue limiting slow HTTP sends. - require(executor.statistics().waiters == 2); - require(!executor.reserveResponse(1)); - first.result.reset(); - head.result.reset(); - executor.stop(); - executor.join(); - require(executor.statistics().jobs == 0); - require(executor.statistics().waiters == 0); - require(executor.statistics().bytes == 0); -}}; + auto gate = std::make_shared(); + Executor executor({1, 2, 200000, 1000}, {gate}); + Completion first, head, full; + auto a = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768), Receiver{first, {}}); + auto b = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768, true), Receiver{head, {}}); + auto changed = std::string(gzipfixtures::fixed); + changed[4] = 1; + auto c = ex::connect(executor.submit(changed, 23768), Receiver{full, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + require(!executor.statistics().workerStarted); + ex::start(a); + gate->wait(); + ex::start(b); + ex::start(c); + full.wait(); + require(!static_cast(*full.result)); + require(c.encoded.empty()); + require(c.encoded.capacity() < gzipfixtures::fixed.size()); + require(executor.statistics().jobs == 1); + require(executor.statistics().waiters == 2); + require(executor.statistics().bytes <= 200000); + require(executor.statistics().decodes == 1); + gate->release(); + first.wait(); + head.wait(); + require(first.result->valid()); + require(first.result->decoded().size() == 23768); + require(first.result->takeBody().size() == 23768); + require(head.result->takeBody().empty()); + // Reservations survive completion and continue limiting slow HTTP sends. + require(executor.statistics().waiters == 2); + require(!executor.reserveResponse(1)); + first.result.reset(); + head.result.reset(); + executor.stop(); + executor.join(); + require(executor.statistics().jobs == 0); + require(executor.statistics().waiters == 0); + require(executor.statistics().bytes == 0); + }}; const Scenario gzipWork{"Gzip work skips cancelled queued jobs and drains an active decode on stop", [] { - auto gate = std::make_shared(); - Executor executor({2, 3, 200000, 1000}, {gate}); - Completion active, queued; - ex::inplace_stop_source cancellation; - auto bytes = std::string(gzipfixtures::fixed); - auto a = ex::connect(executor.submit(bytes, 23768), Receiver{active, {}}); - bytes[4] = 1; - auto b = ex::connect(executor.submit(bytes, 23768), Receiver{queued, cancellation.get_token()}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(a); - gate->wait(); - ex::start(b); - require(executor.statistics().jobs == 2); - cancellation.request_stop(); - given("only the queued request is cancelled", [&] { - gate->release(); - active.wait(); - queued.wait(); - require(active.result->valid()); - require(queued.stopped); - require(executor.statistics().decodes == 1); - }); - given("the server stops while the first decode is running", [&] { - executor.stop(); - require(executor.statistics().jobs == 2); - gate->release(); - executor.join(); - active.wait(); - queued.wait(); - require(active.stopped); - require(queued.stopped); - require(executor.statistics().decodes == 1); - require(executor.statistics().bytes == 0); - }); -}}; + auto gate = std::make_shared(); + Executor executor({2, 3, 200000, 1000}, {gate}); + Completion active, queued; + ex::inplace_stop_source cancellation; + auto bytes = std::string(gzipfixtures::fixed); + auto a = ex::connect(executor.submit(bytes, 23768), Receiver{active, {}}); + bytes[4] = 1; + auto b = ex::connect(executor.submit(bytes, 23768), Receiver{queued, cancellation.get_token()}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(a); + gate->wait(); + ex::start(b); + require(executor.statistics().jobs == 2); + cancellation.request_stop(); + given("only the queued request is cancelled", [&] { + gate->release(); + active.wait(); + queued.wait(); + require(active.result->valid()); + require(queued.stopped); + require(executor.statistics().decodes == 1); + }); + given("the server stops while the first decode is running", [&] { + executor.stop(); + require(executor.statistics().jobs == 2); + gate->release(); + executor.join(); + active.wait(); + queued.wait(); + require(active.stopped); + require(queued.stopped); + require(executor.statistics().decodes == 1); + require(executor.statistics().bytes == 0); + }); + }}; const Scenario gzipWorkRejects{"Gzip work rejects saturation without starting a worker and preserves decode failures", [] { - given("zero job, waiter, byte or encoded-input capacity", [&] { - for (const auto limits : { - gzip::DecodeLimits{0, 2, 100000, 1000}, - {2, 0, 100000, 1000}, - {2, 2, 100, 1000}, - {2, 2, 100000, 498} - }) { - auto gate = std::make_shared(); - Executor executor(limits, {gate}); - Completion result; - auto op = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768), Receiver{result, {}}); - ex::start(op); - result.wait(); - require(!static_cast(*result.result)); - require(!executor.statistics().workerStarted); - require(executor.statistics().bytes == 0); - } - }); - given("corrupt gzip or a decoded output budget one byte too small", [&] { - for (const bool corrupt : {false, true}) { - auto gate = std::make_shared(); - Executor executor({}, {gate}); - Completion result; - auto bytes = std::string(gzipfixtures::fixed); - if (corrupt) - bytes[bytes.size() - 8] ^= 1; - auto op = ex::connect(executor.submit(bytes, corrupt ? 23768 : 23767), Receiver{result, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(op); - gate->wait(); - gate->release(); - result.wait(); - require(!result.result->valid()); - require(result.result->decoded().empty()); - } - }); -}}; + given("zero job, waiter, byte or encoded-input capacity", [&] { + for (const auto limits : { + gzip::DecodeLimits{0, 2, 100000, 1000}, + {2, 0, 100000, 1000}, + {2, 2, 100, 1000}, + {2, 2, 100000, 498} + }) { + auto gate = std::make_shared(); + Executor executor(limits, {gate}); + Completion result; + auto op = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768), Receiver{result, {}}); + ex::start(op); + result.wait(); + require(!static_cast(*result.result)); + require(!executor.statistics().workerStarted); + require(executor.statistics().bytes == 0); + } + }); + given("corrupt gzip or a decoded output budget one byte too small", [&] { + for (const bool corrupt : {false, true}) { + auto gate = std::make_shared(); + Executor executor({}, {gate}); + Completion result; + auto bytes = std::string(gzipfixtures::fixed); + if (corrupt) + bytes[bytes.size() - 8] ^= 1; + auto op = ex::connect(executor.submit(bytes, corrupt ? 23768 : 23767), Receiver{result, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(op); + gate->wait(); + gate->release(); + result.wait(); + require(!result.result->valid()); + require(result.result->decoded().empty()); + } + }); + }}; const Scenario gatedCold{"A gated cold gzip decode leaves HTTP and WebSocket upgrades responsive on the I/O thread", [] { - const auto port = freePort(); - auto gate = std::make_shared(); - Server server("127.0.0.1", port, ".", {}, {gate}); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket cold(clients), plain(clients), upgrade(clients), saturated(clients), pass(clients), warm(clients); - Finally cleanup{[&] { - gate->release(); - server.stop(); - io.join(); - server.drainUntilJoined(); - }}; - send(cold, port, "/asset.js"); - gate->wait(); - require(gate->worker != io.get_id()); - send(plain, port, "/plain.txt"); - require(receive(plain).ends_with("progress")); - send(upgrade, port, "/", "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"); - require(receive(upgrade).starts_with("HTTP/1.1 101")); - send(saturated, port, "/other.js"); - const auto rejected = receive(saturated); - require(rejected.starts_with("HTTP/1.1 503")); - require(rejected.find("Vary: Accept-Encoding") != std::string::npos); - send(pass, port, "/alias.js", "Accept-Encoding: gzip\r\n"); - const auto encoded = receive(pass); - require(encoded.find("Content-Encoding: x-gzip") != std::string::npos); - require(encoded.ends_with(gzipfixtures::fixed)); - gate->release(); - const auto decoded = receive(cold); - require(decoded.starts_with("HTTP/1.1 200")); - require(decoded.find("Content-Length: 23768") != std::string::npos); - send(warm, port, "/asset.js", {}, true); - const auto metadata = receive(warm, true); - require(metadata.find("Content-Length: 23768") != std::string::npos); - require(metadata.ends_with("\r\n\r\n")); - require(server.fallbackDecodeStatistics().decodes == 1); -}}; + const auto port = freePort(); + auto gate = std::make_shared(); + Server server("127.0.0.1", port, ".", {}, {gate}); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket cold(clients), plain(clients), upgrade(clients), saturated(clients), pass(clients), warm(clients); + Finally cleanup{[&] { + gate->release(); + server.stop(); + io.join(); + server.drainUntilJoined(); + }}; + send(cold, port, "/asset.js"); + gate->wait(); + require(gate->worker != io.get_id()); + send(plain, port, "/plain.txt"); + require(receive(plain).ends_with("progress")); + send(upgrade, port, "/", "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"); + require(receive(upgrade).starts_with("HTTP/1.1 101")); + send(saturated, port, "/other.js"); + const auto rejected = receive(saturated); + require(rejected.starts_with("HTTP/1.1 503")); + require(rejected.find("Vary: Accept-Encoding") != std::string::npos); + send(pass, port, "/alias.js", "Accept-Encoding: gzip\r\n"); + const auto encoded = receive(pass); + require(encoded.find("Content-Encoding: x-gzip") != std::string::npos); + require(encoded.ends_with(gzipfixtures::fixed)); + gate->release(); + const auto decoded = receive(cold); + require(decoded.starts_with("HTTP/1.1 200")); + require(decoded.find("Content-Length: 23768") != std::string::npos); + send(warm, port, "/asset.js", {}, true); + const auto metadata = receive(warm, true); + require(metadata.find("Content-Length: 23768") != std::string::npos); + require(metadata.ends_with("\r\n\r\n")); + require(server.fallbackDecodeStatistics().decodes == 1); + }}; const Scenario hTTPStop{"HTTP stop and disconnected clients cannot outlive the owned gzip worker", [] { - const auto port = freePort(); - auto gate = std::make_shared(); - Server server("127.0.0.1", port, ".", {}, {gate}); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket client(clients); - Finally cleanup{[&] { - gate->release(); - server.stop(); - if (io.joinable()) - io.join(); - server.drainUntilJoined(); - }}; - send(client, port, "/asset.js"); - gate->wait(); - client.close(); - server.stop(); - io.join(); - require(server.fallbackDecodeStatistics().jobs == 1); - gate->release(); - server.drainUntilJoined(); - require(server.fallbackDecodeStatistics().jobs == 0); - require(server.fallbackDecodeStatistics().waiters == 0); - require(server.fallbackDecodeStatistics().bytes == 0); -}}; + const auto port = freePort(); + auto gate = std::make_shared(); + Server server("127.0.0.1", port, ".", {}, {gate}); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket client(clients); + Finally cleanup{[&] { + gate->release(); + server.stop(); + if (io.joinable()) + io.join(); + server.drainUntilJoined(); + }}; + send(client, port, "/asset.js"); + gate->wait(); + client.close(); + server.stop(); + io.join(); + require(server.fallbackDecodeStatistics().jobs == 1); + gate->release(); + server.drainUntilJoined(); + require(server.fallbackDecodeStatistics().jobs == 0); + require(server.fallbackDecodeStatistics().waiters == 0); + require(server.fallbackDecodeStatistics().bytes == 0); + }}; const Scenario gzipCoalescing{"Gzip coalescing isolates consumer cancellation and different output budgets", [] { - auto gate = std::make_shared(); - Executor executor({2, 3, 200000, 1000}, {gate}); - Completion first, second; - ex::inplace_stop_source cancellation; - const auto bytes = std::string(gzipfixtures::fixed); - given("one of two consumers of a revision cancels locally", [&] { - auto a = ex::connect(executor.submit(bytes, 23768), Receiver{first, cancellation.get_token()}); - auto b = ex::connect(executor.submit(bytes, 23768, true), Receiver{second, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(a); - gate->wait(); - ex::start(b); - cancellation.request_stop(); - gate->release(); - first.wait(); - second.wait(); - require(first.stopped); - require(second.result->valid()); - require(executor.statistics().decodes == 1); - }); - given("a smaller output budget fails before a larger one validates the same bytes", [&] { - auto a = ex::connect(executor.submit(bytes, 23767), Receiver{first, {}}); - auto b = ex::connect(executor.submit(bytes, 23768), Receiver{second, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(a); - gate->wait(); - ex::start(b); - require(executor.statistics().jobs == 2); - gate->release(); - first.wait(); - second.wait(); - require(!first.result->valid()); - require(second.result->valid()); - require(executor.statistics().decodes == 2); - }); -}}; + auto gate = std::make_shared(); + Executor executor({2, 3, 200000, 1000}, {gate}); + Completion first, second; + ex::inplace_stop_source cancellation; + const auto bytes = std::string(gzipfixtures::fixed); + given("one of two consumers of a revision cancels locally", [&] { + auto a = ex::connect(executor.submit(bytes, 23768), Receiver{first, cancellation.get_token()}); + auto b = ex::connect(executor.submit(bytes, 23768, true), Receiver{second, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(a); + gate->wait(); + ex::start(b); + cancellation.request_stop(); + gate->release(); + first.wait(); + second.wait(); + require(first.stopped); + require(second.result->valid()); + require(executor.statistics().decodes == 1); + }); + given("a smaller output budget fails before a larger one validates the same bytes", [&] { + auto a = ex::connect(executor.submit(bytes, 23767), Receiver{first, {}}); + auto b = ex::connect(executor.submit(bytes, 23768), Receiver{second, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(a); + gate->wait(); + ex::start(b); + require(executor.statistics().jobs == 2); + gate->release(); + first.wait(); + second.wait(); + require(!first.result->valid()); + require(second.result->valid()); + require(executor.statistics().decodes == 2); + }); + }}; const Scenario gzipResponse{"Gzip response leases enforce exact capacity accounting after CPU completion", [] { - auto gate = std::make_shared(); - const auto bytes = std::string(gzipfixtures::fixed); - std::string buffer; - buffer.reserve(23768); - const auto budget = bytes.capacity() + 1 + 2 * (buffer.capacity() + 1); - Executor executor({2, 3, budget, 1000}, {gate}); - Completion first, rejected; - auto a = ex::connect(executor.submit(bytes, 23768), Receiver{first, {}}); - auto b = ex::connect(executor.submit(bytes, 23768, true), Receiver{rejected, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(a); - gate->wait(); - require(executor.statistics().bytes == budget); - ex::start(b); - rejected.wait(); - require(!static_cast(*rejected.result)); - gate->release(); - first.wait(); - require(executor.statistics().bytes == budget); - require(!executor.reserveResponse(1)); - first.result.reset(); - executor.stop(); - executor.join(); - require(executor.statistics().bytes == 0); -}}; + auto gate = std::make_shared(); + const auto bytes = std::string(gzipfixtures::fixed); + std::string buffer; + buffer.reserve(23768); + const auto budget = bytes.capacity() + 1 + 2 * (buffer.capacity() + 1); + Executor executor({2, 3, budget, 1000}, {gate}); + Completion first, rejected; + auto a = ex::connect(executor.submit(bytes, 23768), Receiver{first, {}}); + auto b = ex::connect(executor.submit(bytes, 23768, true), Receiver{rejected, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(a); + gate->wait(); + require(executor.statistics().bytes == budget); + ex::start(b); + rejected.wait(); + require(!static_cast(*rejected.result)); + gate->release(); + first.wait(); + require(executor.statistics().bytes == budget); + require(!executor.reserveResponse(1)); + first.result.reset(); + executor.stop(); + executor.join(); + require(executor.statistics().bytes == 0); + }}; const Scenario failedGzip{"Failed gzip responses retain their job slot until the response lease is released", [] { - for (const bool throws : {false, true}) { - auto gate = std::make_shared(); - gate->release(); - Executor executor({1, 2, 200000, 1000}, {gate, throws}); - Completion first, next; - auto corrupt = std::string(gzipfixtures::fixed); - corrupt[corrupt.size() - 8] ^= 1; - auto a = ex::connect(executor.submit(corrupt, 23768), Receiver{first, {}}); - auto b = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768, true), Receiver{next, {}}); - Finally cleanup{[&] { - executor.stop(); - executor.join(); - }}; - ex::start(a); - first.wait(); - require(static_cast(*first.result)); - require(!first.result->valid()); - // Completion and the consumer's receipt of a response do not release its reservation. - ex::start(b); - next.wait(); - require(!static_cast(*next.result)); - require(executor.statistics().decodes == 1); - require(executor.statistics().jobs == 1); - first.result.reset(); - executor.stop(); - executor.join(); - require(executor.statistics().jobs == 0); - require(executor.statistics().bytes == 0); - } -}}; + for (const bool throws : {false, true}) { + auto gate = std::make_shared(); + gate->release(); + Executor executor({1, 2, 200000, 1000}, {gate, throws}); + Completion first, next; + auto corrupt = std::string(gzipfixtures::fixed); + corrupt[corrupt.size() - 8] ^= 1; + auto a = ex::connect(executor.submit(corrupt, 23768), Receiver{first, {}}); + auto b = ex::connect(executor.submit(std::string(gzipfixtures::fixed), 23768, true), Receiver{next, {}}); + Finally cleanup{[&] { + executor.stop(); + executor.join(); + }}; + ex::start(a); + first.wait(); + require(static_cast(*first.result)); + require(!first.result->valid()); + // Completion and the consumer's receipt of a response do not release its reservation. + ex::start(b); + next.wait(); + require(!static_cast(*next.result)); + require(executor.statistics().decodes == 1); + require(executor.statistics().jobs == 1); + first.result.reset(); + executor.stop(); + executor.join(); + require(executor.statistics().jobs == 0); + require(executor.statistics().bytes == 0); + } + }}; const Scenario gzipCompletion{"Gzip completion resumes on the supplied I/O scheduler", [] { - auto gate = std::make_shared(); - Executor executor({}, {gate}); - Net::IoContext context; - auto work = context.make_work_guard(); - Completion result; - auto op = ex::connect(ex::continues_on(executor.submit(std::string(gzipfixtures::fixed), 23768), context.get_scheduler()), Receiver{result, {}}); - std::jthread io([&] { - context.run(); - }); - const auto ioThread = io.get_id(); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - context.stop(); - io.join(); - }}; - ex::start(op); - gate->wait(); - gate->release(); - result.wait(); - require(result.thread == ioThread); - require(result.thread != gate->worker); - require(result.result->valid()); -}}; + auto gate = std::make_shared(); + Executor executor({}, {gate}); + Net::IoContext context; + auto work = context.make_work_guard(); + Completion result; + auto op = ex::connect(ex::continues_on(executor.submit(std::string(gzipfixtures::fixed), 23768), context.get_scheduler()), + Receiver{result, {}}); + std::jthread io([&] { + context.run(); + }); + const auto ioThread = io.get_id(); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + context.stop(); + io.join(); + }}; + ex::start(op); + gate->wait(); + gate->release(); + result.wait(); + require(result.thread == ioThread); + require(result.thread != gate->worker); + require(result.result->valid()); + }}; const Scenario disconnectedGzip{"A disconnected gzip requester leaves the shared decode usable by another browser", [] { - const auto port = freePort(); - auto gate = std::make_shared(); - Server server("127.0.0.1", port, ".", {}, {gate}); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket lost(clients), plain(clients), next(clients); - Finally cleanup{[&] { - gate->release(); - server.stop(); - io.join(); - server.drainUntilJoined(); - }}; - send(lost, port, "/asset.js"); - gate->wait(); - lost.close(); - send(plain, port, "/plain.txt"); - require(receive(plain).ends_with("progress")); - gate->release(); - send(next, port, "/asset.js"); - const auto response = receive(next); - require(response.starts_with("HTTP/1.1 200")); - require(response.find("Content-Length: 23768") != std::string::npos); - require(server.fallbackDecodeStatistics().decodes == 1); -}}; + const auto port = freePort(); + auto gate = std::make_shared(); + Server server("127.0.0.1", port, ".", {}, {gate}); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket lost(clients), plain(clients), next(clients); + Finally cleanup{[&] { + gate->release(); + server.stop(); + io.join(); + server.drainUntilJoined(); + }}; + send(lost, port, "/asset.js"); + gate->wait(); + lost.close(); + send(plain, port, "/plain.txt"); + require(receive(plain).ends_with("progress")); + gate->release(); + send(next, port, "/asset.js"); + const auto response = receive(next); + require(response.starts_with("HTTP/1.1 200")); + require(response.find("Content-Length: 23768") != std::string::npos); + require(server.fallbackDecodeStatistics().decodes == 1); + }}; const Scenario hTTPGzip{"HTTP gzip workers preserve failure statuses and remain lazy on pass-through", [] { - const auto port = freePort(); - auto gate = std::make_shared(); - gate->release(); - given("ordinary and pass-through responses need no worker", [&] { - Server server("127.0.0.1", port, ".", {}, {gate}); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket plain(clients), encoded(clients), allocationFailure(clients); - Finally cleanup{[&] { - server.stop(); - io.join(); - server.drainUntilJoined(); - }}; - send(allocationFailure, port, "/allocation-failure.js"); - require(receive(allocationFailure).starts_with("HTTP/1.1 503")); - send(plain, port, "/plain.txt"); - require(receive(plain).ends_with("progress")); - send(encoded, port, "/asset.js", "Accept-Encoding: gzip\r\n"); - require(receive(encoded).ends_with(gzipfixtures::fixed)); - require(!server.fallbackDecodeStatistics().workerStarted); - }); - given("invalid gzip and exceptions from the worker", [&] { - for (const bool fail : {false, true}) { - for (const bool head : {false, true}) { - // A received response can precede release of its server-side lease. Give each - // error case its own one-job server so this tests 500, rather than admission (503). - Server server("127.0.0.1", port, ".", {}, {gate, fail}); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket client(clients); - Finally cleanup{[&] { - server.stop(); - io.join(); - server.drainUntilJoined(); - }}; - send(client, port, fail ? "/asset.js" : "/corrupt.js", {}, head); - const auto response = receive(client, head); - auto scope = info("fail ", fail, ", head ", head, ", response ", response); - require(response.starts_with("HTTP/1.1 500")); - require(response.find("Vary: Accept-Encoding") != std::string::npos); - } - } - }); -}}; + const auto port = freePort(); + auto gate = std::make_shared(); + gate->release(); + given("ordinary and pass-through responses need no worker", [&] { + Server server("127.0.0.1", port, ".", {}, {gate}); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket plain(clients), encoded(clients), allocationFailure(clients); + Finally cleanup{[&] { + server.stop(); + io.join(); + server.drainUntilJoined(); + }}; + send(allocationFailure, port, "/allocation-failure.js"); + require(receive(allocationFailure).starts_with("HTTP/1.1 503")); + send(plain, port, "/plain.txt"); + require(receive(plain).ends_with("progress")); + send(encoded, port, "/asset.js", "Accept-Encoding: gzip\r\n"); + require(receive(encoded).ends_with(gzipfixtures::fixed)); + require(!server.fallbackDecodeStatistics().workerStarted); + }); + given("invalid gzip and exceptions from the worker", [&] { + for (const bool fail : {false, true}) { + for (const bool head : {false, true}) { + // A received response can precede release of its server-side lease. Give each + // error case its own one-job server so this tests 500, rather than admission (503). + Server server("127.0.0.1", port, ".", {}, {gate, fail}); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket client(clients); + Finally cleanup{[&] { + server.stop(); + io.join(); + server.drainUntilJoined(); + }}; + send(client, port, fail ? "/asset.js" : "/corrupt.js", {}, head); + const auto response = receive(client, head); + auto scope = info("fail ", fail, ", head ", head, ", response ", response); + require(response.starts_with("HTTP/1.1 500")); + require(response.find("Vary: Accept-Encoding") != std::string::npos); + } + } + }); + }}; namespace { struct SmallInput : DefaultBuffersPolicy { @@ -597,101 +598,101 @@ struct ShrinkingBudget : DefaultBuffersPolicy { } // namespace const Scenario hTTPRejects{"HTTP rejects oversized fallback input before enqueue while preserving gzip pass-through", [] { - RequestHandler handler("."); - Request request; - request.method = Request::Method::Get; - request.uri = "/asset.js"; - require(handler.handleRequest(request).statusCode == Response::ok); - require(handler.fallbackCacheStatistics().entries == 1); - for (const auto method : {Request::Method::Get, Request::Method::Head}) { - request.method = method; - const auto prepared = handler.prepareRequest(request); - require(prepared.response.statusCode == Response::internalServerError); - require(!prepared.needsDecode); - require(prepared.response.getHeaderValue("Vary") == "Accept-Encoding"); - } - const auto port = freePort(); - Server server("127.0.0.1", port); - std::jthread io([&] { - server.run(); - }); - Net::IoContext clients; - Net::Socket fallback(clients), encoded(clients); - Finally cleanup{[&] { - server.stop(); - io.join(); - server.drainUntilJoined(); - }}; - send(fallback, port, "/asset.js"); - require(receive(fallback).starts_with("HTTP/1.1 500")); - send(encoded, port, "/asset.js", "Accept-Encoding: gzip\r\n"); - require(receive(encoded).ends_with(gzipfixtures::fixed)); - require(!server.fallbackDecodeStatistics().workerStarted); -}}; + RequestHandler handler("."); + Request request; + request.method = Request::Method::Get; + request.uri = "/asset.js"; + require(handler.handleRequest(request).statusCode == Response::ok); + require(handler.fallbackCacheStatistics().entries == 1); + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + const auto prepared = handler.prepareRequest(request); + require(prepared.response.statusCode == Response::internalServerError); + require(!prepared.needsDecode); + require(prepared.response.getHeaderValue("Vary") == "Accept-Encoding"); + } + const auto port = freePort(); + Server server("127.0.0.1", port); + std::jthread io([&] { + server.run(); + }); + Net::IoContext clients; + Net::Socket fallback(clients), encoded(clients); + Finally cleanup{[&] { + server.stop(); + io.join(); + server.drainUntilJoined(); + }}; + send(fallback, port, "/asset.js"); + require(receive(fallback).starts_with("HTTP/1.1 500")); + send(encoded, port, "/asset.js", "Accept-Encoding: gzip\r\n"); + require(receive(encoded).ends_with(gzipfixtures::fixed)); + require(!server.fallbackDecodeStatistics().workerStarted); + }}; const Scenario hTTPRechecks{"HTTP rechecks the output budget after a suspended worker finishes", [] { - const auto oldLimit = ShrinkingBudget::maxDecodedAssetSize; - Finally restore{[oldLimit] { - ShrinkingBudget::maxDecodedAssetSize = oldLimit; - }}; - ShrinkingBudget::maxDecodedAssetSize = 23768; - auto gate = std::make_shared(); - Executor executor({}, {gate}); - RequestHandler handler{"."}; - Request request; - request.method = Request::Method::Get; - request.uri = "/asset.js"; - auto prepared = handler.prepareRequest(request); - require(prepared.needsDecode); - Completion result; - auto op = ex::connect(executor.submit(std::move(prepared.response.content), prepared.limit), Receiver{result, {}}); - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(op); - gate->wait(); - ShrinkingBudget::maxDecodedAssetSize = 23767; - gate->release(); - result.wait(); - require(handler.finish(std::move(prepared), *result.result).statusCode == Response::internalServerError); - require(handler.fallbackCacheStatistics().entries == 0); -}}; + const auto oldLimit = ShrinkingBudget::maxDecodedAssetSize; + Finally restore{[oldLimit] { + ShrinkingBudget::maxDecodedAssetSize = oldLimit; + }}; + ShrinkingBudget::maxDecodedAssetSize = 23768; + auto gate = std::make_shared(); + Executor executor({}, {gate}); + RequestHandler handler{"."}; + Request request; + request.method = Request::Method::Get; + request.uri = "/asset.js"; + auto prepared = handler.prepareRequest(request); + require(prepared.needsDecode); + Completion result; + auto op = ex::connect(executor.submit(std::move(prepared.response.content), prepared.limit), Receiver{result, {}}); + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(op); + gate->wait(); + ShrinkingBudget::maxDecodedAssetSize = 23767; + gate->release(); + result.wait(); + require(handler.finish(std::move(prepared), *result.result).statusCode == Response::internalServerError); + require(handler.fallbackCacheStatistics().entries == 0); + }}; const Scenario newGzip{"New gzip consumers retry work skipped or interrupted by a decoder exception", [] { - for (const bool failed : {false, true}) { - auto gate = std::make_shared(); - Executor executor({4, 4, 400000, 1000}, {gate, false, std::make_shared(failed)}); - Completion active, abandoned, retry; - ex::inplace_stop_source cancellation; - auto bytes = std::string(gzipfixtures::fixed); - auto a = ex::connect(executor.submit(bytes, 23768), Receiver{active, {}}); - if (!failed) - bytes[4] = 1; - auto b = ex::connect(executor.submit(bytes, 23768), Receiver{abandoned, cancellation.get_token()}); - auto c = ex::connect(executor.submit(bytes, 23768), Receiver{retry, {}}); - // Reenter admission during completion: the worker still owns the completed Work. - auto& first = failed ? active : abandoned; - first.onCompletion = [&] { - ex::start(c); - }; - Finally cleanup{[&] { - gate->release(); - executor.stop(); - executor.join(); - }}; - ex::start(a); - gate->wait(); - if (!failed) { - ex::start(b); - cancellation.request_stop(); - } - gate->release(); - first.wait(); - retry.wait(); - require(static_cast(*retry.result)); - require(executor.statistics().decodes == 2); - require(retry.result->valid()); - } -}}; + for (const bool failed : {false, true}) { + auto gate = std::make_shared(); + Executor executor({4, 4, 400000, 1000}, {gate, false, std::make_shared(failed)}); + Completion active, abandoned, retry; + ex::inplace_stop_source cancellation; + auto bytes = std::string(gzipfixtures::fixed); + auto a = ex::connect(executor.submit(bytes, 23768), Receiver{active, {}}); + if (!failed) + bytes[4] = 1; + auto b = ex::connect(executor.submit(bytes, 23768), Receiver{abandoned, cancellation.get_token()}); + auto c = ex::connect(executor.submit(bytes, 23768), Receiver{retry, {}}); + // Reenter admission during completion: the worker still owns the completed Work. + auto& first = failed ? active : abandoned; + first.onCompletion = [&] { + ex::start(c); + }; + Finally cleanup{[&] { + gate->release(); + executor.stop(); + executor.join(); + }}; + ex::start(a); + gate->wait(); + if (!failed) { + ex::start(b); + cancellation.request_stop(); + } + gate->release(); + first.wait(); + retry.wait(); + require(static_cast(*retry.result)); + require(executor.statistics().decodes == 2); + require(retry.result->valid()); + } + }}; diff --git a/test/unit/GzipTests.cpp b/test/unit/GzipTests.cpp index 768d328d..751a626c 100644 --- a/test/unit/GzipTests.cpp +++ b/test/unit/GzipTests.cpp @@ -1,7 +1,7 @@ #include "GzipFixtures.hpp" -#include #include #include +#include #include @@ -22,460 +22,484 @@ std::string payload() { } // namespace const Scenario gzipDecoding{"Gzip decoding validates complete bounded members", [] { - const auto expected = payload(); - given("fixed and dynamic Huffman blocks, with optional gzip fields", [&] { - for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional}) { - when("decoding a complete member of ", bytes.size(), " bytes", [&] { - then("the exact binary content is returned", [&] { - require(decodeGzip(bytes) == expected); - require(decodeGzip(bytes, expected.size()) == expected); - require(!decodeGzip(bytes, expected.size() - 1)); - }); - }); - when("truncating a member of ", bytes.size(), " bytes at every byte boundary", [&] { - then("every prefix is rejected", [&] { - for (std::size_t length = 0; length < bytes.size(); ++length) { - auto scope = info("length ", length); - require(!decodeGzip(bytes.substr(0, length))); - } - }); - }); - } - }); - given("a gzip member with a stored DEFLATE block", [&] { - // A final, byte-aligned stored block containing 'abc', CRC32 and ISIZE. - const std::string bytes("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" - "\x01\x03\x00\xfc\xff" - "abc" - "\xc2\x41\x24\x35\x03\x00\x00\x00", - 26); - then("stored bytes and their complement are checked", [&] { - require(decodeGzip(bytes) == "abc"); - auto corrupt = bytes; - corrupt[13] ^= 1; - require(!decodeGzip(corrupt)); - require(!decodeGzip(bytes, 2)); - for (std::size_t length = 0; length < bytes.size(); ++length) - require(!decodeGzip(std::string_view(bytes).substr(0, length))); - }); - }); - given("empty and concatenated members", [&] { - const auto bytes = std::string(gzipfixtures::dynamic) + std::string(gzipfixtures::empty) + std::string(gzipfixtures::fixed); - then("members are decoded independently under one total budget", [&] { - require(decodeGzip(gzipfixtures::empty, 0) == ""); - require(decodeGzip(bytes) == expected + expected); - require(!decodeGzip(bytes, expected.size())); - require(!decodeGzip(std::string(gzipfixtures::dynamic) + "garbage")); - }); - }); - given("corrupt gzip metadata, trailer or block type", [&] { - for (const auto offset : {0u, 1u, 2u, 3u, 10u}) { - auto bytes = std::string(gzipfixtures::dynamic); - bytes[offset] = static_cast(0xff); - require(!decodeGzip(bytes)); - } - for (std::size_t offset = gzipfixtures::dynamic.size() - 8; offset < gzipfixtures::dynamic.size(); ++offset) { - auto bytes = std::string(gzipfixtures::dynamic); - bytes[offset] ^= 1; - require(!decodeGzip(bytes)); - } - auto bytes = std::string(gzipfixtures::optional); - bytes[10] = static_cast(0xff); // Invalid extra-field length. - require(!decodeGzip(bytes)); - bytes = gzipfixtures::optional; - bytes[17] ^= 1; // Header CRC covers the optional name, too. - require(!decodeGzip(bytes)); - }); -}}; + const auto expected = payload(); + given("fixed and dynamic Huffman blocks, with optional gzip fields", [&] { + for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional}) { + when("decoding a complete member of ", bytes.size(), " bytes", [&] { + then("the exact binary content is returned", [&] { + require(decodeGzip(bytes) == expected); + require(decodeGzip(bytes, expected.size()) == expected); + require(!decodeGzip(bytes, expected.size() - 1)); + }); + }); + when("truncating a member of ", bytes.size(), " bytes at every byte boundary", [&] { + then("every prefix is rejected", [&] { + for (std::size_t length = 0; length < bytes.size(); ++length) { + auto scope = info("length ", length); + require(!decodeGzip(bytes.substr(0, length))); + } + }); + }); + } + }); + given("a gzip member with a stored DEFLATE block", [&] { + // A final, byte-aligned stored block containing 'abc', CRC32 and ISIZE. + const std::string bytes("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" + "\x01\x03\x00\xfc\xff" + "abc" + "\xc2\x41\x24\x35\x03\x00\x00\x00", + 26); + then("stored bytes and their complement are checked", [&] { + require(decodeGzip(bytes) == "abc"); + auto corrupt = bytes; + corrupt[13] ^= 1; + require(!decodeGzip(corrupt)); + require(!decodeGzip(bytes, 2)); + for (std::size_t length = 0; length < bytes.size(); ++length) + require(!decodeGzip(std::string_view(bytes).substr(0, length))); + }); + }); + given("empty and concatenated members", [&] { + const auto bytes = std::string(gzipfixtures::dynamic) + std::string(gzipfixtures::empty) + std::string(gzipfixtures::fixed); + then("members are decoded independently under one total budget", [&] { + require(decodeGzip(gzipfixtures::empty, 0) == ""); + require(decodeGzip(bytes) == expected + expected); + require(!decodeGzip(bytes, expected.size())); + require(!decodeGzip(std::string(gzipfixtures::dynamic) + "garbage")); + }); + }); + given("corrupt gzip metadata, trailer or block type", [&] { + for (const auto offset : {0u, 1u, 2u, 3u, 10u}) { + auto bytes = std::string(gzipfixtures::dynamic); + bytes[offset] = static_cast(0xff); + require(!decodeGzip(bytes)); + } + for (std::size_t offset = gzipfixtures::dynamic.size() - 8; offset < gzipfixtures::dynamic.size(); ++offset) { + auto bytes = std::string(gzipfixtures::dynamic); + bytes[offset] ^= 1; + require(!decodeGzip(bytes)); + } + auto bytes = std::string(gzipfixtures::optional); + bytes[10] = static_cast(0xff); // Invalid extra-field length. + require(!decodeGzip(bytes)); + bytes = gzipfixtures::optional; + bytes[17] ^= 1; // Header CRC covers the optional name, too. + require(!decodeGzip(bytes)); + }); + }}; const Scenario gzipRejects{"Gzip rejects invalid Huffman codes and match distances", [] { - given("malformed DEFLATE blocks", [&] { - then("decoding rejects the blocks without accessing missing history or table entries", [&] { - for (const auto bytes : {gzipfixtures::invalidDistance, - gzipfixtures::reservedLiteral, - gzipfixtures::reservedDistance, - gzipfixtures::oversubscribed, - gzipfixtures::repeatWithoutPrevious, - gzipfixtures::repeatOverflow, - gzipfixtures::missingEnd}) { - require(!decodeGzip(bytes)); - } - }); - }); -}}; + given("malformed DEFLATE blocks", [&] { + then("decoding rejects the blocks without accessing missing history or table entries", [&] { + for (const auto bytes : {gzipfixtures::invalidDistance, + gzipfixtures::reservedLiteral, + gzipfixtures::reservedDistance, + gzipfixtures::oversubscribed, + gzipfixtures::repeatWithoutPrevious, + gzipfixtures::repeatOverflow, + gzipfixtures::missingEnd}) { + require(!decodeGzip(bytes)); + } + }); + }); + }}; const Scenario gzipRejectsReserved{"Gzip rejects reserved distance declarations and trailing padding", [] { - given("dynamic blocks declaring 31 or 32 distance symbols", [&] { - then("the declarations are rejected even when no distance is used", [&] { - require(!decodeGzip(gzipfixtures::distanceCount31)); - require(!decodeGzip(gzipfixtures::distanceCount32)); - }); - }); - given("zero padding after a complete member", [&] { - const auto bytes = std::string(gzipfixtures::empty) + std::string(8, '\0'); - then("strict member parsing rejects the padding", [&] { - require(!decodeGzip(bytes)); - }); - }); -}}; + given("dynamic blocks declaring 31 or 32 distance symbols", [&] { + then("the declarations are rejected even when no distance is used", [&] { + require(!decodeGzip(gzipfixtures::distanceCount31)); + require(!decodeGzip(gzipfixtures::distanceCount32)); + }); + }); + given("zero padding after a complete member", [&] { + const auto bytes = std::string(gzipfixtures::empty) + std::string(8, '\0'); + then("strict member parsing rejects the padding", [&] { + require(!decodeGzip(bytes)); + }); + }); + }}; const Scenario gzipDefault{"Gzip default output budget is four MiB across concatenated members", [] { - const auto memberSize = payload().size(); - const auto memberCount = (4 * 1024 * 1024) / memberSize + 1; - std::string bytes; - for (std::size_t index = 0; index < memberCount; ++index) - bytes += gzipfixtures::fixed; - then("the default rejects a response just above four MiB", [&] { - require(!decodeGzip(bytes)); - }); - then("an explicitly larger budget can permit the same valid content", [&] { - const auto decoded = decodeGzip(bytes, memberCount * memberSize); - require(decoded); - require(decoded->size() == memberCount * memberSize); - }); -}}; + const auto memberSize = payload().size(); + const auto memberCount = (4 * 1024 * 1024) / memberSize + 1; + std::string bytes; + for (std::size_t index = 0; index < memberCount; ++index) + bytes += gzipfixtures::fixed; + then("the default rejects a response just above four MiB", [&] { + require(!decodeGzip(bytes)); + }); + then("an explicitly larger budget can permit the same valid content", [&] { + const auto decoded = decodeGzip(bytes, memberCount * memberSize); + require(decoded); + require(decoded->size() == memberCount * memberSize); + }); + }}; const Scenario gzipMatch{"Gzip match copies preserve overlapping history across string growth", [] { - using webfront::http::gzip::InflateContext; - given("a periodic match longer than its distance", [&] { - std::string output = "abc"; - InflateContext context{output, 0, 1000}; - context.copyMatch(258, 3); - then("newly written bytes extend the same periodic sequence", [&] { - require(output.size() == 261); - for (std::size_t index = 0; index < output.size(); ++index) - require(output[index] == "abc"[index % 3]); - }); - }); - given("a repeated byte and an exact output budget", [&] { - std::string output = "x"; - InflateContext context{output, 0, 259}; - context.copyMatch(258, 1); - then("the copy grows safely and the next copy fails without modifying output", [&] { - require(output == std::string(259, 'x')); - requireThrows([&] { context.copyMatch(3, 1); }); - require(output == std::string(259, 'x')); - }); - }); -}}; + using webfront::http::gzip::InflateContext; + given("a periodic match longer than its distance", [&] { + std::string output = "abc"; + InflateContext context{output, 0, 1000}; + context.copyMatch(258, 3); + then("newly written bytes extend the same periodic sequence", [&] { + require(output.size() == 261); + for (std::size_t index = 0; index < output.size(); ++index) + require(output[index] == "abc"[index % 3]); + }); + }); + given("a repeated byte and an exact output budget", [&] { + std::string output = "x"; + InflateContext context{output, 0, 259}; + context.copyMatch(258, 1); + then("the copy grows safely and the next copy fails without modifying output", [&] { + require(output == std::string(259, 'x')); + requireThrows([&] { + context.copyMatch(3, 1); + }); + require(output == std::string(259, 'x')); + }); + }); + }}; const Scenario gzipBulk{"Gzip bulk reads require alignment and complete input", [] { - webfront::http::gzip::GzipReader reader("abc"); - given("an unaligned reader", [&] { - reader.bits(1); - requireThrows([&] { reader.readBytes(1); }); - reader.align(); - then("aligned reads consume only available bytes", [&] { - require(reader.readBytes(2) == "bc"); - require(reader.done()); - require(reader.readBytes(0).empty()); - requireThrows([&] { reader.readBytes(1); }); - }); - }); - given("a truncated read", [&] { - requireThrows([&] { reader.readBytes(4); }); - then("failure leaves the reader position unchanged", [&] { - require(reader.readBytes(3) == "abc"); - }); - }); -}}; + webfront::http::gzip::GzipReader reader("abc"); + given("an unaligned reader", [&] { + reader.bits(1); + requireThrows([&] { + reader.readBytes(1); + }); + reader.align(); + then("aligned reads consume only available bytes", [&] { + require(reader.readBytes(2) == "bc"); + require(reader.done()); + require(reader.readBytes(0).empty()); + requireThrows([&] { + reader.readBytes(1); + }); + }); + }); + given("a truncated read", [&] { + requireThrows([&] { + reader.readBytes(4); + }); + then("failure leaves the reader position unchanged", [&] { + require(reader.readBytes(3) == "abc"); + }); + }); + }}; const Scenario gzipCRC32{"Gzip CRC32 matches standard and binary reference vectors", [] { - using webfront::http::gzip::gzipCrc; - given("the empty input and the standard check vector", [&] { - then("the IEEE CRC32 values match", [&] { - require(gzipCrc("") == 0u); - require(gzipCrc("123456789") == 0xcbf43926u); - }); - }); - given("every byte value, including bytes with the high bit set", [&] { - std::string bytes; - for (unsigned byte = 0; byte < 256; ++byte) - bytes.push_back(static_cast(byte)); - then("the result matches the independent zlib reference", [&] { - require(gzipCrc(bytes) == 0x29058c73u); - }); - }); -}}; + using webfront::http::gzip::gzipCrc; + given("the empty input and the standard check vector", [&] { + then("the IEEE CRC32 values match", [&] { + require(gzipCrc("") == 0u); + require(gzipCrc("123456789") == 0xcbf43926u); + }); + }); + given("every byte value, including bytes with the high bit set", [&] { + std::string bytes; + for (unsigned byte = 0; byte < 256; ++byte) + bytes.push_back(static_cast(byte)); + then("the result matches the independent zlib reference", [&] { + require(gzipCrc(bytes) == 0x29058c73u); + }); + }); + }}; const Scenario validatedGzip{"Validated gzip cache shares GET content and HEAD metadata within the current output budget", [] { - using webfront::http::gzip::ValidatedCache; - ValidatedCache cache(100000); - auto bytes = std::string(gzipfixtures::fixed); - given("HEAD validates a revision before GET", [&] { - require(cache.resolve(bytes, 23768, true) == 23768); - require(bytes.empty()); - bytes = gzipfixtures::fixed; - require(cache.resolve(bytes, 23768) == 23768); - require(bytes == payload()); - then("GET reuses the validated bytes and length", [&] { - require(cache.statistics().decodes == 1); - require(cache.statistics().hits == 1); - }); - then("a smaller active output budget cannot reuse the larger result", [&] { - for (const bool head : {false, true}) { - bytes = gzipfixtures::fixed; - require(!cache.resolve(bytes, 23767, head)); - } - require(cache.statistics().decodes == 1); - bytes = gzipfixtures::fixed; - require(cache.resolve(bytes, 23768, true) == 23768); - }); - }); -}}; + using webfront::http::gzip::ValidatedCache; + ValidatedCache cache(100000); + auto bytes = std::string(gzipfixtures::fixed); + given("HEAD validates a revision before GET", [&] { + require(cache.resolve(bytes, 23768, true) == 23768); + require(bytes.empty()); + bytes = gzipfixtures::fixed; + require(cache.resolve(bytes, 23768) == 23768); + require(bytes == payload()); + then("GET reuses the validated bytes and length", [&] { + require(cache.statistics().decodes == 1); + require(cache.statistics().hits == 1); + }); + then("a smaller active output budget cannot reuse the larger result", [&] { + for (const bool head : {false, true}) { + bytes = gzipfixtures::fixed; + require(!cache.resolve(bytes, 23767, head)); + } + require(cache.statistics().decodes == 1); + bytes = gzipfixtures::fixed; + require(cache.resolve(bytes, 23768, true) == 23768); + }); + }); + }}; const Scenario validatedGzipCache{"Validated gzip cache bounds keys and data and evicts the least recently used revision", [] { - using webfront::http::gzip::ValidatedCache; - auto first = std::string(gzipfixtures::fixed); - auto second = first; - auto third = first; - // MTIME changes the compressed revision without changing the validated payload. - second[4] = 1; - third[4] = 2; - ValidatedCache probe(100000); - auto bytes = first; - require(probe.resolve(bytes, 23768)); - const auto charge = probe.statistics().retainedBytes; - require(charge >= first.size() + 23768); - given("room for exactly two revisions", [&] { - ValidatedCache cache(2 * charge); - for (const auto& revision : {first, second, first, third, first}) { - bytes = revision; - require(cache.resolve(bytes, 23768)); - require(cache.statistics().retainedBytes <= 2 * charge); - } - then("the touched first revision survives while the second is evicted", [&] { - require(cache.statistics().decodes == 3); - require(cache.statistics().hits == 2); - require(cache.statistics().entries == 2); - bytes = second; - require(cache.resolve(bytes, 23768)); - require(cache.statistics().decodes == 4); - }); - }); - given("a budget one byte below a complete entry, or disabled caching", [&] { - for (const auto budget : {std::size_t{0}, charge - 1}) { - ValidatedCache cache(budget); - for (const bool head : {false, true}) { - bytes = first; - require(cache.resolve(bytes, 23768, head)); + using webfront::http::gzip::ValidatedCache; + auto first = std::string(gzipfixtures::fixed); + auto second = first; + auto third = first; + // MTIME changes the compressed revision without changing the validated payload. + second[4] = 1; + third[4] = 2; + ValidatedCache probe(100000); + auto bytes = first; + require(probe.resolve(bytes, 23768)); + const auto charge = probe.statistics().retainedBytes; + require(charge >= first.size() + 23768); + given("room for exactly two revisions", [&] { + ValidatedCache cache(2 * charge); + for (const auto& revision : {first, second, first, third, first}) { + bytes = revision; + require(cache.resolve(bytes, 23768)); + require(cache.statistics().retainedBytes <= 2 * charge); + } + then("the touched first revision survives while the second is evicted", [&] { + require(cache.statistics().decodes == 3); + require(cache.statistics().hits == 2); + require(cache.statistics().entries == 2); + bytes = second; + require(cache.resolve(bytes, 23768)); + require(cache.statistics().decodes == 4); + }); + }); + given("a budget one byte below a complete entry, or disabled caching", [&] { + for (const auto budget : {std::size_t{0}, charge - 1}) { + ValidatedCache cache(budget); + for (const bool head : {false, true}) { + bytes = first; + require(cache.resolve(bytes, 23768, head)); + } + then("both requests succeed without retaining partial keys or metadata", [&] { + require(cache.statistics().retainedBytes == 0); + require(cache.statistics().entries == 0); + require(cache.statistics().decodes == 2); + }); + } + }); + given("an oversized revision alongside a retained asset", [&] { + ValidatedCache cache(charge); + bytes = first; + require(cache.resolve(bytes, 23768)); + bytes = first + first; + require(cache.resolve(bytes, 47536)); + bytes = first; + require(cache.resolve(bytes, 23768)); + require(cache.statistics().decodes == 2); + require(cache.statistics().hits == 1); + }); + }}; + +const Scenario validatedGzipCacheNever{ + "Validated gzip cache never promotes invalid streams or trusts ISIZE alone", + [] { + webfront::http::gzip::ValidatedCache cache(100000); + given("corrupt CRC, invalid trailer, truncated and concatenated invalid members", [&] { + auto corrupt = std::string(gzipfixtures::fixed); + corrupt[corrupt.size() - 8] ^= 1; + auto wrongSize = std::string(gzipfixtures::fixed); + wrongSize.back() = 1; + for (const auto& invalid : {corrupt, wrongSize, std::string(gzipfixtures::fixed.substr(0, 498)), std::string(gzipfixtures::fixed) + corrupt}) { + for (const bool head : {false, true}) { + auto bytes = invalid; + require(!cache.resolve(bytes, 100000, head)); + } } - then("both requests succeed without retaining partial keys or metadata", [&] { - require(cache.statistics().retainedBytes == 0); + then("every attempt validates again and nothing is retained", [&] { + require(cache.statistics().decodes == 8); require(cache.statistics().entries == 0); - require(cache.statistics().decodes == 2); + require(cache.statistics().retainedBytes == 0); }); - } - }); - given("an oversized revision alongside a retained asset", [&] { - ValidatedCache cache(charge); - bytes = first; - require(cache.resolve(bytes, 23768)); - bytes = first + first; - require(cache.resolve(bytes, 47536)); - bytes = first; - require(cache.resolve(bytes, 23768)); - require(cache.statistics().decodes == 2); - require(cache.statistics().hits == 1); - }); -}}; - -const Scenario validatedGzipCacheNever{"Validated gzip cache never promotes invalid streams or trusts ISIZE alone", [] { - webfront::http::gzip::ValidatedCache cache(100000); - given("corrupt CRC, invalid trailer, truncated and concatenated invalid members", [&] { - auto corrupt = std::string(gzipfixtures::fixed); - corrupt[corrupt.size() - 8] ^= 1; - auto wrongSize = std::string(gzipfixtures::fixed); - wrongSize.back() = 1; - for (const auto& invalid : {corrupt, wrongSize, std::string(gzipfixtures::fixed.substr(0, 498)), std::string(gzipfixtures::fixed) + corrupt}) { - for (const bool head : {false, true}) { - auto bytes = invalid; - require(!cache.resolve(bytes, 100000, head)); - } - } - then("every attempt validates again and nothing is retained", [&] { - require(cache.statistics().decodes == 8); - require(cache.statistics().entries == 0); - require(cache.statistics().retainedBytes == 0); }); - }); - given("an initial decode failing its output budget", [&] { - auto bytes = std::string(gzipfixtures::fixed); - require(!cache.resolve(bytes, 1)); - bytes = gzipfixtures::fixed; - require(cache.resolve(bytes, 23768)); - require(cache.statistics().decodes == 2); - require(cache.statistics().entries == 1); - }); -}}; - -const Scenario validatedGzipCacheLifetime{"Validated gzip cache lifetime is owned and copies do not share application state", [] { - using webfront::http::gzip::ValidatedCache; - std::string response(gzipfixtures::fixed); - given("a populated cache", [&] { - { - ValidatedCache cache(100000); - require(cache.resolve(response, 23768)); - auto copy = cache; - require(copy.statistics().entries == 0); + given("an initial decode failing its output budget", [&] { auto bytes = std::string(gzipfixtures::fixed); - require(copy.resolve(bytes, 23768)); - require(copy.statistics().decodes == 1); - } - then("the response survives destruction and a new application starts cold", [&] { - require(response == payload()); - ValidatedCache next(100000); - response = gzipfixtures::fixed; - require(next.resolve(response, 23768, true)); - require(next.statistics().decodes == 1); - require(next.statistics().hits == 0); + require(!cache.resolve(bytes, 1)); + bytes = gzipfixtures::fixed; + require(cache.resolve(bytes, 23768)); + require(cache.statistics().decodes == 2); + require(cache.statistics().entries == 1); }); - }); -}}; + }}; + +const Scenario validatedGzipCacheLifetime{"Validated gzip cache lifetime is owned and copies do not share application state", [] { + using webfront::http::gzip::ValidatedCache; + std::string response(gzipfixtures::fixed); + given("a populated cache", [&] { + { + ValidatedCache cache(100000); + require(cache.resolve(response, 23768)); + auto copy = cache; + require(copy.statistics().entries == 0); + auto bytes = std::string(gzipfixtures::fixed); + require(copy.resolve(bytes, 23768)); + require(copy.statistics().decodes == 1); + } + then("the response survives destruction and a new application starts cold", [&] { + require(response == payload()); + ValidatedCache next(100000); + response = gzipfixtures::fixed; + require(next.resolve(response, 23768, true)); + require(next.statistics().decodes == 1); + require(next.statistics().hits == 0); + }); + }); + }}; const Scenario validatedGzipCachePermits{"Validated gzip cache permits empty streams under a zero output budget", [] { - // Empty stored block, with a validated CRC32 and ISIZE of zero. - const std::string empty("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" - "\x01\x00\x00\xff\xff" - "\x00\x00\x00\x00\x00\x00\x00\x00", - 23); - webfront::http::gzip::ValidatedCache cache(1000); - given("GET then HEAD of a valid empty asset", [&] { - for (const bool head : {false, true}) { - auto bytes = empty; - require(cache.resolve(bytes, 0, head) == 0); - require(bytes.empty()); - } - require(cache.statistics().decodes == 1); - require(cache.statistics().hits == 1); - require(cache.statistics().retainedBytes <= 1000); - }); -}}; + // Empty stored block, with a validated CRC32 and ISIZE of zero. + const std::string empty("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" + "\x01\x00\x00\xff\xff" + "\x00\x00\x00\x00\x00\x00\x00\x00", + 23); + webfront::http::gzip::ValidatedCache cache(1000); + given("GET then HEAD of a valid empty asset", [&] { + for (const bool head : {false, true}) { + auto bytes = empty; + require(cache.resolve(bytes, 0, head) == 0); + require(bytes.empty()); + } + require(cache.statistics().decodes == 1); + require(cache.statistics().hits == 1); + require(cache.statistics().retainedBytes <= 1000); + }); + }}; const Scenario gzipDecodingFills{"Gzip decoding fills a preallocated bounded worker buffer without growing it", [] { - std::string output; - output.reserve(23768); - const auto capacity = output.capacity(); - for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional}) { - require(webfront::http::gzip::decodeGzipInto(bytes, output, 23768)); - require(output == payload()); - require(output.capacity() == capacity); - require(!webfront::http::gzip::decodeGzipInto(bytes, output, 23767)); - require(output.empty()); - } -}}; + std::string output; + output.reserve(23768); + const auto capacity = output.capacity(); + for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional}) { + require(webfront::http::gzip::decodeGzipInto(bytes, output, 23768)); + require(output == payload()); + require(output.capacity() == capacity); + require(!webfront::http::gzip::decodeGzipInto(bytes, output, 23767)); + require(output.empty()); + } + }}; const Scenario gzipBuffered{"Gzip buffered reads preserve logical byte offsets and exact member boundaries", [] { - using webfront::http::gzip::GzipReader; - using webfront::http::gzip::InvalidGzip; - given("a binary stream read with every supported width and initial bit alignment", [&] { - const std::string bytes("\x81\x72\xe3\x54\xa5\x96", 6); - then("every value and offset counts consumed bits without consuming later bytes", [&] { - for (unsigned alignment = 0; alignment < 8; ++alignment) { - for (unsigned width = 0; width <= 32; ++width) { - GzipReader reader(bytes); - reader.bits(alignment); - std::uint32_t expected = 0; - for (unsigned bit = 0; bit < width; ++bit) { - const auto offset = alignment + bit; - expected |= ((static_cast(static_cast(bytes[offset / 8])) >> (offset % 8)) & 1u) << bit; - } - auto scope = info("alignment ", alignment, ", width ", width); - require(reader.bits(width) == expected); - require(reader.offset() == (alignment + width) / 8); - require(!reader.done()); - reader.align(); - const auto consumed = (alignment + width + 7) / 8; - require(reader.offset() == consumed); - require(reader.readBytes(bytes.size() - consumed) == std::string_view(bytes).substr(consumed)); - require(reader.done()); - require(reader.bits(0) == 0); - requireThrows([&] { reader.bits(1); }); - } - } - }); - }); - given("a one-byte input and a partially consumed final byte", [&] { - GzipReader reader(std::string_view("\xff", 1)); - require(reader.bits(1) == 1); - require(reader.offset() == 0); - require(!reader.done()); - require(reader.bits(7) == 127); - require(reader.offset() == 1); - require(reader.done()); - requireThrows([&] { reader.bits(1); }); - requireThrows([&] { reader.bits(33); }); - }); - given("optional header checksums and empty members between Huffman members", [&] { - const auto bytes = std::string(gzipfixtures::optional) + std::string(gzipfixtures::empty) + std::string(gzipfixtures::fixed); - then("header CRC ranges and every member trailer stay exact", [&] { - require(decodeGzip(bytes) == payload() + payload()); - for (std::size_t size = bytes.size() - 8; size < bytes.size(); ++size) - require(!decodeGzip(std::string_view(bytes).substr(0, size))); - require(!decodeGzip(bytes + std::string(1, '\0'))); - }); - }); -}}; + using webfront::http::gzip::GzipReader; + using webfront::http::gzip::InvalidGzip; + given("a binary stream read with every supported width and initial bit alignment", [&] { + const std::string bytes("\x81\x72\xe3\x54\xa5\x96", 6); + then("every value and offset counts consumed bits without consuming later bytes", [&] { + for (unsigned alignment = 0; alignment < 8; ++alignment) { + for (unsigned width = 0; width <= 32; ++width) { + GzipReader reader(bytes); + reader.bits(alignment); + std::uint32_t expected = 0; + for (unsigned bit = 0; bit < width; ++bit) { + const auto offset = alignment + bit; + expected |= ((static_cast(static_cast(bytes[offset / 8])) >> (offset % 8)) & 1u) + << bit; + } + auto scope = info("alignment ", alignment, ", width ", width); + require(reader.bits(width) == expected); + require(reader.offset() == (alignment + width) / 8); + require(!reader.done()); + reader.align(); + const auto consumed = (alignment + width + 7) / 8; + require(reader.offset() == consumed); + require(reader.readBytes(bytes.size() - consumed) == std::string_view(bytes).substr(consumed)); + require(reader.done()); + require(reader.bits(0) == 0); + requireThrows([&] { + reader.bits(1); + }); + } + } + }); + }); + given("a one-byte input and a partially consumed final byte", [&] { + GzipReader reader(std::string_view("\xff", 1)); + require(reader.bits(1) == 1); + require(reader.offset() == 0); + require(!reader.done()); + require(reader.bits(7) == 127); + require(reader.offset() == 1); + require(reader.done()); + requireThrows([&] { + reader.bits(1); + }); + requireThrows([&] { + reader.bits(33); + }); + }); + given("optional header checksums and empty members between Huffman members", [&] { + const auto bytes = std::string(gzipfixtures::optional) + std::string(gzipfixtures::empty) + + std::string(gzipfixtures::fixed); + then("header CRC ranges and every member trailer stay exact", [&] { + require(decodeGzip(bytes) == payload() + payload()); + for (std::size_t size = bytes.size() - 8; size < bytes.size(); ++size) + require(!decodeGzip(std::string_view(bytes).substr(0, size))); + require(!decodeGzip(bytes + std::string(1, '\0'))); + }); + }); + }}; const Scenario gzipLookahead{"Gzip lookahead retains prefetched bytes through alignment and bulk reads", [] { - using webfront::http::gzip::GzipReader; - using webfront::http::gzip::InvalidGzip; - GzipReader reader("abcdef"); - unsigned prefix; - given("lookahead across four bytes without consuming them", [&] { - require(reader.peek(32, prefix)); - require(prefix == 0x64636261u); - require(reader.offset() == 0); - require(reader.readBytes(2) == "ab"); - require(reader.bits(8) == 'c'); - require(reader.peek(16, prefix)); - require(prefix == 0x6564u); - then("alignment keeps complete prefetched bytes", [&] { - reader.bits(1); - reader.align(); - require(reader.offset() == 4); - require(reader.readBytes(2) == "ef"); - require(reader.done()); - }); - }); - given("lookahead beyond the end of an exact input span", [&] { - require(reader.readBytes(5) == "abcde"); - require(!reader.peek(16, prefix)); - then("a failed probe preserves the last byte for a shorter code", [&] { - require(reader.offset() == 5); - require(reader.bits(8) == 'f'); - require(reader.done()); - requireThrows([&] { reader.consume(1); }); - }); - }); -}}; + using webfront::http::gzip::GzipReader; + using webfront::http::gzip::InvalidGzip; + GzipReader reader("abcdef"); + unsigned prefix; + given("lookahead across four bytes without consuming them", [&] { + require(reader.peek(32, prefix)); + require(prefix == 0x64636261u); + require(reader.offset() == 0); + require(reader.readBytes(2) == "ab"); + require(reader.bits(8) == 'c'); + require(reader.peek(16, prefix)); + require(prefix == 0x6564u); + then("alignment keeps complete prefetched bytes", [&] { + reader.bits(1); + reader.align(); + require(reader.offset() == 4); + require(reader.readBytes(2) == "ef"); + require(reader.done()); + }); + }); + given("lookahead beyond the end of an exact input span", [&] { + require(reader.readBytes(5) == "abcde"); + require(!reader.peek(16, prefix)); + then("a failed probe preserves the last byte for a shorter code", [&] { + require(reader.offset() == 5); + require(reader.bits(8) == 'f'); + require(reader.done()); + requireThrows([&] { + reader.consume(1); + }); + }); + }); + }}; const Scenario gzipHuffman{"Gzip Huffman lookup preserves short tails, long codes and empty distance trees", [] { - using namespace webfront::http::gzip; - given("a single-symbol incomplete alphabet at the very last input bit", [&] { - const std::array lengths{1}; - DeflateTree tree(lengths); - GzipReader reader(std::string_view("\x7f", 1)); - reader.bits(7); - require(tree.decode(reader) == 0); - require(reader.done()); - }); - given("a complete tree with codes longer than the direct table", [&] { - std::array tooMany{}; - requireThrows([&] { (void)DeflateTree(tooMany); }); - // One code at each length 1..8 and two at length 9 make a complete alphabet. - const std::array lengths{1, 2, 3, 4, 5, 6, 7, 8, 9, 9}; - DeflateTree tree(lengths); - GzipReader reader(std::string_view("\xff\x01", 2)); - require(tree.decode(reader) == 9); - require(reader.offset() == 1); - require(reader.bits(7) == 0); - require(reader.done()); - }); - given("an empty distance alphabet and a full input byte", [&] { - const std::array lengths{0}; - DeflateTree tree(lengths); - GzipReader reader(std::string_view("\0\0", 2)); - requireThrows([&] { tree.decode(reader); }); - }); -}}; + using namespace webfront::http::gzip; + given("a single-symbol incomplete alphabet at the very last input bit", [&] { + const std::array lengths{1}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\x7f", 1)); + reader.bits(7); + require(tree.decode(reader) == 0); + require(reader.done()); + }); + given("a complete tree with codes longer than the direct table", [&] { + std::array tooMany{}; + requireThrows([&] { + (void)DeflateTree(tooMany); + }); + // One code at each length 1..8 and two at length 9 make a complete alphabet. + const std::array lengths{1, 2, 3, 4, 5, 6, 7, 8, 9, 9}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\xff\x01", 2)); + require(tree.decode(reader) == 9); + require(reader.offset() == 1); + require(reader.bits(7) == 0); + require(reader.done()); + }); + given("an empty distance alphabet and a full input byte", [&] { + const std::array lengths{0}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\0\0", 2)); + requireThrows([&] { + tree.decode(reader); + }); + }); + }}; diff --git a/test/unit/HTTPEncodingTests.cpp b/test/unit/HTTPEncodingTests.cpp index fb41b443..c2add3d8 100644 --- a/test/unit/HTTPEncodingTests.cpp +++ b/test/unit/HTTPEncodingTests.cpp @@ -1,7 +1,7 @@ #include "GzipFixtures.hpp" -#include #include #include +#include #include #include @@ -96,223 +96,224 @@ Request assetRequest() { const Scenario hTTPDecodes{"HTTP decodes gzip when the stored encoding is unavailable", [] { - RequestHandler handler{"."}; - for (const auto header : {"", "br", "gzip;q=0", "gzip;q=0.000, *;q=1", "xgzip", "gzip2", "gzip;q=invalid"}) { - given("Accept-Encoding: ", header, [&] { - auto request = assetRequest(); - request.headers.emplace_back("Accept-Encoding", header); - const auto response = handler.handleRequest(request); - then("the body contains the decoded asset", [&] { - require(response.statusCode == Response::ok); - require(response.content.starts_with("WebFront gzip fallback\n")); - require(response.content.size() == 23768); - }); - then("encoding metadata describes identity", [&] { - require(!response.getHeaderValue("Content-Encoding")); - require(response.getHeaderValue("Content-Length") == "23768"); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - }); - then("the resource keeps its JavaScript MIME type", [&] { - require(response.getHeaderValue("Content-Type") == "application/javascript"); - }); - }); - } -}}; + RequestHandler handler{"."}; + for (const auto header : {"", "br", "gzip;q=0", "gzip;q=0.000, *;q=1", "xgzip", "gzip2", "gzip;q=invalid"}) { + given("Accept-Encoding: ", header, [&] { + auto request = assetRequest(); + request.headers.emplace_back("Accept-Encoding", header); + const auto response = handler.handleRequest(request); + then("the body contains the decoded asset", [&] { + require(response.statusCode == Response::ok); + require(response.content.starts_with("WebFront gzip fallback\n")); + require(response.content.size() == 23768); + }); + then("encoding metadata describes identity", [&] { + require(!response.getHeaderValue("Content-Encoding")); + require(response.getHeaderValue("Content-Length") == "23768"); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + }); + then("the resource keeps its JavaScript MIME type", [&] { + require(response.getHeaderValue("Content-Type") == "application/javascript"); + }); + }); + } + }}; const Scenario hTTPPreserves{"HTTP preserves accepted gzip bytes", [] { - RequestHandler handler{"."}; - for (const auto header : {"gzip", "GZIP", "x-gzip", "X-GZIP;q=0.5", "br, gzip;q=0.5", "gzip;q=1.000", "*;q=0.1", "gzip;q=1, *;q=0"}) { - given("Accept-Encoding: ", header, [&] { - auto request = assetRequest(); - request.headers.emplace_back("Accept-Encoding", header); - const auto response = handler.handleRequest(request); - then("the server returns the original encoded body", [&] { - require(response.statusCode == Response::ok); - require(response.content == gzipfixtures::fixed); - }); - then("metadata describes the gzip representation", [&] { - require(response.getHeaderValue("Content-Length") == std::to_string(gzipfixtures::fixed.size())); - require(response.getHeaderValue("Content-Encoding") == "gzip"); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - }); - }); - } -}}; + RequestHandler handler{"."}; + for (const auto header : + {"gzip", "GZIP", "x-gzip", "X-GZIP;q=0.5", "br, gzip;q=0.5", "gzip;q=1.000", "*;q=0.1", "gzip;q=1, *;q=0"}) { + given("Accept-Encoding: ", header, [&] { + auto request = assetRequest(); + request.headers.emplace_back("Accept-Encoding", header); + const auto response = handler.handleRequest(request); + then("the server returns the original encoded body", [&] { + require(response.statusCode == Response::ok); + require(response.content == gzipfixtures::fixed); + }); + then("metadata describes the gzip representation", [&] { + require(response.getHeaderValue("Content-Length") == std::to_string(gzipfixtures::fixed.size())); + require(response.getHeaderValue("Content-Encoding") == "gzip"); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + }); + }); + } + }}; const Scenario hTTPConsiders{"HTTP considers explicit encoding preferences across fields", [] { - RequestHandler handler{"."}; - auto request = assetRequest(); - given("multiple Accept-Encoding fields", [&] { - request.headers.emplace_back("Accept-Encoding", "br"); - request.headers.emplace_back("accept-encoding", "gzip;q=0.5"); - then("all fields participate in negotiation", [&] { - require(handler.handleRequest(request).getHeaderValue("Content-Encoding") == "gzip"); - }); - }); - given("an explicit identity preference overrides the wildcard exclusion", [&] { - request.headers.emplace_back("Accept-Encoding", "gzip;q=0, *;q=0, identity;q=0.5"); - then("the server can serve identity", [&] { - require(handler.handleRequest(request).statusCode == Response::ok); - }); - }); -}}; + RequestHandler handler{"."}; + auto request = assetRequest(); + given("multiple Accept-Encoding fields", [&] { + request.headers.emplace_back("Accept-Encoding", "br"); + request.headers.emplace_back("accept-encoding", "gzip;q=0.5"); + then("all fields participate in negotiation", [&] { + require(handler.handleRequest(request).getHeaderValue("Content-Encoding") == "gzip"); + }); + }); + given("an explicit identity preference overrides the wildcard exclusion", [&] { + request.headers.emplace_back("Accept-Encoding", "gzip;q=0, *;q=0, identity;q=0.5"); + then("the server can serve identity", [&] { + require(handler.handleRequest(request).statusCode == Response::ok); + }); + }); + }}; const Scenario hTTPRejectsUnavailable{"HTTP rejects unavailable representations", [] { - RequestHandler handler{"."}; - auto request = assetRequest(); - for (const auto header : {"gzip;q=0, identity;q=0", "*;q=0"}) { - given("Accept-Encoding: ", header, [&] { - request.headers.emplace_back("Accept-Encoding", header); - then("the server responds with 406", [&] { - require(handler.handleRequest(request).statusCode == Response::notAcceptable); - }); - }); - } - given("an unavailable custom content coding", [&] { - request.uri = "/unknown.js"; - then("it is rejected unless the client accepts it directly", [&] { - require(handler.handleRequest(request).statusCode == Response::notAcceptable); - request.headers.emplace_back("Accept-Encoding", "br"); - require(handler.handleRequest(request).getHeaderValue("Content-Encoding") == "br"); - }); - }); -}}; + RequestHandler handler{"."}; + auto request = assetRequest(); + for (const auto header : {"gzip;q=0, identity;q=0", "*;q=0"}) { + given("Accept-Encoding: ", header, [&] { + request.headers.emplace_back("Accept-Encoding", header); + then("the server responds with 406", [&] { + require(handler.handleRequest(request).statusCode == Response::notAcceptable); + }); + }); + } + given("an unavailable custom content coding", [&] { + request.uri = "/unknown.js"; + then("it is rejected unless the client accepts it directly", [&] { + require(handler.handleRequest(request).statusCode == Response::notAcceptable); + request.headers.emplace_back("Accept-Encoding", "br"); + require(handler.handleRequest(request).getHeaderValue("Content-Encoding") == "br"); + }); + }); + }}; const Scenario hTTPHEAD{"HTTP HEAD describes the negotiated representation", [] { - RequestHandler handler{"."}; - for (const auto& [header, length] : { - std::pair{ "", std::string("23768")}, - {"gzip", std::to_string(gzipfixtures::fixed.size())} - }) { - given("Accept-Encoding: ", header, [&] { - auto request = assetRequest(); - request.method = Request::Method::Head; - request.headers.emplace_back("Accept-Encoding", header); - const auto response = handler.handleRequest(request); - then("no body is sent", [&] { - require(response.statusCode == Response::ok); - require(response.content.empty()); - }); - then("headers match the corresponding GET representation", [&] { - require(response.getHeaderValue("Content-Length") == length); - require(response.getHeaderValue("Content-Encoding").value_or("") == header); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - }); - }); - } -}}; + RequestHandler handler{"."}; + for (const auto& [header, length] : { + std::pair{ "", std::string("23768")}, + {"gzip", std::to_string(gzipfixtures::fixed.size())} + }) { + given("Accept-Encoding: ", header, [&] { + auto request = assetRequest(); + request.method = Request::Method::Head; + request.headers.emplace_back("Accept-Encoding", header); + const auto response = handler.handleRequest(request); + then("no body is sent", [&] { + require(response.statusCode == Response::ok); + require(response.content.empty()); + }); + then("headers match the corresponding GET representation", [&] { + require(response.getHeaderValue("Content-Length") == length); + require(response.getHeaderValue("Content-Encoding").value_or("") == header); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + }); + }); + } + }}; const Scenario hTTPFallback{"HTTP fallback rejects corrupt and truncated streams", [] { - RequestHandler handler{"."}; - for (const auto path : {"/corrupt.js", "/empty.js", "/truncated.js"}) { - given(path, [&] { - auto request = assetRequest(); - request.uri = path; - const auto response = handler.handleRequest(request); - then("a complete error response is returned", [&] { - require(response.statusCode == Response::internalServerError); - require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); - }); - then("no partial decoded output is exposed", [&] { - require(!response.getHeaderValue("Content-Encoding")); - require(response.content.find("WebFront gzip fallback") == std::string::npos); - }); - }); - } -}}; + RequestHandler handler{"."}; + for (const auto path : {"/corrupt.js", "/empty.js", "/truncated.js"}) { + given(path, [&] { + auto request = assetRequest(); + request.uri = path; + const auto response = handler.handleRequest(request); + then("a complete error response is returned", [&] { + require(response.statusCode == Response::internalServerError); + require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); + }); + then("no partial decoded output is exposed", [&] { + require(!response.getHeaderValue("Content-Encoding")); + require(response.content.find("WebFront gzip fallback") == std::string::npos); + }); + }); + } + }}; const Scenario hTTPGzipFallback{"HTTP gzip fallback respects the configured decoded byte budget", [] { - using Limited = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23767>; - RequestHandler handler{"."}; - auto request = assetRequest(); - given("GET and HEAD identity responses exceeding the budget by one byte", [&] { - for (const auto method : {Request::Method::Get, Request::Method::Head}) { - request.method = method; - then("the server rejects the oversized decoded representation for method ", static_cast(method), [&] { - require(handler.handleRequest(request).statusCode == Response::internalServerError); - }); - } - }); - given("a client accepting the stored gzip representation", [&] { - request.headers.emplace_back("Accept-Encoding", "gzip"); - then("pass-through is independent of the decoded byte budget", [&] { - require(handler.handleRequest(request).statusCode == Response::ok); - }); - }); - given("a budget exactly matching the decoded size", [&] { - using Exact = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23768>; - RequestHandler exact{"."}; - then("the identity response is allowed", [&] { - require(exact.handleRequest(request).content.size() == 23768); - }); - }); -}}; + using Limited = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23767>; + RequestHandler handler{"."}; + auto request = assetRequest(); + given("GET and HEAD identity responses exceeding the budget by one byte", [&] { + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + then("the server rejects the oversized decoded representation for method ", static_cast(method), [&] { + require(handler.handleRequest(request).statusCode == Response::internalServerError); + }); + } + }); + given("a client accepting the stored gzip representation", [&] { + request.headers.emplace_back("Accept-Encoding", "gzip"); + then("pass-through is independent of the decoded byte budget", [&] { + require(handler.handleRequest(request).statusCode == Response::ok); + }); + }); + given("a budget exactly matching the decoded size", [&] { + using Exact = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23768>; + RequestHandler exact{"."}; + then("the identity response is allowed", [&] { + require(exact.handleRequest(request).content.size() == 23768); + }); + }); + }}; const Scenario gzipFallback{"Gzip fallback budgets preserve legacy buffer policy compatibility", [] { - then("an older policy inherits the 4 MiB fallback limit", [&] { - require(maxDecodedAssetSize() == 4 * 1024 * 1024); - require(maxDecodedAssetSize() == defaultMaxDecodedAssetSize); - }); -}}; + then("an older policy inherits the 4 MiB fallback limit", [&] { + require(maxDecodedAssetSize() == 4 * 1024 * 1024); + require(maxDecodedAssetSize() == defaultMaxDecodedAssetSize); + }); + }}; const Scenario hTTPServer{"HTTP Server forwards the application policy to gzip fallback", [] { - AssetServerNet::accepts = 0; - AssetServerNet::statusLine.clear(); - using Limited = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23767>; - given("an application policy below the requested asset size", [&] { - Server server("127.0.0.1", "0"); - then("the connection receives the bounded fallback error", [&] { - require(AssetServerNet::waitForResponse() == "HTTP/1.1 500 Internal Server Error\r\n"); - }); - }); -}}; + AssetServerNet::accepts = 0; + AssetServerNet::statusLine.clear(); + using Limited = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, 23767>; + given("an application policy below the requested asset size", [&] { + Server server("127.0.0.1", "0"); + then("the connection receives the bounded fallback error", [&] { + require(AssetServerNet::waitForResponse() == "HTTP/1.1 500 Internal Server Error\r\n"); + }); + }); + }}; const Scenario hTTPTreats{"HTTP treats stored x-gzip assets as gzip for fallback and pass-through", [] { - RequestHandler handler{"."}; - auto request = assetRequest(); - request.uri = "/legacy.js"; - given("a client needing identity", [&] { - const auto response = handler.handleRequest(request); - then("the alias is decoded", [&] { - require(response.statusCode == Response::ok); - require(!response.getHeaderValue("Content-Encoding")); - require(response.content.starts_with("WebFront gzip fallback\n")); - }); - }); - given("a client accepting gzip", [&] { - request.headers.emplace_back("Accept-Encoding", "gzip"); - const auto response = handler.handleRequest(request); - then("the original stored bytes and coding label are retained", [&] { - require(response.statusCode == Response::ok); - require(response.getHeaderValue("Content-Encoding") == "x-gzip"); - require(response.content == gzipfixtures::fixed); - }); - }); -}}; + RequestHandler handler{"."}; + auto request = assetRequest(); + request.uri = "/legacy.js"; + given("a client needing identity", [&] { + const auto response = handler.handleRequest(request); + then("the alias is decoded", [&] { + require(response.statusCode == Response::ok); + require(!response.getHeaderValue("Content-Encoding")); + require(response.content.starts_with("WebFront gzip fallback\n")); + }); + }); + given("a client accepting gzip", [&] { + request.headers.emplace_back("Accept-Encoding", "gzip"); + const auto response = handler.handleRequest(request); + then("the original stored bytes and coding label are retained", [&] { + require(response.statusCode == Response::ok); + require(response.getHeaderValue("Content-Encoding") == "x-gzip"); + require(response.content == gzipfixtures::fixed); + }); + }); + }}; const Scenario hTTPGET{"HTTP GET and HEAD reuse validated gzip revisions across paths and aliases", [] { - RequestHandler handler{"."}; - auto request = assetRequest(); - given("a cold HEAD followed by GET, another path and the x-gzip alias", [&] { - request.method = Request::Method::Head; - require(handler.handleRequest(request).content.empty()); - request.method = Request::Method::Get; - require(handler.handleRequest(request).content.size() == 23768); - request.uri = "/other.js"; - require(handler.handleRequest(request).content.size() == 23768); - request.uri = "/legacy.js"; - require(handler.handleRequest(request).content.size() == 23768); - then("identical compressed bytes require a single decode", [&] { - require(handler.fallbackCacheStatistics().decodes == 1); - require(handler.fallbackCacheStatistics().hits == 3); - }); - then("gzip pass-through leaves the fallback cache untouched", [&] { - request.headers.emplace_back("Accept-Encoding", "gzip"); - require(handler.handleRequest(request).content == gzipfixtures::fixed); - require(handler.fallbackCacheStatistics().hits == 3); - }); - }); -}}; + RequestHandler handler{"."}; + auto request = assetRequest(); + given("a cold HEAD followed by GET, another path and the x-gzip alias", [&] { + request.method = Request::Method::Head; + require(handler.handleRequest(request).content.empty()); + request.method = Request::Method::Get; + require(handler.handleRequest(request).content.size() == 23768); + request.uri = "/other.js"; + require(handler.handleRequest(request).content.size() == 23768); + request.uri = "/legacy.js"; + require(handler.handleRequest(request).content.size() == 23768); + then("identical compressed bytes require a single decode", [&] { + require(handler.fallbackCacheStatistics().decodes == 1); + require(handler.fallbackCacheStatistics().hits == 3); + }); + then("gzip pass-through leaves the fallback cache untouched", [&] { + request.headers.emplace_back("Accept-Encoding", "gzip"); + require(handler.handleRequest(request).content == gzipfixtures::fixed); + require(handler.fallbackCacheStatistics().hits == 3); + }); + }); + }}; namespace { struct MutableAssetFS : EncodedAssetFS { @@ -328,71 +329,71 @@ struct MutableAssetFS : EncodedAssetFS { } // namespace const Scenario hTTPMutable{"HTTP mutable providers cannot reuse stale identity content or HEAD lengths", [] { - RequestHandler handler{"."}; - auto request = assetRequest(); - MutableAssetFS::revision = gzipfixtures::fixed; - require(handler.handleRequest(request).content.size() == 23768); - given("the provider replaces the same path with two concatenated members", [&] { - MutableAssetFS::revision += gzipfixtures::fixed; - request.method = Request::Method::Head; - const auto head = handler.handleRequest(request); - require(head.getHeaderValue("Content-Length") == "47536"); - require(head.content.empty()); - request.method = Request::Method::Get; - require(handler.handleRequest(request).content.size() == 47536); - require(handler.fallbackCacheStatistics().decodes == 2); - require(handler.fallbackCacheStatistics().hits == 1); - }); - given("the provider replaces it with corrupt content having the same ISIZE", [&] { - MutableAssetFS::revision[MutableAssetFS::revision.size() - 8] ^= 1; - for (const auto method : {Request::Method::Get, Request::Method::Head}) { - request.method = method; - require(handler.handleRequest(request).statusCode == Response::internalServerError); - } - require(handler.fallbackCacheStatistics().decodes == 3); - require(handler.fallbackCacheStatistics().entries == 1); - }); -}}; + RequestHandler handler{"."}; + auto request = assetRequest(); + MutableAssetFS::revision = gzipfixtures::fixed; + require(handler.handleRequest(request).content.size() == 23768); + given("the provider replaces the same path with two concatenated members", [&] { + MutableAssetFS::revision += gzipfixtures::fixed; + request.method = Request::Method::Head; + const auto head = handler.handleRequest(request); + require(head.getHeaderValue("Content-Length") == "47536"); + require(head.content.empty()); + request.method = Request::Method::Get; + require(handler.handleRequest(request).content.size() == 47536); + require(handler.fallbackCacheStatistics().decodes == 2); + require(handler.fallbackCacheStatistics().hits == 1); + }); + given("the provider replaces it with corrupt content having the same ISIZE", [&] { + MutableAssetFS::revision[MutableAssetFS::revision.size() - 8] ^= 1; + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + require(handler.handleRequest(request).statusCode == Response::internalServerError); + } + require(handler.fallbackCacheStatistics().decodes == 3); + require(handler.fallbackCacheStatistics().entries == 1); + }); + }}; const Scenario hTTPCache{"HTTP cache ownership and policy remain local to the application", [] { - using Disabled = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, defaultMaxDecodedAssetSize, 0>; - RequestHandler handler{"."}; - const auto request = assetRequest(); - given("a policy disabling cache retention", [&] { - require(handler.handleRequest(request).statusCode == Response::ok); - require(handler.handleRequest(request).statusCode == Response::ok); - require(handler.fallbackCacheStatistics().decodes == 2); - require(handler.fallbackCacheStatistics().retainedBytes == 0); - }); - then("legacy policies retain the default cache budget", [&] { - require(maxDecodedAssetCacheSize() == defaultMaxDecodedAssetCacheSize); - }); - given("two independent handlers", [&] { - RequestHandler first{"."}, second{"."}; - require(first.handleRequest(request).statusCode == Response::ok); - require(second.fallbackCacheStatistics().entries == 0); - require(second.handleRequest(request).statusCode == Response::ok); - require(second.fallbackCacheStatistics().decodes == 1); - }); -}}; + using Disabled = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, defaultMaxDecodedAssetSize, 0>; + RequestHandler handler{"."}; + const auto request = assetRequest(); + given("a policy disabling cache retention", [&] { + require(handler.handleRequest(request).statusCode == Response::ok); + require(handler.handleRequest(request).statusCode == Response::ok); + require(handler.fallbackCacheStatistics().decodes == 2); + require(handler.fallbackCacheStatistics().retainedBytes == 0); + }); + then("legacy policies retain the default cache budget", [&] { + require(maxDecodedAssetCacheSize() == defaultMaxDecodedAssetCacheSize); + }); + given("two independent handlers", [&] { + RequestHandler first{"."}, second{"."}; + require(first.handleRequest(request).statusCode == Response::ok); + require(second.fallbackCacheStatistics().entries == 0); + require(second.handleRequest(request).statusCode == Response::ok); + require(second.fallbackCacheStatistics().decodes == 1); + }); + }}; const Scenario hTTPServerDrains{"HTTP server drains and destroys a populated fallback cache", [] { - given("successive applications serving an identity fallback", [&] { - for (unsigned instance = 0; instance < 2; ++instance) { - AssetServerNet::accepts = 0; - AssetServerNet::statusLine.clear(); - { - Server server("127.0.0.1", "0"); - require(AssetServerNet::waitForResponse() == "HTTP/1.1 200 OK\r\n"); - server.stop(); - server.drain(); - } - then("shutdown completes with no cache work outstanding", [&] { - require(AssetServerNet::accepts >= 1); - }); - } - }); -}}; + given("successive applications serving an identity fallback", [&] { + for (unsigned instance = 0; instance < 2; ++instance) { + AssetServerNet::accepts = 0; + AssetServerNet::statusLine.clear(); + { + Server server("127.0.0.1", "0"); + require(AssetServerNet::waitForResponse() == "HTTP/1.1 200 OK\r\n"); + server.stop(); + server.drain(); + } + then("shutdown completes with no cache work outstanding", [&] { + require(AssetServerNet::accepts >= 1); + }); + } + }); + }}; namespace { struct ActiveAssetBudget : DefaultBuffersPolicy { @@ -409,22 +410,22 @@ struct ActiveAssetBudget : DefaultBuffersPolicy { } // namespace const Scenario hTTPCached{"HTTP cached GET and HEAD recheck the active application output budget", [] { - const ActiveAssetBudget initialBudget{23768}; - RequestHandler handler{"."}; - auto request = assetRequest(); - require(handler.handleRequest(request).statusCode == Response::ok); - given("the application lowers its budget after validating this revision", [&] { - { - const ActiveAssetBudget smallerBudget{23767}; - for (const auto method : {Request::Method::Get, Request::Method::Head}) { - request.method = method; - const auto response = handler.handleRequest(request); - require(response.statusCode == Response::internalServerError); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - } - require(handler.fallbackCacheStatistics().decodes == 1); - require(handler.fallbackCacheStatistics().hits == 2); - } - require(handler.handleRequest(request).getHeaderValue("Content-Length") == "23768"); - }); -}}; + const ActiveAssetBudget initialBudget{23768}; + RequestHandler handler{"."}; + auto request = assetRequest(); + require(handler.handleRequest(request).statusCode == Response::ok); + given("the application lowers its budget after validating this revision", [&] { + { + const ActiveAssetBudget smallerBudget{23767}; + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + const auto response = handler.handleRequest(request); + require(response.statusCode == Response::internalServerError); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + } + require(handler.fallbackCacheStatistics().decodes == 1); + require(handler.fallbackCacheStatistics().hits == 2); + } + require(handler.handleRequest(request).getHeaderValue("Content-Length") == "23768"); + }); + }}; diff --git a/test/unit/HTTPRangeTests.cpp b/test/unit/HTTPRangeTests.cpp index d2ee458c..0047d8de 100644 --- a/test/unit/HTTPRangeTests.cpp +++ b/test/unit/HTTPRangeTests.cpp @@ -3,9 +3,9 @@ #include "InjectableNetworking.hpp" #include "Mocks.hpp" #include "TemporaryDirectory.hpp" -#include #include #include +#include #include #include @@ -36,12 +36,15 @@ struct Fields { std::list getHeadersValues(std::string_view name) const { std::list values; for (const auto& [key, value] : fields) - if (key == name) values.push_back(value); + if (key == name) + values.push_back(value); return values; } }; -Fields withRange(std::string value) { return {{{"Range", std::move(value)}}}; } +Fields withRange(std::string value) { + return {{{"Range", std::move(value)}}}; +} using range::Outcome; @@ -64,7 +67,8 @@ struct RangeNet : webfront::testing::InjectableNetworking { static inline std::atomic accepts{0}; static auto Accept(auto&) { return networking::ex::then(networking::ex::just(), []() -> Socket { - if (accepts++ != 0) throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + if (accepts++ != 0) + throw std::system_error(std::make_error_code(std::errc::operation_canceled)); return Socket{}; }); } @@ -76,7 +80,7 @@ struct Served { static inline std::vector words; static inline std::filesystem::path native; ///< a native file when set, embedded data otherwise static inline std::string_view encoding; - static inline std::string tag; ///< the provider's validator; empty when it has none + static inline std::string tag; ///< the provider's validator; empty when it has none }; struct ServedFS { @@ -84,7 +88,8 @@ struct ServedFS { std::optional open(std::filesystem::path) { if (!Served::native.empty()) { fs::File file{std::ifstream(Served::native, std::ios::binary)}; - if (!Served::tag.empty()) file.setEntityTag(Served::tag); + if (!Served::tag.empty()) + file.setEntityTag(Served::tag); return file; } auto& words = Served::words; @@ -97,7 +102,8 @@ struct ServedFS { std::string pattern(std::size_t size) { std::string text; - for (std::size_t index = 0; index < size; ++index) text.push_back(static_cast('a' + (index * 7 + index / 13) % 26)); + for (std::size_t index = 0; index < size; ++index) + text.push_back(static_cast('a' + (index * 7 + index / 13) % 26)); return text; } @@ -111,7 +117,8 @@ std::string fetch(const std::string& text) { RangeNet::accepts = 0; http::Server server("127.0.0.1", "0"); std::vector bytes; - for (const char c : text) bytes.push_back(static_cast(c)); + for (const char c : text) + bytes.push_back(static_cast(c)); InjectableSocket::receive(bytes); requireEventually( [] { @@ -131,7 +138,8 @@ std::string body(const std::string& response) { std::string header(const std::string& response, std::string_view name) { const auto head = response.substr(0, response.find("\r\n\r\n")); const auto start = head.find("\r\n" + std::string(name) + ": "); - if (start == std::string::npos) return {}; + if (start == std::string::npos) + return {}; const auto from = start + 4 + name.size(); return head.substr(from, head.find("\r\n", from) - from); } @@ -143,414 +151,443 @@ void serveEmbedded(std::string content, std::string_view encoding = {}) { Served::native.clear(); } -} // namespace +} // namespace const Scenario rangeHeader{"A Range header selects one part of a representation", [] { - static constexpr std::uint64_t size = 1000; - given("well-formed single ranges", [&] { - then("first-last selects the bytes, last being clamped to the end", [&] { - expectSelection(withRange("bytes=0-0"), size, {Outcome::partial, 0, 1}); - expectSelection(withRange("bytes=10-19"), size, {Outcome::partial, 10, 10}); - expectSelection(withRange("bytes=990-5000"), size, {Outcome::partial, 990, 10}); - expectSelection(withRange("bytes=0-999"), size, {Outcome::partial, 0, 1000}); - expectSelection(withRange("bytes=999-999"), size, {Outcome::partial, 999, 1}); - }); - then("first- selects up to the end", [&] { - expectSelection(withRange("bytes=0-"), size, {Outcome::partial, 0, 1000}); - expectSelection(withRange("bytes=900-"), size, {Outcome::partial, 900, 100}); - expectSelection(withRange("bytes=999-"), size, {Outcome::partial, 999, 1}); - }); - then("-n selects the last n bytes, the whole when n exceeds the size", [&] { - expectSelection(withRange("bytes=-1"), size, {Outcome::partial, 999, 1}); - expectSelection(withRange("bytes=-100"), size, {Outcome::partial, 900, 100}); - expectSelection(withRange("bytes=-1000"), size, {Outcome::partial, 0, 1000}); - expectSelection(withRange("bytes=-5000"), size, {Outcome::partial, 0, 1000}); - }); - then("the unit is case-insensitive and surrounding blanks are ignored", [&] { - expectSelection(withRange("Bytes=5-6"), size, {Outcome::partial, 5, 2}); - expectSelection(withRange(" bytes=5-6 \t"), size, {Outcome::partial, 5, 2}); - }); - }); - given("ranges nothing can satisfy", [&] { - then("a first byte at or past the end is unsatisfiable", [&] { - expectSelection(withRange("bytes=1000-"), size, {Outcome::unsatisfiable}); - expectSelection(withRange("bytes=1000-1001"), size, {Outcome::unsatisfiable}); - expectSelection(withRange("bytes=99999999999999999999999-"), size, {Outcome::unsatisfiable}); - }); - then("an empty suffix is unsatisfiable", [&] { expectSelection(withRange("bytes=-0"), size, {Outcome::unsatisfiable}); }); - then("any range of an empty representation is unsatisfiable", [&] { - expectSelection(withRange("bytes=0-0"), 0, {Outcome::unsatisfiable}); - expectSelection(withRange("bytes=0-"), 0, {Outcome::unsatisfiable}); - expectSelection(withRange("bytes=-5"), 0, {Outcome::unsatisfiable}); - }); - }); - given("headers the server ignores", [&] { - then("the whole representation is answered", [&] { - expectSelection({}, size, {Outcome::whole}); - expectSelection(withRange("items=0-5"), size, {Outcome::whole}); - expectSelection(withRange("bytes"), size, {Outcome::whole}); - expectSelection(withRange("bytes="), size, {Outcome::whole}); - expectSelection(withRange("bytes=-"), size, {Outcome::whole}); - expectSelection(withRange("bytes=5-2"), size, {Outcome::whole}); - expectSelection(withRange("bytes=a-b"), size, {Outcome::whole}); - expectSelection(withRange("bytes=+1-2"), size, {Outcome::whole}); - expectSelection(withRange("bytes=1 -2"), size, {Outcome::whole}); - expectSelection(withRange("bytes=0-1,5-6"), size, {Outcome::whole}); - expectSelection(withRange("bytes=0-1,"), size, {Outcome::whole}); - expectSelection({{{"Range", "bytes=0-1"}, {"Range", "bytes=5-6"}}}, size, {Outcome::whole}); - }); - }); - given("a number beyond 64 bits", [&] { - then("it saturates instead of wrapping", [&] { - expectSelection(withRange("bytes=0-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); - expectSelection(withRange("bytes=-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); - }); - }); - given("an If-Range condition", [&] { - const std::optional tag{"\"1000-42\""}; - auto conditioned = [](std::string condition) { - return Fields{{{"Range", "bytes=10-19"}, {"If-Range", std::move(condition)}}}; - }; - then("the range applies when it is the strong tag of the representation", [&] { - expectSelection(conditioned("\"1000-42\""), size, {Outcome::partial, 10, 10}, tag); - }); - then("the whole representation is answered when the tag differs, is weak, is a date or cannot be compared", [&] { - expectSelection(conditioned("\"1000-43\""), size, {Outcome::whole}, tag); - expectSelection(conditioned("W/\"1000-42\""), size, {Outcome::whole}, tag); - expectSelection(conditioned("Sun, 06 Nov 1994 08:49:37 GMT"), size, {Outcome::whole}, tag); - expectSelection(conditioned("\"1000-42\""), size, {Outcome::whole}); - expectSelection({{{"Range", "bytes=10-19"}, {"If-Range", "\"1000-42\""}, {"If-Range", "\"1000-42\""}}}, size, {Outcome::whole}, tag); - }); - then("an If-Range without Range does nothing", [&] { - expectSelection({{{"If-Range", "\"1000-42\""}}}, size, {Outcome::whole}, tag); - }); - }); - then("the Content-Range headers spell the bounds and the size", [&] { - require(range::contentRange({Outcome::partial, 10, 10}, 1000) == "bytes 10-19/1000"); - require(range::unsatisfiedContentRange(1000) == "bytes */1000"); - }); -}}; + static constexpr std::uint64_t size = 1000; + given("well-formed single ranges", [&] { + then("first-last selects the bytes, last being clamped to the end", [&] { + expectSelection(withRange("bytes=0-0"), size, {Outcome::partial, 0, 1}); + expectSelection(withRange("bytes=10-19"), size, {Outcome::partial, 10, 10}); + expectSelection(withRange("bytes=990-5000"), size, {Outcome::partial, 990, 10}); + expectSelection(withRange("bytes=0-999"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=999-999"), size, {Outcome::partial, 999, 1}); + }); + then("first- selects up to the end", [&] { + expectSelection(withRange("bytes=0-"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=900-"), size, {Outcome::partial, 900, 100}); + expectSelection(withRange("bytes=999-"), size, {Outcome::partial, 999, 1}); + }); + then("-n selects the last n bytes, the whole when n exceeds the size", [&] { + expectSelection(withRange("bytes=-1"), size, {Outcome::partial, 999, 1}); + expectSelection(withRange("bytes=-100"), size, {Outcome::partial, 900, 100}); + expectSelection(withRange("bytes=-1000"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=-5000"), size, {Outcome::partial, 0, 1000}); + }); + then("the unit is case-insensitive and surrounding blanks are ignored", [&] { + expectSelection(withRange("Bytes=5-6"), size, {Outcome::partial, 5, 2}); + expectSelection(withRange(" bytes=5-6 \t"), size, {Outcome::partial, 5, 2}); + }); + }); + given("ranges nothing can satisfy", [&] { + then("a first byte at or past the end is unsatisfiable", [&] { + expectSelection(withRange("bytes=1000-"), size, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=1000-1001"), size, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=99999999999999999999999-"), size, {Outcome::unsatisfiable}); + }); + then("an empty suffix is unsatisfiable", [&] { + expectSelection(withRange("bytes=-0"), size, {Outcome::unsatisfiable}); + }); + then("any range of an empty representation is unsatisfiable", [&] { + expectSelection(withRange("bytes=0-0"), 0, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=0-"), 0, {Outcome::unsatisfiable}); + expectSelection(withRange("bytes=-5"), 0, {Outcome::unsatisfiable}); + }); + }); + given("headers the server ignores", [&] { + then("the whole representation is answered", [&] { + expectSelection({}, size, {Outcome::whole}); + expectSelection(withRange("items=0-5"), size, {Outcome::whole}); + expectSelection(withRange("bytes"), size, {Outcome::whole}); + expectSelection(withRange("bytes="), size, {Outcome::whole}); + expectSelection(withRange("bytes=-"), size, {Outcome::whole}); + expectSelection(withRange("bytes=5-2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=a-b"), size, {Outcome::whole}); + expectSelection(withRange("bytes=+1-2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=1 -2"), size, {Outcome::whole}); + expectSelection(withRange("bytes=0-1,5-6"), size, {Outcome::whole}); + expectSelection(withRange("bytes=0-1,"), size, {Outcome::whole}); + expectSelection( + { + {{"Range", "bytes=0-1"}, {"Range", "bytes=5-6"}} + }, + size, + {Outcome::whole}); + }); + }); + given("a number beyond 64 bits", [&] { + then("it saturates instead of wrapping", [&] { + expectSelection(withRange("bytes=0-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); + expectSelection(withRange("bytes=-99999999999999999999999"), size, {Outcome::partial, 0, 1000}); + }); + }); + given("an If-Range condition", [&] { + const std::optional tag{"\"1000-42\""}; + auto conditioned = [](std::string condition) { + return Fields{ + {{"Range", "bytes=10-19"}, {"If-Range", std::move(condition)}} + }; + }; + then("the range applies when it is the strong tag of the representation", [&] { + expectSelection(conditioned("\"1000-42\""), size, {Outcome::partial, 10, 10}, tag); + }); + then("the whole representation is answered when the tag differs, is weak, is a date or cannot be compared", [&] { + expectSelection(conditioned("\"1000-43\""), size, {Outcome::whole}, tag); + expectSelection(conditioned("W/\"1000-42\""), size, {Outcome::whole}, tag); + expectSelection(conditioned("Sun, 06 Nov 1994 08:49:37 GMT"), size, {Outcome::whole}, tag); + expectSelection(conditioned("\"1000-42\""), size, {Outcome::whole}); + expectSelection( + { + {{"Range", "bytes=10-19"}, {"If-Range", "\"1000-42\""}, {"If-Range", "\"1000-42\""}} + }, + size, + {Outcome::whole}, + tag); + }); + then("an If-Range without Range does nothing", [&] { + expectSelection({{{"If-Range", "\"1000-42\""}}}, size, {Outcome::whole}, tag); + }); + }); + then("the Content-Range headers spell the bounds and the size", [&] { + require(range::contentRange({Outcome::partial, 10, 10}, 1000) == "bytes 10-19/1000"); + require(range::unsatisfiedContentRange(1000) == "bytes */1000"); + }); + }}; -const Scenario fileServed{"A file is served by ranges", [] { - const auto chunk = DefaultBuffersPolicy::emissionBufferSize; - for (const bool native : {false, true}) { - given(std::string(native ? "a native file" : "an embedded file"), " of several chunks", [&] { - webfront::test::TemporaryDirectory directory; - const auto content = pattern(3 * chunk + 11); - serveEmbedded(content); - if (native) { - Served::native = directory.path() / "media.bin"; - std::ofstream(Served::native, std::ios::binary) << content; - } - when("the whole file is requested", [&] { - const auto response = fetch(request("GET", "")); - then("200 announces the ranges", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "Accept-Ranges") == "bytes"); - require(body(response) == content); - }); - then("no validator is derived from a pathname, a size or a time", [&] { - require(header(response, "ETag").empty()); - }); - }); - when("a range crosses the emission chunks", [&] { - const auto first = chunk - 5; - const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "\r\n")); - then("206 sends exactly those bytes", [&] { - require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(header(response, "Content-Range") == "bytes " + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "/" + std::to_string(content.size())); - require(header(response, "Content-Length") == std::to_string(chunk + 10)); - require(body(response) == content.substr(first, chunk + 10)); - }); - }); - when("the end of the file is requested", [&] { - then("an open range reads to the end", [&] { - const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 7) + "-\r\n")); - require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(body(response) == content.substr(content.size() - 7)); +const Scenario fileServed{ + "A file is served by ranges", + [] { + const auto chunk = DefaultBuffersPolicy::emissionBufferSize; + for (const bool native : {false, true}) { + given(std::string(native ? "a native file" : "an embedded file"), " of several chunks", [&] { + webfront::test::TemporaryDirectory directory; + const auto content = pattern(3 * chunk + 11); + serveEmbedded(content); + if (native) { + Served::native = directory.path() / "media.bin"; + std::ofstream(Served::native, std::ios::binary) << content; + } + when("the whole file is requested", [&] { + const auto response = fetch(request("GET", "")); + then("200 announces the ranges", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "Accept-Ranges") == "bytes"); + require(body(response) == content); + }); + then("no validator is derived from a pathname, a size or a time", [&] { + require(header(response, "ETag").empty()); + }); }); - then("a suffix reads the last bytes", [&] { - const auto response = fetch(request("GET", "Range: bytes=-7\r\n")); - require(body(response) == content.substr(content.size() - 7)); - require(header(response, "Content-Range") == "bytes " + std::to_string(content.size() - 7) + "-" + std::to_string(content.size() - 1) + "/" + std::to_string(content.size())); + when("a range crosses the emission chunks", [&] { + const auto first = chunk - 5; + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "\r\n")); + then("206 sends exactly those bytes", [&] { + require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(header(response, "Content-Range") + == "bytes " + std::to_string(first) + "-" + std::to_string(2 * chunk + 4) + "/" + std::to_string(content.size())); + require(header(response, "Content-Length") == std::to_string(chunk + 10)); + require(body(response) == content.substr(first, chunk + 10)); + }); }); - then("a last byte past the end is clamped", [&] { - const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 3) + "-99999999\r\n")); - require(body(response) == content.substr(content.size() - 3)); + when("the end of the file is requested", [&] { + then("an open range reads to the end", [&] { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 7) + "-\r\n")); + require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(body(response) == content.substr(content.size() - 7)); + }); + then("a suffix reads the last bytes", [&] { + const auto response = fetch(request("GET", "Range: bytes=-7\r\n")); + require(body(response) == content.substr(content.size() - 7)); + require(header(response, "Content-Range") + == "bytes " + std::to_string(content.size() - 7) + "-" + std::to_string(content.size() - 1) + "/" + + std::to_string(content.size())); + }); + then("a last byte past the end is clamped", [&] { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size() - 3) + "-99999999\r\n")); + require(body(response) == content.substr(content.size() - 3)); + }); }); - }); - when("the range starts at the first byte", [&] { - const auto response = fetch(request("GET", "Range: bytes=0-0\r\n")); - then("206 sends it without seeking", [&] { require(body(response) == content.substr(0, 1)); }); - }); - when("the range starts past the end", [&] { - const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); - then("416 tells the size and sends no content", [&] { - require(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); - require(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); - require(header(response, "Content-Length") == "0"); - require(body(response).empty()); + when("the range starts at the first byte", [&] { + const auto response = fetch(request("GET", "Range: bytes=0-0\r\n")); + then("206 sends it without seeking", [&] { + require(body(response) == content.substr(0, 1)); + }); }); - }); - when("several ranges are requested", [&] { - const auto response = fetch(request("GET", "Range: bytes=0-1,5-6\r\n")); - then("the whole file is answered", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(body(response) == content); + when("the range starts past the end", [&] { + const auto response = fetch(request("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); + then("416 tells the size and sends no content", [&] { + require(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); + require(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); + require(header(response, "Content-Length") == "0"); + require(body(response).empty()); + }); }); - }); - when("HEAD carries a range", [&] { - const auto response = fetch(request("HEAD", "Range: bytes=10-29\r\n")); - then("the range is ignored: it describes the whole file and sends no body", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "Content-Length") == std::to_string(content.size())); - require(header(response, "Content-Range").empty()); - require(header(response, "Accept-Ranges") == "bytes"); - require(body(response).empty()); + when("several ranges are requested", [&] { + const auto response = fetch(request("GET", "Range: bytes=0-1,5-6\r\n")); + then("the whole file is answered", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(body(response) == content); + }); }); - then("an unsatisfiable range is ignored too", [&] { - const auto past = fetch(request("HEAD", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); - require(past.starts_with("HTTP/1.1 200 OK\r\n")); + when("HEAD carries a range", [&] { + const auto response = fetch(request("HEAD", "Range: bytes=10-29\r\n")); + then("the range is ignored: it describes the whole file and sends no body", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "Content-Length") == std::to_string(content.size())); + require(header(response, "Content-Range").empty()); + require(header(response, "Accept-Ranges") == "bytes"); + require(body(response).empty()); + }); + then("an unsatisfiable range is ignored too", [&] { + const auto past = fetch(request("HEAD", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); + require(past.starts_with("HTTP/1.1 200 OK\r\n")); + }); }); }); - }); - } -}}; + } + }}; const Scenario rangeSurvives{"A range survives a file changed between two requests only when its validator still matches", [] { - webfront::test::TemporaryDirectory directory; - Served::native = directory.path() / "media.bin"; - Served::encoding = {}; - // The provider versions its storage: here the tag is a hash of the content, which no time or size can replace. - const auto publish = [](const std::string& content) { - std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << content; - Served::tag = "\"v" + std::to_string(std::hash{}(content)) + "\""; - }; - const auto original = pattern(5000); - publish(original); - const auto tag = header(fetch(request("GET", "")), "ETag"); - require(tag == Served::tag); - const std::string conditional = "Range: bytes=100-199\r\nIf-Range: " + tag + "\r\n"; + webfront::test::TemporaryDirectory directory; + Served::native = directory.path() / "media.bin"; + Served::encoding = {}; + // The provider versions its storage: here the tag is a hash of the content, which no time or size can replace. + const auto publish = [](const std::string& content) { + std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << content; + Served::tag = "\"v" + std::to_string(std::hash{}(content)) + "\""; + }; + const auto original = pattern(5000); + publish(original); + const auto tag = header(fetch(request("GET", "")), "ETag"); + require(tag == Served::tag); + const std::string conditional = "Range: bytes=100-199\r\nIf-Range: " + tag + "\r\n"; - given("the file did not change", [&] { - const auto response = fetch(request("GET", conditional)); - then("the range is served", [&] { - require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(body(response) == original.substr(100, 100)); - }); - }); - given("the file grew", [&] { - const auto replaced = pattern(5001); - publish(replaced); - const auto response = fetch(request("GET", conditional)); - then("the current file is sent in full, with its new tag", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(body(response) == replaced); - require(header(response, "ETag") != tag); - }); - }); - given("the file was rewritten with the same size and the same modification time", [&] { - const auto before = std::filesystem::last_write_time(Served::native); - std::string replaced = original; - std::reverse(replaced.begin(), replaced.end()); - publish(replaced); - std::filesystem::last_write_time(Served::native, before); - const auto response = fetch(request("GET", conditional)); - then("the current file is sent in full", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(body(response) == replaced); - }); - }); - given("a native file whose provider gives no validator", [&] { - Served::tag.clear(); - const auto response = fetch(request("GET", "Range: bytes=100-199\r\nIf-Range: " + tag + "\r\n")); - then("it has no ETag and a conditioned range is answered in full", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "ETag").empty()); - require(body(response) == original); - }); - then("a range without condition is still served", [&] { - const auto plain = fetch(request("GET", "Range: bytes=100-199\r\n")); - require(plain.starts_with("HTTP/1.1 206 Partial Content\r\n")); - }); - }); - given("the file shrank without the validator being checked", [&] { - std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << pattern(150); - const auto response = fetch(request("GET", "Range: bytes=100-199\r\n")); - then("the range is clamped to the current file", [&] { - require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(body(response) == pattern(150).substr(100)); - }); - }); - given("embedded data, which has no validator", [&] { - serveEmbedded(original); - const auto response = fetch(request("GET", "Range: bytes=100-199\r\nIf-Range: \"anything\"\r\n")); - then("a conditioned range is answered in full", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(body(response) == original); - }); - }); -}}; + given("the file did not change", [&] { + const auto response = fetch(request("GET", conditional)); + then("the range is served", [&] { + require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(body(response) == original.substr(100, 100)); + }); + }); + given("the file grew", [&] { + const auto replaced = pattern(5001); + publish(replaced); + const auto response = fetch(request("GET", conditional)); + then("the current file is sent in full, with its new tag", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(body(response) == replaced); + require(header(response, "ETag") != tag); + }); + }); + given("the file was rewritten with the same size and the same modification time", [&] { + const auto before = std::filesystem::last_write_time(Served::native); + std::string replaced = original; + std::reverse(replaced.begin(), replaced.end()); + publish(replaced); + std::filesystem::last_write_time(Served::native, before); + const auto response = fetch(request("GET", conditional)); + then("the current file is sent in full", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(body(response) == replaced); + }); + }); + given("a native file whose provider gives no validator", [&] { + Served::tag.clear(); + const auto response = fetch(request("GET", "Range: bytes=100-199\r\nIf-Range: " + tag + "\r\n")); + then("it has no ETag and a conditioned range is answered in full", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "ETag").empty()); + require(body(response) == original); + }); + then("a range without condition is still served", [&] { + const auto plain = fetch(request("GET", "Range: bytes=100-199\r\n")); + require(plain.starts_with("HTTP/1.1 206 Partial Content\r\n")); + }); + }); + given("the file shrank without the validator being checked", [&] { + std::ofstream(Served::native, std::ios::binary | std::ios::trunc) << pattern(150); + const auto response = fetch(request("GET", "Range: bytes=100-199\r\n")); + then("the range is clamped to the current file", [&] { + require(response.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(body(response) == pattern(150).substr(100)); + }); + }); + given("embedded data, which has no validator", [&] { + serveEmbedded(original); + const auto response = fetch(request("GET", "Range: bytes=100-199\r\nIf-Range: \"anything\"\r\n")); + then("a conditioned range is answered in full", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(body(response) == original); + }); + }); + }}; const Scenario storedDecoded{"A stored or decoded representation is not served by ranges", [] { - const auto content = pattern(300); - given("a gzip file the client accepts", [&] { - serveEmbedded(content, "gzip"); - const auto response = fetch(request("GET", "Range: bytes=10-19\r\n")); - then("it is sent in full, as stored, and says it has no ranges", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "Accept-Ranges") == "none"); - require(header(response, "Content-Encoding") == "gzip"); - }); - }); - given("a gzip file the client does not accept, which the server decodes", [&] { - serveEmbedded(std::string(gzipfixtures::fixed), "gzip"); - const auto response = fetch("GET /media.bin HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nRange: bytes=10-19\r\n\r\n"); - then("the answer is never a 206 and says it has no ranges", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(body(response).starts_with("WebFront gzip fallback")); - require(header(response, "Accept-Ranges") == "none"); - }); - }); -}}; + const auto content = pattern(300); + given("a gzip file the client accepts", [&] { + serveEmbedded(content, "gzip"); + const auto response = fetch(request("GET", "Range: bytes=10-19\r\n")); + then("it is sent in full, as stored, and says it has no ranges", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "Accept-Ranges") == "none"); + require(header(response, "Content-Encoding") == "gzip"); + }); + }); + given("a gzip file the client does not accept, which the server decodes", [&] { + serveEmbedded(std::string(gzipfixtures::fixed), "gzip"); + const auto response = fetch( + "GET /media.bin HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nRange: bytes=10-19\r\n\r\n"); + then("the answer is never a 206 and says it has no ranges", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(body(response).starts_with("WebFront gzip fallback")); + require(header(response, "Accept-Ranges") == "none"); + }); + }); + }}; const Scenario dynamicRoute{"A dynamic route serves a file by ranges", [] { - for (const bool native : {false, true}) { - given(std::string(native ? "a native file" : "an embedded file"), " behind a route", [&] { - webfront::test::TemporaryDirectory directory; - const auto content = pattern(2 * DefaultBuffersPolicy::emissionBufferSize + 3); - serveEmbedded(content); - Served::native.clear(); - const auto path = directory.path() / "granted.bin"; - if (native) std::ofstream(path, std::ios::binary) << content; - const auto open = [&] { - if (native) return fs::File(std::ifstream(path, std::ios::binary)); - static std::vector words; - words.assign((content.size() + 7) / 8, 0); - for (std::size_t index = 0; index < content.size(); ++index) - words[index / 8] |= static_cast(static_cast(content[index])) << ((7 - index % 8) * 8); - return fs::File(words, content.size()); - }; - const auto answer = [&](const std::string& text) { - InjectableSocket::reset(); - RangeNet::accepts = 0; - http::Server server("127.0.0.1", "0"); - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& routed) { - auto reply = fileReply(routed.request, open(), "video/mp4"); - reply.headers.emplace_back("Cache-Control", "no-store"); - return reply; - }); - std::vector bytes; - for (const char c : text) bytes.push_back(static_cast(c)); - InjectableSocket::receive(bytes); - requireEventually( - [] { - return InjectableSocket::shutdownCount() > 0; - }, - 10s); - auto written = InjectableSocket::writtenText(); - InjectableSocket::reset(); - return written; - }; - const auto get = [](std::string_view method, std::string_view headers) { - return std::string(method) + " /webfront/services/files/token HTTP/1.1\r\nHost: localhost\r\n" + std::string(headers) + "\r\n"; - }; - when("the file is requested in full, then twice by range on the same URL", [&] { - const auto whole = answer(get("GET", "")); - const auto middle = answer(get("GET", "Range: bytes=1000-1999\r\n")); - const auto resumed = answer(get("GET", "Range: bytes=2000-\r\n")); - then("every request succeeds with its own bytes", [&] { - require(whole.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(whole, "Accept-Ranges") == "bytes"); - require(header(whole, "Content-Type") == "video/mp4"); - require(header(whole, "Cache-Control") == "no-store"); - require(body(whole) == content); - require(middle.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(header(middle, "Content-Range") == "bytes 1000-1999/" + std::to_string(content.size())); - require(body(middle) == content.substr(1000, 1000)); - require(resumed.starts_with("HTTP/1.1 206 Partial Content\r\n")); - require(body(resumed) == content.substr(2000)); - }); - }); - when("the range is unsatisfiable", [&] { - const auto response = answer(get("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); - then("416 tells the size", [&] { - require(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); - require(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); - require(header(response, "Content-Length") == "0"); - }); - }); - when("HEAD carries a range", [&] { - const auto response = answer(get("HEAD", "Range: bytes=5-14\r\n")); - then("the range is ignored: it describes the whole file and sends no body", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "Content-Length") == std::to_string(content.size())); - require(body(response).empty()); - }); - }); - }); - } -}}; + for (const bool native : {false, true}) { + given(std::string(native ? "a native file" : "an embedded file"), " behind a route", [&] { + webfront::test::TemporaryDirectory directory; + const auto content = pattern(2 * DefaultBuffersPolicy::emissionBufferSize + 3); + serveEmbedded(content); + Served::native.clear(); + const auto path = directory.path() / "granted.bin"; + if (native) + std::ofstream(path, std::ios::binary) << content; + const auto open = [&] { + if (native) + return fs::File(std::ifstream(path, std::ios::binary)); + static std::vector words; + words.assign((content.size() + 7) / 8, 0); + for (std::size_t index = 0; index < content.size(); ++index) + words[index / 8] |= static_cast(static_cast(content[index])) + << ((7 - index % 8) * 8); + return fs::File(words, content.size()); + }; + const auto answer = [&](const std::string& text) { + InjectableSocket::reset(); + RangeNet::accepts = 0; + http::Server server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& routed) { + auto reply = fileReply(routed.request, open(), "video/mp4"); + reply.headers.emplace_back("Cache-Control", "no-store"); + return reply; + }); + std::vector bytes; + for (const char c : text) + bytes.push_back(static_cast(c)); + InjectableSocket::receive(bytes); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + auto written = InjectableSocket::writtenText(); + InjectableSocket::reset(); + return written; + }; + const auto get = [](std::string_view method, std::string_view headers) { + return std::string(method) + " /webfront/services/files/token HTTP/1.1\r\nHost: localhost\r\n" + + std::string(headers) + "\r\n"; + }; + when("the file is requested in full, then twice by range on the same URL", [&] { + const auto whole = answer(get("GET", "")); + const auto middle = answer(get("GET", "Range: bytes=1000-1999\r\n")); + const auto resumed = answer(get("GET", "Range: bytes=2000-\r\n")); + then("every request succeeds with its own bytes", [&] { + require(whole.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(whole, "Accept-Ranges") == "bytes"); + require(header(whole, "Content-Type") == "video/mp4"); + require(header(whole, "Cache-Control") == "no-store"); + require(body(whole) == content); + require(middle.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(header(middle, "Content-Range") == "bytes 1000-1999/" + std::to_string(content.size())); + require(body(middle) == content.substr(1000, 1000)); + require(resumed.starts_with("HTTP/1.1 206 Partial Content\r\n")); + require(body(resumed) == content.substr(2000)); + }); + }); + when("the range is unsatisfiable", [&] { + const auto response = answer(get("GET", "Range: bytes=" + std::to_string(content.size()) + "-\r\n")); + then("416 tells the size", [&] { + require(response.starts_with("HTTP/1.1 416 Range Not Satisfiable\r\n")); + require(header(response, "Content-Range") == "bytes */" + std::to_string(content.size())); + require(header(response, "Content-Length") == "0"); + }); + }); + when("HEAD carries a range", [&] { + const auto response = answer(get("HEAD", "Range: bytes=5-14\r\n")); + then("the range is ignored: it describes the whole file and sends no body", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "Content-Length") == std::to_string(content.size())); + require(body(response).empty()); + }); + }); + }); + } + }}; const Scenario routeServing{"A route serving a stored encoding keeps it and negotiates it", [] { - const auto content = pattern(64); - const auto serve = [&](std::string_view acceptEncoding) { - InjectableSocket::reset(); - RangeNet::accepts = 0; - http::Server server("127.0.0.1", "0"); - std::vector words((content.size() + 7) / 8, 0); - for (std::size_t index = 0; index < content.size(); ++index) - words[index / 8] |= static_cast(static_cast(content[index])) << ((7 - index % 8) * 8); - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& routed) { - return fileReply(routed.request, fs::File(words, content.size(), "gzip"), "text/html"); - }); - const std::string text = "GET /webfront/services/files/page.html HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: " + std::string(acceptEncoding) + - "\r\nRange: bytes=0-3\r\n\r\n"; - std::vector bytes; - for (const char c : text) bytes.push_back(static_cast(c)); - InjectableSocket::receive(bytes); - requireEventually( - [] { - return InjectableSocket::shutdownCount() > 0; - }, - 10s); - auto written = InjectableSocket::writtenText(); - InjectableSocket::reset(); - return written; - }; - given("a client that accepts gzip", [&] { - const auto response = serve("gzip"); - then("the stored bytes are labelled with their coding, in full, whatever the Range", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(header(response, "Content-Encoding") == "gzip"); - require(header(response, "Vary") == "Accept-Encoding"); - require(header(response, "Accept-Ranges") == "none"); - require(body(response) == content); - }); - }); - given("a client that does not accept gzip", [&] { - const auto response = serve("identity"); - then("it gets a 406 instead of bytes it cannot read", [&] { - require(response.starts_with("HTTP/1.1 406 Not Acceptable\r\n")); - require(header(response, "Vary") == "Accept-Encoding"); - require(header(response, "Content-Encoding").empty()); - }); - }); -}}; + const auto content = pattern(64); + const auto serve = [&](std::string_view acceptEncoding) { + InjectableSocket::reset(); + RangeNet::accepts = 0; + http::Server server("127.0.0.1", "0"); + std::vector words((content.size() + 7) / 8, 0); + for (std::size_t index = 0; index < content.size(); ++index) + words[index / 8] |= static_cast(static_cast(content[index])) << ((7 - index % 8) * 8); + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& routed) { + return fileReply(routed.request, fs::File(words, content.size(), "gzip"), "text/html"); + }); + const std::string text = "GET /webfront/services/files/page.html HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: " + + std::string(acceptEncoding) + "\r\nRange: bytes=0-3\r\n\r\n"; + std::vector bytes; + for (const char c : text) + bytes.push_back(static_cast(c)); + InjectableSocket::receive(bytes); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + auto written = InjectableSocket::writtenText(); + InjectableSocket::reset(); + return written; + }; + given("a client that accepts gzip", [&] { + const auto response = serve("gzip"); + then("the stored bytes are labelled with their coding, in full, whatever the Range", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(header(response, "Content-Encoding") == "gzip"); + require(header(response, "Vary") == "Accept-Encoding"); + require(header(response, "Accept-Ranges") == "none"); + require(body(response) == content); + }); + }); + given("a client that does not accept gzip", [&] { + const auto response = serve("identity"); + then("it gets a 406 instead of bytes it cannot read", [&] { + require(response.starts_with("HTTP/1.1 406 Not Acceptable\r\n")); + require(header(response, "Vary") == "Accept-Encoding"); + require(header(response, "Content-Encoding").empty()); + }); + }); + }}; const Scenario nativeFile{"A native file can be read again from any position after its end", [] { - webfront::test::TemporaryDirectory directory; - const auto path = directory.path() / "short.bin"; - std::ofstream(path, std::ios::binary) << "abc"; - fs::File file{std::ifstream(path, std::ios::binary)}; - std::array buffer{}; - require(file.read(buffer) == 3); - then("seek positions it again, and the content reads as before", [&] { - require(file.seek(0)); - require(file.read(buffer) == 3); - require(std::string(buffer.data(), 3) == "abc"); - require(file.seek(2)); - require(file.read(buffer) == 1); - require(buffer[0] == 'c'); - }); -}}; + webfront::test::TemporaryDirectory directory; + const auto path = directory.path() / "short.bin"; + std::ofstream(path, std::ios::binary) << "abc"; + fs::File file{std::ifstream(path, std::ios::binary)}; + std::array buffer{}; + require(file.read(buffer) == 3); + then("seek positions it again, and the content reads as before", [&] { + require(file.seek(0)); + require(file.read(buffer) == 3); + require(std::string(buffer.data(), 3) == "abc"); + require(file.seek(2)); + require(file.read(buffer) == 1); + require(buffer[0] == 'c'); + }); + }}; diff --git a/test/unit/HTTPRoutesTests.cpp b/test/unit/HTTPRoutesTests.cpp index a53657cf..4f16b6a0 100644 --- a/test/unit/HTTPRoutesTests.cpp +++ b/test/unit/HTTPRoutesTests.cpp @@ -2,17 +2,17 @@ #include "InjectableNetworking.hpp" #include "Mocks.hpp" #include "TemporaryDirectory.hpp" -#include #include #include +#include #include -#include #include +#include +#include #include #include #include -#include #include using namespace webfront::bdd; @@ -32,7 +32,8 @@ struct RouteNet : webfront::testing::InjectableNetworking { static inline std::atomic accepts{0}; static auto Accept(auto&) { return networking::ex::then(networking::ex::just(), []() -> Socket { - if (accepts++ != 0) throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + if (accepts++ != 0) + throw std::system_error(std::make_error_code(std::errc::operation_canceled)); return Socket{}; }); } @@ -46,7 +47,8 @@ using Router = Server; void send(std::string_view request) { std::vector bytes; - for (const char c : request) bytes.push_back(static_cast(c)); + for (const char c : request) + bytes.push_back(static_cast(c)); InjectableSocket::receive(bytes); } @@ -61,7 +63,11 @@ std::string post(std::string_view target, std::string_view headers, std::string_ /// Waits until the server asks for the read after `count` others: the bytes sent so far have been taken. void awaitRead(int count) { - requireEventually([count] { return InjectableSocket::readCallCount() > count; }, 10s); + requireEventually( + [count] { + return InjectableSocket::readCallCount() > count; + }, + 10s); } struct Fixture { @@ -69,7 +75,9 @@ struct Fixture { InjectableSocket::reset(); RouteNet::accepts = 0; } - ~Fixture() { InjectableSocket::reset(); } + ~Fixture() { + InjectableSocket::reset(); + } /// Sends the request and waits for the end of the connection; returns what the server wrote. std::string answer(std::string_view request) { @@ -97,466 +105,571 @@ RouteReply text(std::string body) { return reply; } -bool contains(const std::string& haystack, std::string_view needle) { return haystack.find(needle) != std::string::npos; } +bool contains(const std::string& haystack, std::string_view needle) { + return haystack.find(needle) != std::string::npos; +} -} // namespace +} // namespace const Scenario routePrefixes{"Route prefixes are validated when registered", [] { - RouteTable table; - const auto handler = [](const RouteRequest&) { return RouteReply{}; }; - given("prefixes that cannot be routes", [&] { - for (const auto* prefix : {"", "/", "/files", "files/", "/a//b/", "/a/../b/", "/a/./b/", "/a b/", "/a?b/", "/a#/", "/a%2e/"}) { - then("'", prefix, "' is refused", [&] { requireThrows([&] { (void)table.add(prefix, handler); }); }); - } - then("a route without handler is refused", [&] { requireThrows([&] { (void)table.add("/webfront/services/files/", nullptr); }); }); - }); - given("a registered prefix", [&] { - auto registration = table.add("/webfront/services/files/", handler); - then("the same prefix, a longer one and a shorter one collide", [&] { - requireThrows([&] { (void)table.add("/webfront/services/files/", handler); }); - requireThrows([&] { (void)table.add("/webfront/services/files/deep/", handler); }); - requireThrows([&] { (void)table.add("/webfront/services/", handler); }); - }); - then("a sibling prefix, even sharing the name's start, is accepted", [&] { - requireNothrow([&] { (void)table.add("/webfront/services/files2/", handler); }); - requireNothrow([&] { (void)table.add("/webfront/services/dialogs/", handler); }); - }); - then("lookup matches paths under the prefix only", [&] { - require(table.find("/webfront/services/files/token")); - require(!table.find("/webfront/services/files")); - require(!table.find("/webfront/services/filesX/token")); - require(!table.find("/WebFront.js")); - }); - then("unregistering frees the prefix and the lookup", [&] { - registration.reset(); - require(!table.find("/webfront/services/files/token")); - requireNothrow([&] { (void)table.add("/webfront/services/files/", handler); }); - }); - then("a moved registration keeps the route until it is destroyed", [&] { - auto moved = std::move(registration); - require(table.find("/webfront/services/files/x")); - moved = {}; - require(!table.find("/webfront/services/files/x")); - }); - }); - given("a registration outliving its table", [&] { - RouteTable::Registration registration; - { - RouteTable shortLived; - registration = shortLived.add("/webfront/services/files/", handler); - } - then("destroying it is harmless", [&] { requireNothrow([&] { registration.reset(); }); }); - }); -}}; + RouteTable table; + const auto handler = [](const RouteRequest&) { + return RouteReply{}; + }; + given("prefixes that cannot be routes", [&] { + for (const auto* prefix : + {"", "/", "/files", "files/", "/a//b/", "/a/../b/", "/a/./b/", "/a b/", "/a?b/", "/a#/", "/a%2e/"}) { + then("'", prefix, "' is refused", [&] { + requireThrows([&] { + (void)table.add(prefix, handler); + }); + }); + } + then("a route without handler is refused", [&] { + requireThrows([&] { + (void)table.add("/webfront/services/files/", nullptr); + }); + }); + }); + given("a registered prefix", [&] { + auto registration = table.add("/webfront/services/files/", handler); + then("the same prefix, a longer one and a shorter one collide", [&] { + requireThrows([&] { + (void)table.add("/webfront/services/files/", handler); + }); + requireThrows([&] { + (void)table.add("/webfront/services/files/deep/", handler); + }); + requireThrows([&] { + (void)table.add("/webfront/services/", handler); + }); + }); + then("a sibling prefix, even sharing the name's start, is accepted", [&] { + requireNothrow([&] { + (void)table.add("/webfront/services/files2/", handler); + }); + requireNothrow([&] { + (void)table.add("/webfront/services/dialogs/", handler); + }); + }); + then("lookup matches paths under the prefix only", [&] { + require(table.find("/webfront/services/files/token")); + require(!table.find("/webfront/services/files")); + require(!table.find("/webfront/services/filesX/token")); + require(!table.find("/WebFront.js")); + }); + then("unregistering frees the prefix and the lookup", [&] { + registration.reset(); + require(!table.find("/webfront/services/files/token")); + requireNothrow([&] { + (void)table.add("/webfront/services/files/", handler); + }); + }); + then("a moved registration keeps the route until it is destroyed", [&] { + auto moved = std::move(registration); + require(table.find("/webfront/services/files/x")); + moved = {}; + require(!table.find("/webfront/services/files/x")); + }); + }); + given("a registration outliving its table", [&] { + RouteTable::Registration registration; + { + RouteTable shortLived; + registration = shortLived.add("/webfront/services/files/", handler); + } + then("destroying it is harmless", [&] { + requireNothrow([&] { + registration.reset(); + }); + }); + }); + }}; const Scenario routeStreams{"A route streams its reply in bounded chunks", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - given("a body several chunks long", [&] { - std::string body; - for (std::size_t index = 0; index < 3 * DefaultBuffersPolicy::emissionBufferSize + 5; ++index) body.push_back(static_cast('a' + index % 26)); - std::size_t largestChunk = 0; - std::string target, query; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { - target = std::string(request.path); - query = std::string(request.query); - auto reply = text(body); - reply.body = [inner = std::move(reply.body), &largestChunk](std::span out) { - largestChunk = std::max(largestChunk, out.size()); - return inner(out); - }; - return reply; - }); - when("the browser requests it with a percent-encoded name and a query", [&] { - const auto response = fixture.answer(get("/webfront/services/files/a%20b.txt?token=1")); - then("the headers describe the reply and the whole body follows", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(contains(response, "Content-Type: text/plain\r\n")); - require(contains(response, "Cache-Control: no-store\r\n")); - require(contains(response, "Content-Length: " + std::to_string(body.size()) + "\r\n")); - require(contains(response, "Connection: close\r\n")); - require(response.ends_with("\r\n\r\n" + body)); - }); - then("the handler saw the decoded path and the raw query", [&] { - require(target == "/webfront/services/files/a b.txt"); - require(query == "token=1"); - }); - then("the body was never asked for more than the emission buffer at once", [&] { - require(largestChunk == DefaultBuffersPolicy::emissionBufferSize); - }); - }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a body several chunks long", [&] { + std::string body; + for (std::size_t index = 0; index < 3 * DefaultBuffersPolicy::emissionBufferSize + 5; ++index) + body.push_back(static_cast('a' + index % 26)); + std::size_t largestChunk = 0; + std::string target, query; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { + target = std::string(request.path); + query = std::string(request.query); + auto reply = text(body); + reply.body = [inner = std::move(reply.body), &largestChunk](std::span out) { + largestChunk = std::max(largestChunk, out.size()); + return inner(out); + }; + return reply; + }); + when("the browser requests it with a percent-encoded name and a query", [&] { + const auto response = fixture.answer(get("/webfront/services/files/a%20b.txt?token=1")); + then("the headers describe the reply and the whole body follows", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(contains(response, "Content-Type: text/plain\r\n")); + require(contains(response, "Cache-Control: no-store\r\n")); + require(contains(response, "Content-Length: " + std::to_string(body.size()) + "\r\n")); + require(contains(response, "Connection: close\r\n")); + require(response.ends_with("\r\n\r\n" + body)); + }); + then("the handler saw the decoded path and the raw query", [&] { + require(target == "/webfront/services/files/a b.txt"); + require(query == "token=1"); + }); + then("the body was never asked for more than the emission buffer at once", [&] { + require(largestChunk == DefaultBuffersPolicy::emissionBufferSize); + }); + }); + }); + }}; const Scenario routeAnswers{"A route answers HEAD without reading its body", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic reads{0}; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - auto reply = text("0123456789"); - reply.body = [&reads](std::span) { ++reads; return std::size_t{0}; }; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); - then("the headers announce the length and no body follows", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(contains(response, "Content-Length: 10\r\n")); - require(response.ends_with("\r\n\r\n")); - require(reads == 0); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic reads{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + auto reply = text("0123456789"); + reply.body = [&reads](std::span) { + ++reads; + return std::size_t{0}; + }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + then("the headers announce the length and no body follows", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(contains(response, "Content-Length: 10\r\n")); + require(response.ends_with("\r\n\r\n")); + require(reads == 0); + }); + }}; const Scenario routePrecedes{"A route precedes the file providers and refuses other methods", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic calls{0}; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - ++calls; - return text("from the route"); - }); - given("a provider that also has a file under the prefix", [&] { - const auto response = fixture.answer(get("/webfront/services/files/provided.txt")); - then("the route answers", [&] { require(response.ends_with("from the route")); }); - }); - given("a POST", [&] { - const auto response = fixture.answer(get("/webfront/services/files/x", "POST")); - then("it is refused with the methods the route serves, without calling the handler", [&] { - require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); - require(contains(response, "Allow: GET, HEAD\r\n")); - require(calls == 0); - }); - }); -}}; - -const Scenario routePosts{"A route that accepts POST reads a body bounded by Content-Length (#619)", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic calls{0}; - std::string seen; - auto route = server.addRoute("/webfront/services/rpc/", [&](const RouteRequest& request) { - ++calls; - seen = std::string(request.body); - return text("echo:" + seen); - }, RouteOptions{.postBodyLimit = 64}); - given("a body received with the headers", [&] { - const auto response = fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 5\r\nContent-Type: application/json\r\n", "hello")); - then("the handler gets the whole body and answers", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(response.ends_with("echo:hello")); - require(seen == "hello"); - }); - }); - given("a client that waits for 100 Continue, then sends the body in two parts", [&] { - send(post("/webfront/services/rpc/x", "Content-Length: 11\r\nExpect: 100-continue\r\n")); - awaitRead(1); - then("the server invites the body before the handler runs", [&] { - require(InjectableSocket::writtenText() == "HTTP/1.1 100 Continue\r\n\r\n"); - require(calls == 0); - }); - send("hello"); - awaitRead(2); - send(" world"); - requireEventually([] { return InjectableSocket::shutdownCount() > 0; }, 10s); - then("the handler gets both parts", [&] { - require(seen == "hello world"); - require(InjectableSocket::writtenText().ends_with("echo:hello world")); + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic calls{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + ++calls; + return text("from the route"); + }); + given("a provider that also has a file under the prefix", [&] { + const auto response = fixture.answer(get("/webfront/services/files/provided.txt")); + then("the route answers", [&] { + require(response.ends_with("from the route")); + }); + }); + given("a POST", [&] { + const auto response = fixture.answer(get("/webfront/services/files/x", "POST")); + then("it is refused with the methods the route serves, without calling the handler", [&] { + require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + require(contains(response, "Allow: GET, HEAD\r\n")); + require(calls == 0); + }); + }); + }}; + +const Scenario routePosts{ + "A route that accepts POST reads a body bounded by Content-Length (#619)", + [] { + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic calls{0}; + std::string seen; + auto route = server.addRoute( + "/webfront/services/rpc/", + [&](const RouteRequest& request) { + ++calls; + seen = std::string(request.body); + return text("echo:" + seen); + }, + RouteOptions{.postBodyLimit = 64}); + given("a body received with the headers", [&] { + const auto response = fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 5\r\nContent-Type: application/json\r\n", "hello")); + then("the handler gets the whole body and answers", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.ends_with("echo:hello")); + require(seen == "hello"); + }); }); - }); - for (const auto& expect : std::initializer_list{"100-continue, 100-continue", "100-continue,100-continue", "x, 100-Continue", "100-CONTINUE ,x"}) { - given("a client that waits for 100 Continue with 'Expect: ", expect, "'", [&] { - send(post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: " + std::string(expect) + "\r\n")); + given("a client that waits for 100 Continue, then sends the body in two parts", [&] { + send(post("/webfront/services/rpc/x", "Content-Length: 11\r\nExpect: 100-continue\r\n")); awaitRead(1); - then("the server invites the body", [&] { + then("the server invites the body before the handler runs", [&] { require(InjectableSocket::writtenText() == "HTTP/1.1 100 Continue\r\n\r\n"); require(calls == 0); }); - send("ok"); - requireEventually([] { return InjectableSocket::shutdownCount() > 0; }, 10s); - then("the handler then gets the body", [&] { require(seen == "ok"); }); - }); - } - given("bytes beyond the announced length", [&] { - fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 2\r\n", "okGET / HTTP/1.1")); - then("only the announced body reaches the handler", [&] { require(seen == "ok"); }); - }); - given("a GET on the same route", [&] { - const auto response = fixture.answer(get("/webfront/services/rpc/x")); - then("it is served with an empty body", [&] { - require(response.ends_with("echo:")); - require(calls == 1); - }); - }); - for (const auto& [headers, status] : std::initializer_list>{ - {"", "411 Length Required"}, - {"Transfer-Encoding: chunked\r\n", "501 Not Implemented"}, - {"Content-Length: 5\r\nTransfer-Encoding: chunked\r\n", "501 Not Implemented"}, - {"Content-Length: 1x\r\n", "400 Bad Request"}, - {"Content-Length: -1\r\n", "400 Bad Request"}, - {"Content-Length: 99999999999999999999999\r\n", "400 Bad Request"}, - {"Content-Length: 2\r\nContent-Length: 3\r\n", "400 Bad Request"}, - {"Content-Length: 2, 3\r\n", "400 Bad Request"}, - {"Content-Length: 2,\r\n", "400 Bad Request"}, - {"Content-Length: ,2\r\n", "400 Bad Request"}, - {"Content-Length: 2 2\r\n", "400 Bad Request"}, - {"Content-Length: \r\n", "400 Bad Request"}, - {"Content-Length:\r\n", "400 Bad Request"}, - {"Content-Length: 65\r\n", "413 Payload Too Large"}}) { - given("a POST with '", headers, "'", [&] { - const auto response = fixture.answer(post("/webfront/services/rpc/x", headers)); - then("it is refused with ", status, " without reading a body or calling the handler", [&] { - require(response.starts_with("HTTP/1.1 " + std::string(status) + "\r\n")); - require(calls == 0); + send("hello"); + awaitRead(2); + send(" world"); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + then("the handler gets both parts", [&] { + require(seen == "hello world"); + require(InjectableSocket::writtenText().ends_with("echo:hello world")); }); }); - } - for (const auto& headers : std::initializer_list{ - "Content-Length: 2\r\n", "Content-Length: 2 \r\n", "Content-Length: 2, 2\r\n", "Content-Length: 2,2\r\n", "Content-Length:2\r\n", "Content-Length:\t2\t\r\n", "Content-Length: 2,\t2\r\n", - "Content-Length: 2\r\nContent-Length: 2\r\n", "Content-Length: 2, 2\r\nContent-Length: 2\r\n"}) { - given("a POST with the valid length '", headers, "'", [&] { - const auto response = fixture.answer(post("/webfront/services/rpc/x", headers, "ok")); - then("the body reaches the handler", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); + for (const auto& expect : + std::initializer_list{"100-continue, 100-continue", "100-continue,100-continue", "x, 100-Continue", "100-CONTINUE ,x"}) { + given("a client that waits for 100 Continue with 'Expect: ", expect, "'", [&] { + send(post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: " + std::string(expect) + "\r\n")); + awaitRead(1); + then("the server invites the body", [&] { + require(InjectableSocket::writtenText() == "HTTP/1.1 100 Continue\r\n\r\n"); + require(calls == 0); + }); + send("ok"); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + then("the handler then gets the body", [&] { + require(seen == "ok"); + }); + }); + } + given("bytes beyond the announced length", [&] { + fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 2\r\n", "okGET / HTTP/1.1")); + then("only the announced body reaches the handler", [&] { require(seen == "ok"); }); }); - } - // Where no body has to be invited, `100 Continue` is never written, even when the client asked for it. - for (const auto& [request, why] : std::initializer_list>{ - {post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: 100-continue\r\n", "ok"), "the body came with the headers"}, - {post("/webfront/services/rpc/x", "Content-Length: 65\r\nExpect: 100-continue\r\n"), "the body is too long"}, - {post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: x-100-continue-y\r\n", "ok"), "the value only contains the token"}, - {"POST /webfront/services/rpc/x HTTP/1.0\r\nContent-Length: 2\r\nExpect: 100-continue\r\n\r\nok", "the client speaks HTTP/1.0"}}) { - given("an Expect header when ", why, [&] { - const auto response = fixture.answer(request); - then("no interim answer is written", [&] { require(!contains(response, "100 Continue")); }); - }); - } - given("a connection that ends before the announced length", [&] { - send(post("/webfront/services/rpc/x", "Content-Length: 10\r\n", "abc")); - awaitRead(1); - InjectableSocket::fail({}); - requireEventually([] { return InjectableSocket::shutdownCount() > 0; }, 10s); - then("the connection is closed without an answer and the handler is not called", [&] { - require(InjectableSocket::writtenText().empty()); - require(calls == 0); - }); - }); - given("a handler that accepts without a body", [&] { - auto other = server.addRoute("/webfront/services/status/", [](const RouteRequest& request) { - RouteReply reply; - reply.status = request.query == "accepted" ? Response::accepted : Response::unauthorized; - reply.contentLength = 0; - return reply; + given("a GET on the same route", [&] { + const auto response = fixture.answer(get("/webfront/services/rpc/x")); + then("it is served with an empty body", [&] { + require(response.ends_with("echo:")); + require(calls == 1); + }); }); - then("the status line carries the reason phrase", [&] { - require(fixture.answer(get("/webfront/services/status/x?accepted")).starts_with("HTTP/1.1 202 Accepted\r\n")); + for (const auto& [headers, status] : std::initializer_list>{ + { "", "411 Length Required"}, + { "Transfer-Encoding: chunked\r\n", "501 Not Implemented"}, + {"Content-Length: 5\r\nTransfer-Encoding: chunked\r\n", "501 Not Implemented"}, + { "Content-Length: 1x\r\n", "400 Bad Request"}, + { "Content-Length: -1\r\n", "400 Bad Request"}, + { "Content-Length: 99999999999999999999999\r\n", "400 Bad Request"}, + { "Content-Length: 2\r\nContent-Length: 3\r\n", "400 Bad Request"}, + { "Content-Length: 2, 3\r\n", "400 Bad Request"}, + { "Content-Length: 2,\r\n", "400 Bad Request"}, + { "Content-Length: ,2\r\n", "400 Bad Request"}, + { "Content-Length: 2 2\r\n", "400 Bad Request"}, + { "Content-Length: \r\n", "400 Bad Request"}, + { "Content-Length:\r\n", "400 Bad Request"}, + { "Content-Length: 65\r\n", "413 Payload Too Large"} + }) { + given("a POST with '", headers, "'", [&] { + const auto response = fixture.answer(post("/webfront/services/rpc/x", headers)); + then("it is refused with ", status, " without reading a body or calling the handler", [&] { + require(response.starts_with("HTTP/1.1 " + std::string(status) + "\r\n")); + require(calls == 0); + }); + }); + } + for (const auto& headers : std::initializer_list{"Content-Length: 2\r\n", + "Content-Length: 2 \r\n", + "Content-Length: 2, 2\r\n", + "Content-Length: 2,2\r\n", + "Content-Length:2\r\n", + "Content-Length:\t2\t\r\n", + "Content-Length: 2,\t2\r\n", + "Content-Length: 2\r\nContent-Length: 2\r\n", + "Content-Length: 2, 2\r\nContent-Length: 2\r\n"}) { + given("a POST with the valid length '", headers, "'", [&] { + const auto response = fixture.answer(post("/webfront/services/rpc/x", headers, "ok")); + then("the body reaches the handler", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(seen == "ok"); + }); + }); + } + // Where no body has to be invited, `100 Continue` is never written, even when the client asked for it. + for (const auto& [request, why] : std::initializer_list>{ + {post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: 100-continue\r\n", "ok"), "the body came with the headers"}, + {post("/webfront/services/rpc/x", "Content-Length: 65\r\nExpect: 100-continue\r\n"), "the body is too long"}, + {post("/webfront/services/rpc/x", "Content-Length: 2\r\nExpect: x-100-continue-y\r\n", "ok"), "the value only contains the token"}, + {"POST /webfront/services/rpc/x HTTP/1.0\r\nContent-Length: 2\r\nExpect: 100-continue\r\n\r\nok", "the client speaks HTTP/1.0"} + }) { + given("an Expect header when ", why, [&] { + const auto response = fixture.answer(request); + then("no interim answer is written", [&] { + require(!contains(response, "100 Continue")); + }); + }); + } + given("a connection that ends before the announced length", [&] { + send(post("/webfront/services/rpc/x", "Content-Length: 10\r\n", "abc")); + awaitRead(1); + InjectableSocket::fail({}); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + then("the connection is closed without an answer and the handler is not called", [&] { + require(InjectableSocket::writtenText().empty()); + require(calls == 0); + }); }); - }); - given("a handler that refuses the credentials", [&] { - auto other = server.addRoute("/webfront/services/status/", [](const RouteRequest&) { - RouteReply reply; - reply.status = Response::unauthorized; - reply.contentLength = 0; - return reply; + given("a handler that accepts without a body", [&] { + auto other = server.addRoute("/webfront/services/status/", [](const RouteRequest& request) { + RouteReply reply; + reply.status = request.query == "accepted" ? Response::accepted : Response::unauthorized; + reply.contentLength = 0; + return reply; + }); + then("the status line carries the reason phrase", [&] { + require(fixture.answer(get("/webfront/services/status/x?accepted")).starts_with("HTTP/1.1 202 Accepted\r\n")); + }); }); - then("the status line carries the reason phrase", [&] { - require(fixture.answer(get("/webfront/services/status/x")).starts_with("HTTP/1.1 401 Unauthorized\r\n")); + given("a handler that refuses the credentials", [&] { + auto other = server.addRoute("/webfront/services/status/", [](const RouteRequest&) { + RouteReply reply; + reply.status = Response::unauthorized; + reply.contentLength = 0; + return reply; + }); + then("the status line carries the reason phrase", [&] { + require(fixture.answer(get("/webfront/services/status/x")).starts_with("HTTP/1.1 401 Unauthorized\r\n")); + }); }); - }); - given("a route whose limit is zero", [&] { - auto zero = server.addRoute("/webfront/services/zero/", [&](const RouteRequest& request) { return text("empty:" + std::string(request.body)); }, RouteOptions{.postBodyLimit = 0}); - then("an empty body is served and any other refused", [&] { - require(fixture.answer(post("/webfront/services/zero/x", "Content-Length: 0\r\n")).ends_with("empty:")); + given("a route whose limit is zero", [&] { + auto zero = server.addRoute( + "/webfront/services/zero/", + [&](const RouteRequest& request) { + return text("empty:" + std::string(request.body)); + }, + RouteOptions{.postBodyLimit = 0}); + then("an empty body is served and any other refused", [&] { + require(fixture.answer(post("/webfront/services/zero/x", "Content-Length: 0\r\n")).ends_with("empty:")); + }); }); - }); - given("a route whose limit is zero and a body of one byte", [&] { - auto zero = server.addRoute("/webfront/services/zero/", [&](const RouteRequest&) { return text("never"); }, RouteOptions{.postBodyLimit = 0}); - then("it is refused with 413", [&] { - require(fixture.answer(post("/webfront/services/zero/x", "Content-Length: 1\r\n", "a")).starts_with("HTTP/1.1 413 Payload Too Large\r\n")); + given("a route whose limit is zero and a body of one byte", [&] { + auto zero = server.addRoute( + "/webfront/services/zero/", + [&](const RouteRequest&) { + return text("never"); + }, + RouteOptions{.postBodyLimit = 0}); + then("it is refused with 413", [&] { + require(fixture.answer(post("/webfront/services/zero/x", "Content-Length: 1\r\n", "a")).starts_with("HTTP/1.1 413 Payload Too Large\r\n")); + }); }); - }); - given("a Content-Length folded on two lines", [&] { - const auto response = fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 1\r\n 0\r\n", "x")); - then("the fold is a space, not a concatenated number: the length is refused", [&] { - require(response.starts_with("HTTP/1.1 400 Bad Request\r\n")); - require(calls == 0); + given("a Content-Length folded on two lines", [&] { + const auto response = fixture.answer(post("/webfront/services/rpc/x", "Content-Length: 1\r\n 0\r\n", "x")); + then("the fold is a space, not a concatenated number: the length is refused", [&] { + require(response.starts_with("HTTP/1.1 400 Bad Request\r\n")); + require(calls == 0); + }); }); - }); - given("a header folded on two lines", [&] { - auto note = server.addRoute("/webfront/services/note/", [](const RouteRequest& request) { - return text(request.request.getHeaderValue("X-Note").value_or("none")); + given("a header folded on two lines", [&] { + auto note = server.addRoute("/webfront/services/note/", [](const RouteRequest& request) { + return text(request.request.getHeaderValue("X-Note").value_or("none")); + }); + then("the handler sees one space where the line was folded", [&] { + require(fixture.answer("GET /webfront/services/note/x HTTP/1.1\r\nHost: localhost\r\nX-Note: a\r\n b\r\n\r\n").ends_with("a b")); + }); }); - then("the handler sees one space where the line was folded", [&] { - require(fixture.answer("GET /webfront/services/note/x HTTP/1.1\r\nHost: localhost\r\nX-Note: a\r\n b\r\n\r\n").ends_with("a b")); + given("an answer that streams from the view of a body received apart from the headers", [&] { + auto keep = server.addRoute( + "/webfront/services/keep/", + [](const RouteRequest& request) { + RouteReply reply; + reply.headers.emplace_back("Content-Type", "text/plain"); + reply.headers.emplace_back("Cache-Control", "no-store"); + reply.contentLength = request.body.size(); + reply.body = [view = request.body, position = std::size_t{0}](std::span out) mutable { + const auto count = std::min(out.size(), view.size() - position); + std::copy_n(view.data() + position, count, out.data()); + position += count; + return count; + }; + return reply; + }, + RouteOptions{.postBodyLimit = 64}); + const std::string large(40, 'x'); // beyond the small string buffer: the body is on the heap + send(post("/webfront/services/keep/x", "Content-Length: 40\r\n")); + awaitRead(1); + send(large); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + then("the body is still alive while the answer is sent", [&] { + require(InjectableSocket::writtenText().ends_with(large)); + }); }); - }); - given("an answer that streams from the view of a body received apart from the headers", [&] { - auto keep = server.addRoute("/webfront/services/keep/", [](const RouteRequest& request) { - RouteReply reply; - reply.headers.emplace_back("Content-Type", "text/plain"); - reply.headers.emplace_back("Cache-Control", "no-store"); - reply.contentLength = request.body.size(); - reply.body = [view = request.body, position = std::size_t{0}](std::span out) mutable { - const auto count = std::min(out.size(), view.size() - position); - std::copy_n(view.data() + position, count, out.data()); - position += count; - return count; - }; - return reply; - }, RouteOptions{.postBodyLimit = 64}); - const std::string large(40, 'x'); // beyond the small string buffer: the body is on the heap - send(post("/webfront/services/keep/x", "Content-Length: 40\r\n")); - awaitRead(1); - send(large); - requireEventually([] { return InjectableSocket::shutdownCount() > 0; }, 10s); - then("the body is still alive while the answer is sent", [&] { require(InjectableSocket::writtenText().ends_with(large)); }); - }); - given("a PUT", [&] { - const auto response = fixture.answer(get("/webfront/services/rpc/x", "PUT")); - then("it is refused with the methods of the route, POST included", [&] { - require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); - require(contains(response, "Allow: GET, HEAD, POST\r\n")); - require(calls == 0); + given("a PUT", [&] { + const auto response = fixture.answer(get("/webfront/services/rpc/x", "PUT")); + then("it is refused with the methods of the route, POST included", [&] { + require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + require(contains(response, "Allow: GET, HEAD, POST\r\n")); + require(calls == 0); + }); }); - }); -}}; + }}; const Scenario pathOutside{"A path outside every route, or after unregistering, goes to the providers", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { return text("x"); }); - given("a registration that was reset", [&] { - route.reset(); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the request is a 404", [&] { require(response.starts_with("HTTP/1.1 404 Not Found\r\n")); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + return text("x"); + }); + given("a registration that was reset", [&] { + route.reset(); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the request is a 404", [&] { + require(response.starts_with("HTTP/1.1 404 Not Found\r\n")); + }); + }); + }}; const Scenario failingHandler{"A failing handler answers 500 without leaking its error", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - given("a handler that throws", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw std::runtime_error("secret detail"); }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the browser gets a bare 500", [&] { - require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); - require(!contains(response, "secret detail")); - }); - }); - given("a handler whose header would split the response", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("x"); - reply.headers.emplace_back("X-Name", "a\r\nSet-Cookie: injected=1"); - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("it is refused", [&] { - require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); - require(!contains(response, "injected")); - }); - }); - given("a handler setting a header the server owns", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("x"); - reply.headers.emplace_back("content-length", "1"); - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("it is refused", [&] { require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a handler that throws", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { + throw std::runtime_error("secret detail"); + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the browser gets a bare 500", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + require(!contains(response, "secret detail")); + }); + }); + given("a handler whose header would split the response", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("X-Name", "a\r\nSet-Cookie: injected=1"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("it is refused", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + require(!contains(response, "injected")); + }); + }); + given("a handler setting a header the server owns", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("content-length", "1"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("it is refused", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + }); + }); + }}; const Scenario bodyBreaks{"A body that breaks its promise closes the connection", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - given("a body shorter than its Content-Length", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("abc"); - reply.contentLength = 10; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the client receives a truncated body, which it detects", [&] { - require(contains(response, "Content-Length: 10\r\n")); - require(response.ends_with("\r\n\r\nabc")); - }); - }); - given("a body longer than its Content-Length", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("abcdef"); - reply.contentLength = 3; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("nothing past the announced length is sent", [&] { require(response.ends_with("\r\n\r\n")); }); - }); - given("a body that throws after a first chunk", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - RouteReply reply; - reply.contentLength = 100; - reply.body = [first = true](std::span out) mutable -> std::size_t { - if (!std::exchange(first, false)) throw std::runtime_error("disk gone"); - out[0] = 'x'; - return 1; - }; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the connection ends after what was read", [&] { require(response.ends_with("\r\n\r\nx")); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a body shorter than its Content-Length", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("abc"); + reply.contentLength = 10; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the client receives a truncated body, which it detects", [&] { + require(contains(response, "Content-Length: 10\r\n")); + require(response.ends_with("\r\n\r\nabc")); + }); + }); + given("a body longer than its Content-Length", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("abcdef"); + reply.contentLength = 3; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("nothing past the announced length is sent", [&] { + require(response.ends_with("\r\n\r\n")); + }); + }); + given("a body that throws after a first chunk", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + RouteReply reply; + reply.contentLength = 100; + reply.body = [first = true](std::span out) mutable -> std::size_t { + if (!std::exchange(first, false)) + throw std::runtime_error("disk gone"); + out[0] = 'x'; + return 1; + }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the connection ends after what was read", [&] { + require(response.ends_with("\r\n\r\nx")); + }); + }); + }}; const Scenario slowHandler{"A slow handler does not block the server context", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic entered{false}, release{false}; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - entered = true; - while (!release) std::this_thread::sleep_for(1ms); - return text("late"); - }); - send(get("/webfront/services/files/x")); - requireEventually( - [&] { - return entered.load(); - }, - 10s); - then("the thread which sent the request has already returned, and the reply comes when the handler ends", [&] { - require(InjectableSocket::shutdownCount() == 0); - release = true; - requireEventually( - [] { - return InjectableSocket::shutdownCount() > 0; - }, - 10s); - require(InjectableSocket::writtenText().ends_with("late")); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic entered{false}, release{false}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + entered = true; + while (!release) + std::this_thread::sleep_for(1ms); + return text("late"); + }); + send(get("/webfront/services/files/x")); + requireEventually( + [&] { + return entered.load(); + }, + 10s); + then("the thread which sent the request has already returned, and the reply comes when the handler ends", [&] { + require(InjectableSocket::shutdownCount() == 0); + release = true; + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + require(InjectableSocket::writtenText().ends_with("late")); + }); + }}; const Scenario drainingWaits{"Draining waits for a handler still running on the worker instead of reporting a stalled scope", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic entered{false}, release{false}; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - entered = true; - while (!release) std::this_thread::sleep_for(1ms); - return text("late"); - }); - send(get("/webfront/services/files/x")); - requireEventually( - [&] { - return entered.load(); - }, - 10s); - when("the server is stopped and drained while the handler has not returned", [&] { - server.stop(); - std::jthread finishing([&] { - std::this_thread::sleep_for(100ms); - release = true; - }); - then("the drain waits for the handler and returns without an error", [&] { requireNothrow([&] { server.drain(); }); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic entered{false}, release{false}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + entered = true; + while (!release) + std::this_thread::sleep_for(1ms); + return text("late"); + }); + send(get("/webfront/services/files/x")); + requireEventually( + [&] { + return entered.load(); + }, + 10s); + when("the server is stopped and drained while the handler has not returned", [&] { + server.stop(); + std::jthread finishing([&] { + std::this_thread::sleep_for(100ms); + release = true; + }); + then("the drain waits for the handler and returns without an error", [&] { + requireNothrow([&] { + server.drain(); + }); + }); + }); + }}; namespace { // Peak resident set of the process in bytes, or 0 where it cannot be read. @@ -565,7 +678,8 @@ std::uint64_t peakResidentBytes() { return 0; #else rusage usage{}; - if (getrusage(RUSAGE_SELF, &usage) != 0) return 0; + if (getrusage(RUSAGE_SELF, &usage) != 0) + return 0; #ifdef __APPLE__ return static_cast(usage.ru_maxrss); // bytes #else @@ -580,94 +694,102 @@ struct StreamingPolicy : DefaultBuffersPolicy { } // namespace const Scenario largeBody{"A large body is streamed without being held", [] { - Fixture fixture; - Server server("127.0.0.1", "0"); - static constexpr std::uint64_t size = 128ull * 1024 * 1024; - std::size_t largestChunk = 0; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - RouteReply reply; - reply.contentLength = size; - reply.body = [&largestChunk, produced = std::uint64_t{0}](std::span out) mutable { - largestChunk = std::max(largestChunk, out.size()); - const auto count = static_cast(std::min(out.size(), size - produced)); - produced += count; - return count; - }; - return reply; - }); - InjectableSocket::discardWrites(); - const auto before = peakResidentBytes(); - send(get("/webfront/services/files/big")); - // Each chunk crosses to the worker thread. The limit stays below - // the 60 s CTest timeout of the scenarios, so that a stall is reported by the test rather than by a kill. - requireEventually( - [] { - return InjectableSocket::shutdownCount() > 0; - }, - 45s); - then("the peak memory of the process did not grow with the size sent", [&] { - // Holding the body would add its 128 MiB to the peak; ctest runs each scenario in its own process. - if (const auto after = peakResidentBytes()) - require(after - before < 48ull * 1024 * 1024); - }); - then("every byte was sent through a buffer of the emission size", [&] { - require(InjectableSocket::discardedBytes() > size); - require(largestChunk == StreamingPolicy::emissionBufferSize); - }); -}}; + Fixture fixture; + Server server("127.0.0.1", "0"); + static constexpr std::uint64_t size = 128ull * 1024 * 1024; + std::size_t largestChunk = 0; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.contentLength = size; + reply.body = [&largestChunk, produced = std::uint64_t{0}](std::span out) mutable { + largestChunk = std::max(largestChunk, out.size()); + const auto count = static_cast(std::min(out.size(), size - produced)); + produced += count; + return count; + }; + return reply; + }); + InjectableSocket::discardWrites(); + const auto before = peakResidentBytes(); + send(get("/webfront/services/files/big")); + // Each chunk crosses to the worker thread. The limit stays below + // the 60 s CTest timeout of the scenarios, so that a stall is reported by the test rather than by a kill. + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 45s); + then("the peak memory of the process did not grow with the size sent", [&] { + // Holding the body would add its 128 MiB to the peak; ctest runs each scenario in its own process. + if (const auto after = peakResidentBytes()) + require(after - before < 48ull * 1024 * 1024); + }); + then("every byte was sent through a buffer of the emission size", [&] { + require(InjectableSocket::discardedBytes() > size); + require(largestChunk == StreamingPolicy::emissionBufferSize); + }); + }}; const Scenario connectionWhich{"A connection which fails while a reply is streamed stops the reading", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::atomic reads{0}; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - RouteReply reply; - reply.body = [&reads](std::span out) { - if (++reads == 2) InjectableSocket::failWrites(std::make_error_code(std::errc::connection_reset)); - return out.size(); - }; - return reply; - }); - send(get("/webfront/services/files/endless")); - requireEventually( - [] { - return InjectableSocket::shutdownCount() > 0; - }, - 10s); - then("the body is not read again", [&] { - const auto seen = reads.load(); - std::this_thread::sleep_for(20ms); - require(reads == seen); - require(seen <= 3); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + std::atomic reads{0}; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.body = [&reads](std::span out) { + if (++reads == 2) + InjectableSocket::failWrites(std::make_error_code(std::errc::connection_reset)); + return out.size(); + }; + return reply; + }); + send(get("/webfront/services/files/endless")); + requireEventually( + [] { + return InjectableSocket::shutdownCount() > 0; + }, + 10s); + then("the body is not read again", [&] { + const auto seen = reads.load(); + std::this_thread::sleep_for(20ms); + require(reads == seen); + require(seen <= 3); + }); + }}; const Scenario stoppingServer{"Stopping the server ends a reply being streamed", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { - RouteReply reply; - reply.body = [](std::span out) { return out.size(); }; - return reply; - }); - InjectableSocket::deferWrites(); - send(get("/webfront/services/files/endless")); - requireEventually( - [] { - return InjectableSocket::hasDeferredWrites(); - }, - 10s); - when("the server is stopped and drained while a send is pending", [&] { - server.stop(); - then("the drain returns", [&] { requireNothrow([&] { server.drain(); }); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest&) { + RouteReply reply; + reply.body = [](std::span out) { + return out.size(); + }; + return reply; + }); + InjectableSocket::deferWrites(); + send(get("/webfront/services/files/endless")); + requireEventually( + [] { + return InjectableSocket::hasDeferredWrites(); + }, + 10s); + when("the server is stopped and drained while a send is pending", [&] { + server.stop(); + then("the drain returns", [&] { + requireNothrow([&] { + server.drain(); + }); + }); + }); + }}; namespace { std::string pattern(std::size_t size) { std::string bytes; - for (std::size_t index = 0; index < size; ++index) bytes.push_back(static_cast((index * 7 + 3) % 251)); + for (std::size_t index = 0; index < size; ++index) + bytes.push_back(static_cast((index * 7 + 3) % 251)); return bytes; } @@ -680,7 +802,8 @@ struct ProvidedFile { struct ProvidedFS { explicit ProvidedFS(std::filesystem::path) {} std::optional open(std::filesystem::path) { - if (!ProvidedFile::native.empty()) return fs::File(std::ifstream(ProvidedFile::native, std::ios::binary)); + if (!ProvidedFile::native.empty()) + return fs::File(std::ifstream(ProvidedFile::native, std::ios::binary)); auto& words = ProvidedFile::words; words.assign((ProvidedFile::content.size() + 7) / 8, 0); for (std::size_t index = 0; index < ProvidedFile::content.size(); ++index) @@ -689,254 +812,293 @@ struct ProvidedFS { } }; -} // namespace +} // namespace const Scenario filesProvider{"Files of a provider are announced by size and streamed", [] { - for (const bool native : {false, true}) { - given(std::string(native ? "a native file" : "an embedded file"), " of several chunks", [&] { - webfront::test::TemporaryDirectory directory; - ProvidedFile::content = pattern(3 * DefaultBuffersPolicy::emissionBufferSize + 11); - ProvidedFile::native.clear(); - if (native) { - ProvidedFile::native = directory.path() / "file.bin"; - std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; - } - Fixture fixture; - Server server("127.0.0.1", "0"); - when("it is requested", [&] { - const auto response = fixture.answer(get("/file.bin")); - then("the length is announced and the whole content follows", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(contains(response, "Content-Length: " + std::to_string(ProvidedFile::content.size()) + "\r\n")); - require(response.ends_with("\r\n\r\n" + ProvidedFile::content)); - }); - }); - }); - given(std::string(native ? "a native file" : "an embedded file"), " requested with HEAD", [&] { - webfront::test::TemporaryDirectory directory; - ProvidedFile::content = pattern(20000); - ProvidedFile::native.clear(); - if (native) { - ProvidedFile::native = directory.path() / "file.bin"; - std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; - } - Fixture fixture; - Server server("127.0.0.1", "0"); - const auto response = fixture.answer(get("/file.bin", "HEAD")); - then("the length is announced and no body follows", [&] { - require(contains(response, "Content-Length: 20000\r\n")); - require(response.ends_with("\r\n\r\n")); - }); - }); - } - given("an empty file", [&] { - ProvidedFile::content = ""; - ProvidedFile::native.clear(); - Fixture fixture; - Server server("127.0.0.1", "0"); - const auto response = fixture.answer(get("/file.bin")); - then("it is a 200 with a zero length", [&] { - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(contains(response, "Content-Length: 0\r\n")); - }); - }); -}}; + for (const bool native : {false, true}) { + given(std::string(native ? "a native file" : "an embedded file"), " of several chunks", [&] { + webfront::test::TemporaryDirectory directory; + ProvidedFile::content = pattern(3 * DefaultBuffersPolicy::emissionBufferSize + 11); + ProvidedFile::native.clear(); + if (native) { + ProvidedFile::native = directory.path() / "file.bin"; + std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; + } + Fixture fixture; + Server server("127.0.0.1", "0"); + when("it is requested", [&] { + const auto response = fixture.answer(get("/file.bin")); + then("the length is announced and the whole content follows", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(contains(response, "Content-Length: " + std::to_string(ProvidedFile::content.size()) + "\r\n")); + require(response.ends_with("\r\n\r\n" + ProvidedFile::content)); + }); + }); + }); + given(std::string(native ? "a native file" : "an embedded file"), " requested with HEAD", [&] { + webfront::test::TemporaryDirectory directory; + ProvidedFile::content = pattern(20000); + ProvidedFile::native.clear(); + if (native) { + ProvidedFile::native = directory.path() / "file.bin"; + std::ofstream(ProvidedFile::native, std::ios::binary) << ProvidedFile::content; + } + Fixture fixture; + Server server("127.0.0.1", "0"); + const auto response = fixture.answer(get("/file.bin", "HEAD")); + then("the length is announced and no body follows", [&] { + require(contains(response, "Content-Length: 20000\r\n")); + require(response.ends_with("\r\n\r\n")); + }); + }); + } + given("an empty file", [&] { + ProvidedFile::content = ""; + ProvidedFile::native.clear(); + Fixture fixture; + Server server("127.0.0.1", "0"); + const auto response = fixture.answer(get("/file.bin")); + then("it is a 200 with a zero length", [&] { + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(contains(response, "Content-Length: 0\r\n")); + }); + }); + }}; const Scenario nativeFileKnown{"A native file known by its size reports it", [] { - webfront::test::TemporaryDirectory directory; - const auto path = directory.path() / "known.bin"; - std::ofstream(path, std::ios::binary) << pattern(1234); - then("knownSize is the size on disk, whatever was read", [&] { - fs::File file{std::ifstream(path, std::ios::binary)}; - require(file.knownSize() == 1234); - std::array buffer{}; - require(file.read(buffer) == 100); - require(file.knownSize() == 1234); - }); -}}; + webfront::test::TemporaryDirectory directory; + const auto path = directory.path() / "known.bin"; + std::ofstream(path, std::ios::binary) << pattern(1234); + then("knownSize is the size on disk, whatever was read", [&] { + fs::File file{std::ifstream(path, std::ios::binary)}; + require(file.knownSize() == 1234); + std::array buffer{}; + require(file.read(buffer) == 100); + require(file.knownSize() == 1234); + }); + }}; const Scenario failedHEAD{"Failed HEAD requests carry no body", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - given("a handler which throws", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw std::runtime_error("no"); }); - const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); - then("the 500 has its headers only", [&] { - require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); - require(response.ends_with("\r\n\r\n")); - }); - }); - given("a handler with an invalid header", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("x"); - reply.headers.emplace_back("Bad Name", "v"); - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); - then("the 500 has its headers only", [&] { require(response.ends_with("\r\n\r\n")); }); - }); - given("a file which does not exist", [&] { - const auto response = fixture.answer(get("/nothing.txt", "HEAD")); - then("the 404 has its headers only", [&] { - require(response.starts_with("HTTP/1.1 404 Not Found\r\n")); - require(response.ends_with("\r\n\r\n")); - }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a handler which throws", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { + throw std::runtime_error("no"); + }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + then("the 500 has its headers only", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + require(response.ends_with("\r\n\r\n")); + }); + }); + given("a handler with an invalid header", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("Bad Name", "v"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x", "HEAD")); + then("the 500 has its headers only", [&] { + require(response.ends_with("\r\n\r\n")); + }); + }); + given("a file which does not exist", [&] { + const auto response = fixture.answer(get("/nothing.txt", "HEAD")); + then("the 404 has its headers only", [&] { + require(response.starts_with("HTTP/1.1 404 Not Found\r\n")); + require(response.ends_with("\r\n\r\n")); + }); + }); + }}; const Scenario fileWrapped{"A file wrapped after a prefix yields the remaining bytes and their count", [] { - webfront::test::TemporaryDirectory directory; - const auto path = directory.path() / "prefixed.bin"; - std::ofstream(path, std::ios::binary) << "prefix:payload"; - std::ifstream stream(path, std::ios::binary); - stream.seekg(7); - fs::File file{std::move(stream)}; - then("only the payload is counted and read", [&] { - require(file.knownSize() == 7); - std::array buffer{}; - const auto count = file.read(buffer); - require(std::string(buffer.data(), count) == "payload"); - }); -}}; + webfront::test::TemporaryDirectory directory; + const auto path = directory.path() / "prefixed.bin"; + std::ofstream(path, std::ios::binary) << "prefix:payload"; + std::ifstream stream(path, std::ios::binary); + stream.seekg(7); + fs::File file{std::move(stream)}; + then("only the payload is counted and read", [&] { + require(file.knownSize() == 7); + std::array buffer{}; + const auto count = file.read(buffer); + require(std::string(buffer.data(), count) == "payload"); + }); + }}; namespace { struct Completes { using receiver_concept = networking::ex::receiver_tag; std::promise* done; - void set_value() noexcept { done->set_value(); } - void set_error(std::exception_ptr) noexcept { done->set_value(); } - void set_stopped() noexcept { done->set_value(); } + void set_value() noexcept { + done->set_value(); + } + void set_error(std::exception_ptr) noexcept { + done->set_value(); + } + void set_stopped() noexcept { + done->set_value(); + } }; } // namespace const Scenario blockedJob{"A blocked job does not delay the others of a worker with several threads", [] { - BlockingWorker worker{2}; - std::promise release, blockedDone, quickDone; - auto shared = release.get_future().share(); - std::atomic blocked{false}; - auto blockedEnded = blockedDone.get_future(); - auto quickEnded = quickDone.get_future(); - auto slow = networking::ex::connect(worker.run([&] { blocked = true; shared.wait(); }), Completes{&blockedDone}); - auto fast = networking::ex::connect(worker.run([] {}), Completes{&quickDone}); - // The blocked job is released whatever happens: the worker's destructor waits for it. - struct Release { - std::promise& promise; - bool done = false; - void now() { - if (!std::exchange(done, true)) promise.set_value(); - } - ~Release() { now(); } - } releaseGuard{release}; - networking::ex::start(slow); - const bool started = waitUntil( - [&] { - return blocked.load(); - }, - 10s); - if (started) networking::ex::start(fast); - const bool quickDoneInTime = started && waitReady(quickEnded, 5s); - const bool slowStillBlocked = blockedEnded.wait_for(10ms) == std::future_status::timeout; - releaseGuard.now(); - if (started) blockedEnded.wait(); - if (started) quickEnded.wait(); // `fast` and `worker` outlive any use of each other, even when an assertion fails - then("the quick job completes while the slow one still runs", [&] { - require(started); - require(quickDoneInTime); - require(slowStillBlocked); - }); -}}; + BlockingWorker worker{2}; + std::promise release, blockedDone, quickDone; + auto shared = release.get_future().share(); + std::atomic blocked{false}; + auto blockedEnded = blockedDone.get_future(); + auto quickEnded = quickDone.get_future(); + auto slow = networking::ex::connect(worker.run([&] { + blocked = true; + shared.wait(); + }), + Completes{&blockedDone}); + auto fast = networking::ex::connect(worker.run([] {}), Completes{&quickDone}); + // The blocked job is released whatever happens: the worker's destructor waits for it. + struct Release { + std::promise& promise; + bool done = false; + void now() { + if (!std::exchange(done, true)) + promise.set_value(); + } + ~Release() { + now(); + } + } releaseGuard{release}; + networking::ex::start(slow); + const bool started = waitUntil( + [&] { + return blocked.load(); + }, + 10s); + if (started) + networking::ex::start(fast); + const bool quickDoneInTime = started && waitReady(quickEnded, 5s); + const bool slowStillBlocked = blockedEnded.wait_for(10ms) == std::future_status::timeout; + releaseGuard.now(); + if (started) + blockedEnded.wait(); + if (started) + quickEnded.wait(); // `fast` and `worker` outlive any use of each other, even when an assertion fails + then("the quick job completes while the slow one still runs", [&] { + require(started); + require(quickDoneInTime); + require(slowStillBlocked); + }); + }}; const Scenario singleThread{"A single-thread worker keeps the jobs in order", [] { - BlockingWorker worker; - std::promise firstDone, secondDone; - std::string order; - auto first = networking::ex::connect(worker.run([&] { order += 'a'; }), Completes{&firstDone}); - auto second = networking::ex::connect(worker.run([&] { order += 'b'; }), Completes{&secondDone}); - networking::ex::start(first); - networking::ex::start(second); - firstDone.get_future().wait(); - secondDone.get_future().wait(); - require(order == "ab"); -}}; + BlockingWorker worker; + std::promise firstDone, secondDone; + std::string order; + auto first = networking::ex::connect(worker.run([&] { + order += 'a'; + }), + Completes{&firstDone}); + auto second = networking::ex::connect(worker.run([&] { + order += 'b'; + }), + Completes{&secondDone}); + networking::ex::start(first); + networking::ex::start(second); + firstDone.get_future().wait(); + secondDone.get_future().wait(); + require(order == "ab"); + }}; const Scenario handlerBody{"A handler or a body throwing something else than a std::exception is contained", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - given("a handler which throws an int", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { throw 42; }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the browser gets a 500", [&] { require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); }); - }); - given("a body which throws an int after the headers", [&] { - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - RouteReply reply; - reply.contentLength = 10; - reply.body = [](std::span) -> std::size_t { throw 42; }; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("the connection ends after the headers", [&] { require(response.ends_with("\r\n\r\n")); }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + given("a handler which throws an int", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) -> RouteReply { + throw 42; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the browser gets a 500", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + }); + }); + given("a body which throws an int after the headers", [&] { + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + RouteReply reply; + reply.contentLength = 10; + reply.body = [](std::span) -> std::size_t { + throw 42; + }; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("the connection ends after the headers", [&] { + require(response.ends_with("\r\n\r\n")); + }); + }); + }}; const Scenario routeMatching{"Route matching sees the path as a URL path", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - std::string seen; - auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { - seen = std::string(request.path); - return text("ok"); - }); - auto plus = server.addRoute("/a+b/", [&](const RouteRequest& request) { - seen = std::string(request.path); - return text("plus"); - }); - given("a prefix with a literal plus", [&] { - const auto response = fixture.answer(get("/a+b/x+y")); - then("the plus stays a plus in the matching and in the path", [&] { - require(response.ends_with("plus")); - require(seen == "/a+b/x+y"); - }); - }); - given("a percent-encoded plus", [&] { - const auto response = fixture.answer(get("/a%2Bb/x")); - then("it matches the same route", [&] { require(response.ends_with("plus")); }); - }); - given("empty and dot segments before the prefix", [&] { - for (std::string target : {"/webfront//services/files/x", "/webfront/./services/files/x", "//webfront/services//files/./x"}) - when(target, [&] { - const auto response = fixture.answer(get(target)); - then("the route answers, not a file provider, with the normalized path", [&] { - require(response.ends_with("ok")); - require(seen == "/webfront/services/files/x"); - }); - }); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + std::string seen; + auto route = server.addRoute("/webfront/services/files/", [&](const RouteRequest& request) { + seen = std::string(request.path); + return text("ok"); + }); + auto plus = server.addRoute("/a+b/", [&](const RouteRequest& request) { + seen = std::string(request.path); + return text("plus"); + }); + given("a prefix with a literal plus", [&] { + const auto response = fixture.answer(get("/a+b/x+y")); + then("the plus stays a plus in the matching and in the path", [&] { + require(response.ends_with("plus")); + require(seen == "/a+b/x+y"); + }); + }); + given("a percent-encoded plus", [&] { + const auto response = fixture.answer(get("/a%2Bb/x")); + then("it matches the same route", [&] { + require(response.ends_with("plus")); + }); + }); + given("empty and dot segments before the prefix", [&] { + for (std::string target : + {"/webfront//services/files/x", "/webfront/./services/files/x", "//webfront/services//files/./x"}) + when(target, [&] { + const auto response = fixture.answer(get(target)); + then("the route answers, not a file provider, with the normalized path", [&] { + require(response.ends_with("ok")); + require(seen == "/webfront/services/files/x"); + }); + }); + }); + }}; const Scenario handlerMay{"A handler may answer 405 with a body of its own", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("not this path"); - reply.status = Response::methodNotAllowed; - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("its body is streamed after its headers", [&] { - require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); - require(response.ends_with("\r\n\r\nnot this path")); - }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("not this path"); + reply.status = Response::methodNotAllowed; + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("its body is streamed after its headers", [&] { + require(response.starts_with("HTTP/1.1 405 Method Not Allowed\r\n")); + require(response.ends_with("\r\n\r\nnot this path")); + }); + }}; const Scenario headerNames{"Header names are ASCII tokens whatever the locale", [] { - Fixture fixture; - Router server("127.0.0.1", "0"); - auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { - auto reply = text("x"); - reply.headers.emplace_back("X-Caf\xC3\xA9", "v"); - return reply; - }); - const auto response = fixture.answer(get("/webfront/services/files/x")); - then("a non-ASCII name is refused", [&] { require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); }); -}}; + Fixture fixture; + Router server("127.0.0.1", "0"); + auto route = server.addRoute("/webfront/services/files/", [](const RouteRequest&) { + auto reply = text("x"); + reply.headers.emplace_back("X-Caf\xC3\xA9", "v"); + return reply; + }); + const auto response = fixture.answer(get("/webfront/services/files/x")); + then("a non-ASCII name is refused", [&] { + require(response.starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + }); + }}; diff --git a/test/unit/HTTPServerTests.cpp b/test/unit/HTTPServerTests.cpp index 483deafd..a8760c81 100644 --- a/test/unit/HTTPServerTests.cpp +++ b/test/unit/HTTPServerTests.cpp @@ -1,9 +1,9 @@ #include "InjectableNetworking.hpp" #include "Mocks.hpp" -#include #include #include #include +#include #include #include @@ -22,163 +22,171 @@ using namespace std; using Net = networking::NetworkingMock; const Scenario hTTPRequest{"HTTP Request", [] { - given("A request with % encoded characters", [&] { - Request request; - request.uri = "http://aaa.bbb.ccc/bozo%20le%20clown"; - - when("decoding url", [&] { - then("% are expanded and decoded", [&] { require(uri::decode(request.uri) == "http://aaa.bbb.ccc/bozo le clown"); }); - }); - }); - - require(Request::getMethodFromString("GET") == Request::Method::Get); - require(Request::getMethodFromString("HEAD") == Request::Method::Head); - require(Request::getMethodFromString("CONNECT") == Request::Method::Connect); - require(Request::getMethodFromString("DELETE") == Request::Method::Delete); - require(Request::getMethodFromString("OPTIONS") == Request::Method::Options); - require(Request::getMethodFromString("PATCH") == Request::Method::Patch); - require(Request::getMethodFromString("POST") == Request::Method::Post); - require(Request::getMethodFromString("PUT") == Request::Method::Put); - require(Request::getMethodFromString("TRACE") == Request::Method::Trace); - require(Request::getMethodFromString("test") == Request::Method::Undefined); -}}; + given("A request with % encoded characters", [&] { + Request request; + request.uri = "http://aaa.bbb.ccc/bozo%20le%20clown"; + + when("decoding url", [&] { + then("% are expanded and decoded", [&] { + require(uri::decode(request.uri) == "http://aaa.bbb.ccc/bozo le clown"); + }); + }); + }); + + require(Request::getMethodFromString("GET") == Request::Method::Get); + require(Request::getMethodFromString("HEAD") == Request::Method::Head); + require(Request::getMethodFromString("CONNECT") == Request::Method::Connect); + require(Request::getMethodFromString("DELETE") == Request::Method::Delete); + require(Request::getMethodFromString("OPTIONS") == Request::Method::Options); + require(Request::getMethodFromString("PATCH") == Request::Method::Patch); + require(Request::getMethodFromString("POST") == Request::Method::Post); + require(Request::getMethodFromString("PUT") == Request::Method::Put); + require(Request::getMethodFromString("TRACE") == Request::Method::Trace); + require(Request::getMethodFromString("test") == Request::Method::Undefined); + }}; const Scenario hTTPResponse{"HTTP Response", [] { - given("Ok Response", [&] { - auto ok = Response::getStatusResponse(Response::ok); - then("Fields should be", [&] { - require(ok.content == "OK

200 OK

"); - require(ok.headers[0].name == "Content-Length"); - require(ok.headers[1].name == "Content-Type"); - require(ok.headers[0].value == "71"); - require(ok.headers[1].value == "text/html"); - }); - }); - - given("notFound Response", [&] { - auto notFound = Response::getStatusResponse(Response::notFound); - then("Fields should be", [&] { - require(notFound.content == - "Not Found

404 Not Found

"); - require(notFound.headers[0].name == "Content-Length"); - require(notFound.headers[1].name == "Content-Type"); - require(notFound.headers[0].value == "85"); - require(notFound.headers[1].value == "text/html"); - }); - }); - - given("badRequest Response", [&] { - auto bad = Response::getStatusResponse(Response::badRequest); - when("extracting buffers", [&] { - auto buffers = bad.toBuffers(); - then("buffer contents should be", [&] { - require(buffers.size() == 12); - using Buffer = decltype(buffers[0]); - auto compare = [](Buffer b, std::string s) { - auto data = reinterpret_cast(b.data()); - for (size_t index = 0; index < s.size(); ++index) - if (data[index] != s[index]) return false; - return true; - }; - require(compare(buffers[0], "HTTP/1.1 400 Bad Request")); - require(compare(buffers[1], "Content-Length")); - require(compare(buffers[2], ": ")); - require(compare(buffers[3], "89")); - require(compare(buffers[4], "\r\n")); - require(compare(buffers[5], "Content-Type")); - require(compare(buffers[6], ": ")); - require(compare(buffers[7], "text/html")); - require(compare(buffers[8], "\r\n")); - require(compare(buffers[9], "Connection: close\r\n")); - require(compare(buffers[10], "\r\n")); - require(compare(buffers[11], - "Bad Request

400 Bad Request

")); - }); - }); - }); -}}; + given("Ok Response", [&] { + auto ok = Response::getStatusResponse(Response::ok); + then("Fields should be", [&] { + require(ok.content == "OK

200 OK

"); + require(ok.headers[0].name == "Content-Length"); + require(ok.headers[1].name == "Content-Type"); + require(ok.headers[0].value == "71"); + require(ok.headers[1].value == "text/html"); + }); + }); + + given("notFound Response", [&] { + auto notFound = Response::getStatusResponse(Response::notFound); + then("Fields should be", [&] { + require(notFound.content == "Not Found

404 Not Found

"); + require(notFound.headers[0].name == "Content-Length"); + require(notFound.headers[1].name == "Content-Type"); + require(notFound.headers[0].value == "85"); + require(notFound.headers[1].value == "text/html"); + }); + }); + + given("badRequest Response", [&] { + auto bad = Response::getStatusResponse(Response::badRequest); + when("extracting buffers", [&] { + auto buffers = bad.toBuffers(); + then("buffer contents should be", [&] { + require(buffers.size() == 12); + using Buffer = decltype(buffers[0]); + auto compare = [](Buffer b, std::string s) { + auto data = reinterpret_cast(b.data()); + for (size_t index = 0; index < s.size(); ++index) + if (data[index] != s[index]) + return false; + return true; + }; + require(compare(buffers[0], "HTTP/1.1 400 Bad Request")); + require(compare(buffers[1], "Content-Length")); + require(compare(buffers[2], ": ")); + require(compare(buffers[3], "89")); + require(compare(buffers[4], "\r\n")); + require(compare(buffers[5], "Content-Type")); + require(compare(buffers[6], ": ")); + require(compare(buffers[7], "text/html")); + require(compare(buffers[8], "\r\n")); + require(compare(buffers[9], "Connection: close\r\n")); + require(compare(buffers[10], "\r\n")); + require(compare(buffers[11], + "Bad Request

400 Bad Request

")); + }); + }); + }); + }}; const Scenario pendingHTTP{"Pending HTTP response buffers remain independent and announce connection closure", [] { - const auto text = [](const auto& buffers) { - std::string result; - for (const auto& buffer : buffers) - result.append(static_cast(buffer.data()), buffer.size()); - return result; - }; - auto first = Response::getStatusResponse(Response::internalServerError); - auto firstBuffers = first.toBuffers(); - auto second = Response::getStatusResponse(Response::ok); - auto secondBuffers = second.toBuffers(); - then("another pending send cannot replace the first status line", [&] { - require(text(firstBuffers).starts_with("HTTP/1.1 500 Internal Server Error\r\n")); - require(text(secondBuffers).starts_with("HTTP/1.1 200 OK\r\n")); - }); - then("ordinary responses tell clients that the server will close the connection", [&] { - require(text(firstBuffers).find("\r\nConnection: close\r\n") != std::string::npos); - require(text(secondBuffers).find("\r\nConnection: close\r\n") != std::string::npos); - }); - given("a WebSocket upgrade", [&] { - Response upgrade; - upgrade.statusCode = Response::switchingProtocols; - upgrade.headers.emplace_back("Connection", "Upgrade"); - const auto response = text(upgrade.toBuffers()); - require(response.find("\r\nConnection: Upgrade\r\n") != std::string::npos); - require(response.find("Connection: close") == std::string::npos); - require(text(firstBuffers).starts_with("HTTP/1.1 500 Internal Server Error\r\n")); - }); -}}; + const auto text = [](const auto& buffers) { + std::string result; + for (const auto& buffer : buffers) + result.append(static_cast(buffer.data()), buffer.size()); + return result; + }; + auto first = Response::getStatusResponse(Response::internalServerError); + auto firstBuffers = first.toBuffers(); + auto second = Response::getStatusResponse(Response::ok); + auto secondBuffers = second.toBuffers(); + then("another pending send cannot replace the first status line", [&] { + require(text(firstBuffers).starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + require(text(secondBuffers).starts_with("HTTP/1.1 200 OK\r\n")); + }); + then("ordinary responses tell clients that the server will close the connection", [&] { + require(text(firstBuffers).find("\r\nConnection: close\r\n") != std::string::npos); + require(text(secondBuffers).find("\r\nConnection: close\r\n") != std::string::npos); + }); + given("a WebSocket upgrade", [&] { + Response upgrade; + upgrade.statusCode = Response::switchingProtocols; + upgrade.headers.emplace_back("Connection", "Upgrade"); + const auto response = text(upgrade.toBuffers()); + require(response.find("\r\nConnection: Upgrade\r\n") != std::string::npos); + require(response.find("Connection: close") == std::string::npos); + require(text(firstBuffers).starts_with("HTTP/1.1 500 Internal Server Error\r\n")); + }); + }}; const Scenario requestParser{"RequestParser", [] { - given("A valid HTTP request", [&] { - string input{"GET /hello.htm HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.tutorialspoint.com\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip\r\n" - "Accept-Encoding: deflate\r\nConnection: Keep-Alive\r\n\r\n"}; - when("parsing it", [&] { - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - then("It should fill correctly the Request structure", [&] { - require(request.completed()); - require(request.uri == "/hello.htm"); - require(request.method == Request::Method::Get); - - auto language = request.getHeaderValue("Accept-Language"); - require(language == "en-us"); - - require(!request.getHeaderValue("Bozo le clown")); - - auto encodings = request.getHeadersValues("Accept-Encoding"); - require(encodings.size() == 2); - - require(request.headersContain("Accept-Encoding", "deflate")); - require(request.headersContain("Accept-Encoding", "gzip")); - }); - }); - }); - - given("An invalid HTTP request", [&] { - string input{"GET /hello.htm HTTP/1.1\r\nUser - Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.tutorialspoint.com\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nConnection: " - "Keep-Alive\r\n\r\n"}; - when("parsing it", [&] { - Request request; - requireThrows([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - }); - }); - - given("An upgrade request", [&] { - string input{"GET / HTTP/1.1\r\nOrigin: localhost\r\nSec-WebSocket-Protocol: WebFront_0.1\r\nSec-WebSocket-Extensions: " - "permessage-deflate\r\nSec-WebSocket-Key: Dh54KYbN4sDdk6ejeVPqXQ==\r\nConnection: keep-alive, " - "Upgrade\r\nUpgrade: websocket\r\n\r\n"}; - when("parsing it", [&] { - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - then("An upgrade request should be detected", [&] { - require(request.completed()); - require(request.isUpgradeRequest("websocket")); - }); - }); - }); -}}; + given("A valid HTTP request", [&] { + string input{"GET /hello.htm HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.tutorialspoint.com\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip\r\n" + "Accept-Encoding: deflate\r\nConnection: Keep-Alive\r\n\r\n"}; + when("parsing it", [&] { + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + then("It should fill correctly the Request structure", [&] { + require(request.completed()); + require(request.uri == "/hello.htm"); + require(request.method == Request::Method::Get); + + auto language = request.getHeaderValue("Accept-Language"); + require(language == "en-us"); + + require(!request.getHeaderValue("Bozo le clown")); + + auto encodings = request.getHeadersValues("Accept-Encoding"); + require(encodings.size() == 2); + + require(request.headersContain("Accept-Encoding", "deflate")); + require(request.headersContain("Accept-Encoding", "gzip")); + }); + }); + }); + + given("An invalid HTTP request", [&] { + string input{"GET /hello.htm HTTP/1.1\r\nUser - Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.tutorialspoint.com\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nConnection: " + "Keep-Alive\r\n\r\n"}; + when("parsing it", [&] { + Request request; + requireThrows([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + }); + }); + + given("An upgrade request", [&] { + string input{"GET / HTTP/1.1\r\nOrigin: localhost\r\nSec-WebSocket-Protocol: WebFront_0.1\r\nSec-WebSocket-Extensions: " + "permessage-deflate\r\nSec-WebSocket-Key: Dh54KYbN4sDdk6ejeVPqXQ==\r\nConnection: keep-alive, " + "Upgrade\r\nUpgrade: websocket\r\n\r\n"}; + when("parsing it", [&] { + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + then("An upgrade request should be detected", [&] { + require(request.completed()); + require(request.isUpgradeRequest("websocket")); + }); + }); + }); + }}; struct ResourceAndFile { static inline list names{"ressource.txt", "file.txt", "compressed.txt"}; @@ -187,188 +195,219 @@ struct ResourceAndFile { bool compare(auto& buffer, std::string text) { auto data = reinterpret_cast(buffer.data()); for (size_t index = 0; index < text.size(); ++index) - if (data[index] != text[index]) return false; + if (data[index] != text[index]) + return false; return true; }; const Scenario requestParsing{"Request parsing", [] { - given("A valid HTTP request with an unimplemented method", [&] { - string input{"DELETE /ressource.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - require(request.completed()); - require(request.uri == "/ressource.txt"); - require(request.method == Request::Method::Delete); - when("A RequestHandler process it", [&] { - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - - then("It should respond with a 'Not Implemented' http response", [&] { - auto buffers = response.toBuffers(); - require(compare(buffers[0], "HTTP/1.1 501 Not Implemented")); - }); - }); - }); - - given("A valid HTTP upgrade request to websocket protocol", [&] { - string input{ - "GET /chat HTTP/1.1\r\nHost: server.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " - "x3JJHMbDL1EzLkh9GBhXDw==\r\nSec-WebSocket-Protocol: chat, superchat\r\nSec-WebSocket-Version: 13\r\nOrigin: " - "http://example.com\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - require(request.completed()); - require(request.uri == "/chat"); - require(request.method == Request::Method::Get); - when("A RequestHandler process it", [&] { - RequestHandler> handler{".", detail::BoundContentPolicy{"http://example.com"}}; - auto response = handler.handleRequest(request); - - then("It should respond with a 'Switching Protocols' http response", [&] { - auto buffers = response.toBuffers(); - require(compare(buffers[0], "HTTP/1.1 101 Switching Protocols")); - require(compare(buffers[1], "Upgrade")); - require(compare(buffers[3], "websocket")); - require(compare(buffers[9], "Sec-WebSocket-Accept")); - require(compare(buffers[11], "HSmrc0sMlYUkAGmm5OPpG2HaGWk=")); - }); - }); - }); - - given("A HTTP HEAD request", [&] { - string input{"HEAD /file.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-Encoding: br\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - require(request.completed()); - require(request.uri == "/file.txt"); - require(request.method == Request::Method::Head); - when("A RequestHandler process it", [&] { - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - - then("It should find the file", [&] { require(response.statusCode == Response::ok); }); + given("A valid HTTP request with an unimplemented method", [&] { + string input{"DELETE /ressource.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + require(request.completed()); + require(request.uri == "/ressource.txt"); + require(request.method == Request::Method::Delete); + when("A RequestHandler process it", [&] { + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); + + then("It should respond with a 'Not Implemented' http response", [&] { + auto buffers = response.toBuffers(); + require(compare(buffers[0], "HTTP/1.1 501 Not Implemented")); + }); + }); + }); + + given("A valid HTTP upgrade request to websocket protocol", [&] { + string input{ + "GET /chat HTTP/1.1\r\nHost: server.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " + "x3JJHMbDL1EzLkh9GBhXDw==\r\nSec-WebSocket-Protocol: chat, superchat\r\nSec-WebSocket-Version: 13\r\nOrigin: " + "http://example.com\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + require(request.completed()); + require(request.uri == "/chat"); + require(request.method == Request::Method::Get); + when("A RequestHandler process it", [&] { + RequestHandler> handler{".", detail::BoundContentPolicy{"http://example.com"}}; + auto response = handler.handleRequest(request); + + then("It should respond with a 'Switching Protocols' http response", [&] { + auto buffers = response.toBuffers(); + require(compare(buffers[0], "HTTP/1.1 101 Switching Protocols")); + require(compare(buffers[1], "Upgrade")); + require(compare(buffers[3], "websocket")); + require(compare(buffers[9], "Sec-WebSocket-Accept")); + require(compare(buffers[11], "HSmrc0sMlYUkAGmm5OPpG2HaGWk=")); + }); + }); + }); + + given("A HTTP HEAD request", [&] { + string input{"HEAD /file.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-Encoding: br\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + require(request.completed()); + require(request.uri == "/file.txt"); + require(request.method == Request::Method::Head); + when("A RequestHandler process it", [&] { + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); + + then("It should find the file", [&] { + require(response.statusCode == Response::ok); + }); + }); + }); + + given("A HTTP HEAD request with an empty URL", [&] { + string input{"HEAD HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; + + Request request; + requireThrows([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + }); + }}; + +const Scenario headerWhitespace{ + "HTTP header values accept optional whitespace and empty values", + [] { + given("headers split across individual receives", [] { + const std::string input = "GET / HTTP/1.1\r\nContent-Length:5\r\nX-Tab:\t \talpha\tbeta \t\r\nX-Empty:\r\nX-Blank: \t\r\n\r\n"; + Request request; + for (const char& byte : input) + request.parseSomeData(&byte, &byte + 1); + require(request.completed()); + require(request.getHeaderValue("Content-Length") == "5"); + require(request.getHeaderValue("X-Tab") == "alpha\tbeta \t"); + require(request.getHeaderValue("X-Empty") == ""); + require(request.getHeaderValue("X-Blank") == ""); }); - }); - - given("A HTTP HEAD request with an empty URL", [&] { - string input{"HEAD HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; - - Request request; - requireThrows([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - }); -}}; - -const Scenario headerWhitespace{"HTTP header values accept optional whitespace and empty values", [] { - given("headers split across individual receives", [] { - const std::string input = "GET / HTTP/1.1\r\nContent-Length:5\r\nX-Tab:\t \talpha\tbeta \t\r\nX-Empty:\r\nX-Blank: \t\r\n\r\n"; - Request request; - for (const char& byte : input) request.parseSomeData(&byte, &byte + 1); - require(request.completed()); - require(request.getHeaderValue("Content-Length") == "5"); - require(request.getHeaderValue("X-Tab") == "alpha\tbeta \t"); - require(request.getHeaderValue("X-Empty") == ""); - require(request.getHeaderValue("X-Blank") == ""); - }); - given("forbidden control characters in a field value", [] { - for (const char control : {'\0', '\1', '\n', '\x7f'}) { - std::string input = "GET / HTTP/1.1\r\nX-Test: value"; - input += control; - input += "more\r\n\r\n"; - Request request; - requireThrows([&] { request.parseSomeData(input.begin(), input.end()); }); - } - const std::string input = "GET / HTTP/1.1\r\nX-Test: value\rmore\r\n\r\n"; - Request request; - requireThrows([&] { request.parseSomeData(input.begin(), input.end()); }); - }); - given("a forbidden control character before a field value", [] { - for (const std::string prefix : {"X-Test:", "X-Test: "}) { + given("forbidden control characters in a field value", [] { for (const char control : {'\0', '\1', '\n', '\x7f'}) { - std::string input = "GET / HTTP/1.1\r\n" + prefix; - input += control; - input += "value\r\n\r\n"; + std::string input = "GET / HTTP/1.1\r\nX-Test: value"; + input += control; + input += "more\r\n\r\n"; Request request; - requireThrows([&] { request.parseSomeData(input.begin(), input.end()); }); + requireThrows([&] { + request.parseSomeData(input.begin(), input.end()); + }); } - } - }); -}}; - -const Scenario asynchronousRequest{"Asynchronous Request parsing", [] { - given("A HTTP HEAD request received asynchronously", [&] { - string chunk1{"HEAD /file.txt HTTP/1.1\r\nUser-Agent:"}; - string chunk2{" Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: "}; - string chunk3{"www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-Encoding: br\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(chunk1.cbegin(), chunk1.cend()); }); - require(!request.completed()); - requireNothrow([&] { request.parseSomeData(chunk2.cbegin(), chunk2.cend()); }); - require(!request.completed()); - requireNothrow([&] { request.parseSomeData(chunk3.cbegin(), chunk3.cend()); }); - require(request.completed()); - require(request.uri == "/file.txt"); - require(request.method == Request::Method::Head); - when("A RequestHandler process it", [&] { - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - - then("It should find the file", [&] { require(response.statusCode == Response::ok); }); - }); - }); -}}; - -const Scenario requestHandlerHTTP{"RequestHandler on a HTTP GET", [] { - given("A valid HTTP GET request on a compressed file with no supported encoding", [&] { - string input{"GET /compressed.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - require(request.completed()); - require(request.uri == "/compressed.txt"); - require(request.method == Request::Method::Get); - when("A RequestHandler process it", [&] { - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - - then("It should reject an unavailable custom encoding", [&] { - auto buffers = response.toBuffers(); - require(compare(buffers[0], "HTTP/1.1 406 Not Acceptable")); + const std::string input = "GET / HTTP/1.1\r\nX-Test: value\rmore\r\n\r\n"; + Request request; + requireThrows([&] { + request.parseSomeData(input.begin(), input.end()); }); }); - }); - - given("A valid HTTP GET request on a compressed file with supported encoding", [&] { - string input{"GET /compressed.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " - "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-encoding: gzip, br, deflate\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); - require(request.completed()); - require(request.uri == "/compressed.txt"); - require(request.method == Request::Method::Get); - when("A RequestHandler process it", [&] { - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); - then("It should respond ok with a brotli encoded (empty) file", [&] { - require(response.statusCode == Response::ok); - require(response.getHeaderValue("Content-Encoding") == "br"); - require(response.getHeaderValue("Content-Type") == "text/plain"); - require(response.getHeaderValue("Content-Length") == "0"); - }); + given("a forbidden control character before a field value", [] { + for (const std::string prefix : {"X-Test:", "X-Test: "}) { + for (const char control : {'\0', '\1', '\n', '\x7f'}) { + std::string input = "GET / HTTP/1.1\r\n" + prefix; + input += control; + input += "value\r\n\r\n"; + Request request; + requireThrows([&] { + request.parseSomeData(input.begin(), input.end()); + }); + } + } }); - }); + }}; + +const Scenario asynchronousRequest{"Asynchronous Request parsing", [] { + given("A HTTP HEAD request received asynchronously", [&] { + string chunk1{"HEAD /file.txt HTTP/1.1\r\nUser-Agent:"}; + string chunk2{" Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: "}; + string chunk3{"www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-Encoding: br\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(chunk1.cbegin(), chunk1.cend()); + }); + require(!request.completed()); + requireNothrow([&] { + request.parseSomeData(chunk2.cbegin(), chunk2.cend()); + }); + require(!request.completed()); + requireNothrow([&] { + request.parseSomeData(chunk3.cbegin(), chunk3.cend()); + }); + require(request.completed()); + require(request.uri == "/file.txt"); + require(request.method == Request::Method::Head); + when("A RequestHandler process it", [&] { + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); + + then("It should find the file", [&] { + require(response.statusCode == Response::ok); + }); + }); + }); + }}; -}}; +const Scenario requestHandlerHTTP{"RequestHandler on a HTTP GET", [] { + given("A valid HTTP GET request on a compressed file with no supported encoding", [&] { + string input{"GET /compressed.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + require(request.completed()); + require(request.uri == "/compressed.txt"); + require(request.method == Request::Method::Get); + when("A RequestHandler process it", [&] { + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); + + then("It should reject an unavailable custom encoding", [&] { + auto buffers = response.toBuffers(); + require(compare(buffers[0], "HTTP/1.1 406 Not Acceptable")); + }); + }); + }); + + given("A valid HTTP GET request on a compressed file with supported encoding", [&] { + string input{"GET /compressed.txt HTTP/1.1\r\nUser-Agent: Mozilla / 4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: " + "www.bernardlehacker.com\r\nConnection: Keep-Alive\r\nAccept-encoding: gzip, br, deflate\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); + require(request.completed()); + require(request.uri == "/compressed.txt"); + require(request.method == Request::Method::Get); + when("A RequestHandler process it", [&] { + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); + then("It should respond ok with a brotli encoded (empty) file", [&] { + require(response.statusCode == Response::ok); + require(response.getHeaderValue("Content-Encoding") == "br"); + require(response.getHeaderValue("Content-Type") == "text/plain"); + require(response.getHeaderValue("Content-Length") == "0"); + }); + }); + }); + }}; namespace { // Accepts one connection which asks for a WebSocket upgrade; the end of the response write is held. // The first accept fails if failFirstAccept is set, and the accepts after the connection are cancelled. struct UpgradingNet : networking::NetworkingMock { - static inline int accepts = 0; - static inline bool failFirstAccept = false; + static inline int accepts = 0; + static inline bool failFirstAccept = false; static inline webfront::testing::ManualSender::Completion heldSend; static void reset(bool failFirst) { @@ -380,8 +419,10 @@ struct UpgradingNet : networking::NetworkingMock { static auto Accept(Acceptor&) { return networking::ex::then(networking::ex::just(), []() -> Socket { const int number = ++accepts; - if (failFirstAccept && number == 1) throw std::system_error(make_error_code(errc::connection_aborted)); - if (number > (failFirstAccept ? 2 : 1)) throw std::system_error(make_error_code(errc::operation_canceled)); + if (failFirstAccept && number == 1) + throw std::system_error(make_error_code(errc::connection_aborted)); + if (number > (failFirstAccept ? 2 : 1)) + throw std::system_error(make_error_code(errc::operation_canceled)); return Socket{}; }); } @@ -389,46 +430,54 @@ struct UpgradingNet : networking::NetworkingMock { static auto Receive(Socket&, MutableBuffer buffer) { return networking::ex::then(networking::ex::just(), [buffer] { static constexpr string_view request{"GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"}; + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"}; copy(request.begin(), request.end(), static_cast(buffer.data())); return request.size(); }); } static webfront::testing::ManualSender Send(Socket&, const auto&) { - return webfront::testing::ManualSender([](webfront::testing::ManualSender::Completion completion) { heldSend = std::move(completion); }); + return webfront::testing::ManualSender([](webfront::testing::ManualSender::Completion completion) { + heldSend = std::move(completion); + }); } }; } // namespace const Scenario stoppedServer{"A stopped server hands no connection over", [] { - given("A connection asking for an upgrade, whose response write is still in progress", [&] { - int upgrades = 0; - UpgradingNet::reset(false); - { - http::Server server("127.0.0.1", "0"); - server.onUpgrade([&upgrades](UpgradingNet::Socket&&) { ++upgrades; }); - require(UpgradingNet::heldSend.complete); - - when("the server is stopped before the response is written", [&] { - server.stop(); - UpgradingNet::heldSend.complete({}, 0); - - then("the connection is closed instead of being upgraded", [&] { require(upgrades == 0); }); - }); - } - }); -}}; + given("A connection asking for an upgrade, whose response write is still in progress", [&] { + int upgrades = 0; + UpgradingNet::reset(false); + { + http::Server server("127.0.0.1", "0"); + server.onUpgrade([&upgrades](UpgradingNet::Socket&&) { + ++upgrades; + }); + require(UpgradingNet::heldSend.complete); + + when("the server is stopped before the response is written", [&] { + server.stop(); + UpgradingNet::heldSend.complete({}, 0); + + then("the connection is closed instead of being upgraded", [&] { + require(upgrades == 0); + }); + }); + } + }); + }}; const Scenario failedAccept{"A failed accept does not stop the server from accepting", [] { - given("A first accept which fails, then a connection", [&] { - UpgradingNet::reset(true); - http::Server server("127.0.0.1", "0"); + given("A first accept which fails, then a connection", [&] { + UpgradingNet::reset(true); + http::Server server("127.0.0.1", "0"); - then("the connection is served", [&] { require(UpgradingNet::heldSend.complete); }); - }); -}}; + then("the connection is served", [&] { + require(UpgradingNet::heldSend.complete); + }); + }); + }}; // Serves "index.html", "app.js" and "a?b.txt", and records every path it is asked to open. struct RecordingFS { @@ -446,90 +495,92 @@ struct RecordingFS { }; const Scenario requestHandlerIgnores{"RequestHandler ignores the query string of a request", [] { - RecordingFS::opened.clear(); - RequestHandler handler{"."}; - const auto get = [&](string uri, Request::Method method = Request::Method::Get) { - Request request; - request.method = method; - request.uri = std::move(uri); - return handler.handleRequest(request).statusCode; - }; - - given("A GET request with a query", [&] { - then("The file is looked up without it", [&] { - require(get("/app.js?v=2&debug=1") == Response::ok); - require(RecordingFS::opened == vector{"app.js"}); - }); - }); - given("A query on a file that does not exist", [&] { - then("The request fails with not found", [&] { - require(get("/missing.js?v=2") == Response::notFound); - require(RecordingFS::opened == vector{"missing.js"}); - }); - }); - given("A query on the root", [&] { - then("The default page is served", [&] { - require(get("/?x=1") == Response::ok); - require(RecordingFS::opened == vector{"index.html"}); - }); - }); - given("A HEAD request with a query", [&] { - then("The file is found", [&] { - require(get("/app.js?v=2", Request::Method::Head) == Response::ok); - }); - }); - given("A percent-encoded question mark", [&] { - then("It is part of the file name, not a query", [&] { - require(get("/a%3Fb.txt") == Response::ok); - require(RecordingFS::opened == vector{"a?b.txt"}); - }); - }); - given("Encoded dots in the path, or a question mark in the query", [&] { - then("The '..' check applies to the decoded path only", [&] { - require(get("/%2E%2E/secret.txt") == Response::badRequest); - require(get("/app.js?path=../x") == Response::ok); - }); - }); -}}; + RecordingFS::opened.clear(); + RequestHandler handler{"."}; + const auto get = [&](string uri, Request::Method method = Request::Method::Get) { + Request request; + request.method = method; + request.uri = std::move(uri); + return handler.handleRequest(request).statusCode; + }; + + given("A GET request with a query", [&] { + then("The file is looked up without it", [&] { + require(get("/app.js?v=2&debug=1") == Response::ok); + require(RecordingFS::opened == vector{"app.js"}); + }); + }); + given("A query on a file that does not exist", [&] { + then("The request fails with not found", [&] { + require(get("/missing.js?v=2") == Response::notFound); + require(RecordingFS::opened == vector{"missing.js"}); + }); + }); + given("A query on the root", [&] { + then("The default page is served", [&] { + require(get("/?x=1") == Response::ok); + require(RecordingFS::opened == vector{"index.html"}); + }); + }); + given("A HEAD request with a query", [&] { + then("The file is found", [&] { + require(get("/app.js?v=2", Request::Method::Head) == Response::ok); + }); + }); + given("A percent-encoded question mark", [&] { + then("It is part of the file name, not a query", [&] { + require(get("/a%3Fb.txt") == Response::ok); + require(RecordingFS::opened == vector{"a?b.txt"}); + }); + }); + given("Encoded dots in the path, or a question mark in the query", [&] { + then("The '..' check applies to the decoded path only", [&] { + require(get("/%2E%2E/secret.txt") == Response::badRequest); + require(get("/app.js?path=../x") == Response::ok); + }); + }); + }}; const Scenario hTTPVersion{"HTTP version digits cannot overflow their integer fields", [] { - for (const std::string version : {"99999999999999999999.1", "1.99999999999999999999"}) { - const auto input = "GET / HTTP/" + version + "\r\n\r\n"; - Request request; - requireThrows([&] { request.parseSomeData(input.begin(), input.end()); }); - } -}}; + for (const std::string version : {"99999999999999999999.1", "1.99999999999999999999"}) { + const auto input = "GET / HTTP/" + version + "\r\n\r\n"; + Request request; + requireThrows([&] { + request.parseSomeData(input.begin(), input.end()); + }); + } + }}; const Scenario unknownHTTP{"Unknown HTTP methods have a safe display name", [] { - const std::string input = "CUSTOM / HTTP/1.1\r\n\r\n"; - Request request; - require(request.parseSomeData(input.begin(), input.end())); - require(request.getMethodName() == "Undefined"); -}}; + const std::string input = "CUSTOM / HTTP/1.1\r\n\r\n"; + Request request; + require(request.parseSomeData(input.begin(), input.end())); + require(request.getMethodName() == "Undefined"); + }}; const Scenario hTTPRequests{"HTTP requests keep method parsing state across interleaved receives", [] { - given("two connections whose method names arrive in separate reads", [&] { - Request first; - Request second; - const std::string firstStart = "G"; - const std::string secondStart = "PO"; - require(!first.parseSomeData(firstStart.begin(), firstStart.end())); - require(!second.parseSomeData(secondStart.begin(), secondStart.end())); - - when("the first request completes before the second", [&] { - const std::string firstRest = "ET /first HTTP/1.1\r\n\r\n"; - const std::string secondRest = "ST /second HTTP/1.1\r\n\r\n"; - require(first.parseSomeData(firstRest.begin(), firstRest.end())); - require(second.parseSomeData(secondRest.begin(), secondRest.end())); - - then("the first request retains its method and URI", [&] { - check(first.method == Request::Method::Get); - check(first.uri == "/first"); - }); - andThen("the second request retains its method and URI", [&] { - check(second.method == Request::Method::Post); - check(second.uri == "/second"); - }); - }); - }); -}}; + given("two connections whose method names arrive in separate reads", [&] { + Request first; + Request second; + const std::string firstStart = "G"; + const std::string secondStart = "PO"; + require(!first.parseSomeData(firstStart.begin(), firstStart.end())); + require(!second.parseSomeData(secondStart.begin(), secondStart.end())); + + when("the first request completes before the second", [&] { + const std::string firstRest = "ET /first HTTP/1.1\r\n\r\n"; + const std::string secondRest = "ST /second HTTP/1.1\r\n\r\n"; + require(first.parseSomeData(firstRest.begin(), firstRest.end())); + require(second.parseSomeData(secondRest.begin(), secondRest.end())); + + then("the first request retains its method and URI", [&] { + check(first.method == Request::Method::Get); + check(first.uri == "/first"); + }); + andThen("the second request retains its method and URI", [&] { + check(second.method == Request::Method::Post); + check(second.uri == "/second"); + }); + }); + }); + }}; diff --git a/test/unit/HostLoopTests.cpp b/test/unit/HostLoopTests.cpp index ad50018d..9f3cddd2 100644 --- a/test/unit/HostLoopTests.cpp +++ b/test/unit/HostLoopTests.cpp @@ -49,8 +49,8 @@ std::vector unpacked(const std::vector& runs) { // A consumer that counts the images it receives and keeps the last one. struct Consumer { - int received{0}; - Frame last; + int received{0}; + Frame last; Host::Deliver deliver() { return [this](const Frame& frame) { ++received; @@ -60,453 +60,531 @@ struct Consumer { }; } // namespace -const Scenario hostLoopCapture{"Host loop: capture refuses unsupported modes and reports failures", [] { - using webfront::frontend::CaptureResult; - then("capture needs a native window, including when benchmark would otherwise take precedence", [] { - validateCapture(true, true, false, false); - validateCapture(false, false, true, true); - requireThrows([] { validateCapture(true, false, false, false); }); - requireThrows([] { validateCapture(true, true, true, false); }); - requireThrows([] { validateCapture(true, true, false, true); }); - }); - then("a frame clock advances only for rendered frames and survives a material change", [] { - Host host{{.quality = 0}}; - require(!host.iterate(0.04, true)); - require(host.sceneSeconds() == 0.); - host.request(1, [](const Frame&) {}); - require(host.iterate(0.04, true)); - require(host.sceneSeconds() == 0.04); - require(!host.iterate(20., true)); - require(host.sceneSeconds() == 0.04); - host.set({.glass = true, .quality = 0}); - host.request(1, [](const Frame& frame) { require(frame.scene.glass == 1); }); - require(host.iterate(0.04, true)); - require(host.sceneSeconds() == 0.08); - }); - then("capture sequences accept only bounded positive frame counts", [] { - require(captureFrameCount("1") == 1); - require(captureFrameCount("600") == 600); - for (const auto text : {"", "0", "601", "-1", "+1", "2x", "999999999999999999999"}) - require(!captureFrameCount(text)); - }); - then("single captures keep their path and sequences keep their directory", [] { - require(captureFramePath("frames/ball.png", 0, 1) == "frames/ball.png"); - require(std::filesystem::path{captureFramePath("frames/ball.png", 0, 80)} == std::filesystem::path{"frames/ball-0000.png"}); - require(std::filesystem::path{captureFramePath("frames/ball.png", 79, 80)} == std::filesystem::path{"frames/ball-0079.png"}); - }); - then("an unavailable or timed out capture preserves its diagnostic", [] { - requireThrows([] { - saveCapture(CaptureResult{std::unexpected("window did not answer")}, "unused.png"); - }, contains("window did not answer")); - }); - then("an unwritable destination fails", [] { - // Opening an existing directory as a file fails on every supported platform. - requireThrows([] { - saveCapture(CaptureResult{std::vector{1, 2, 3}}, "."); - }, contains("cannot write")); - }); - then("a successful capture writes every byte", [] { - const auto directory = std::filesystem::temp_directory_path() - / ("webfront-capture-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); - require(std::filesystem::create_directory(directory)); - struct Cleanup { - std::filesystem::path directory; - ~Cleanup() { std::filesystem::remove_all(directory); } - } cleanup{directory}; - const auto path = directory / "capture.png"; - saveCapture(CaptureResult{std::vector{1, 2, 3}}, path.string()); - std::ifstream file{path, std::ios::binary}; - std::array bytes{}; - file.read(bytes.data(), 3); - require(file.gcount() == 3); - require(bytes == std::array{1, 2, 3}); - require(file.peek() == std::char_traits::eof()); - }); +const Scenario hostLoopCapture{ + "Host loop: capture refuses unsupported modes and reports failures", + [] { + using webfront::frontend::CaptureResult; + then("capture needs a native window, including when benchmark would otherwise take precedence", [] { + validateCapture(true, true, false, false); + validateCapture(false, false, true, true); + requireThrows([] { + validateCapture(true, false, false, false); + }); + requireThrows([] { + validateCapture(true, true, true, false); + }); + requireThrows([] { + validateCapture(true, true, false, true); + }); + }); + then("a frame clock advances only for rendered frames and survives a material change", [] { + Host host{{.quality = 0}}; + require(!host.iterate(0.04, true)); + require(host.sceneSeconds() == 0.); + host.request(1, [](const Frame&) {}); + require(host.iterate(0.04, true)); + require(host.sceneSeconds() == 0.04); + require(!host.iterate(20., true)); + require(host.sceneSeconds() == 0.04); + host.set({.glass = true, .quality = 0}); + host.request(1, [](const Frame& frame) { + require(frame.scene.glass == 1); + }); + require(host.iterate(0.04, true)); + require(host.sceneSeconds() == 0.08); + }); + then("capture sequences accept only bounded positive frame counts", [] { + require(captureFrameCount("1") == 1); + require(captureFrameCount("600") == 600); + for (const auto text : {"", "0", "601", "-1", "+1", "2x", "999999999999999999999"}) + require(!captureFrameCount(text)); + }); + then("single captures keep their path and sequences keep their directory", [] { + require(captureFramePath("frames/ball.png", 0, 1) == "frames/ball.png"); + require(std::filesystem::path{captureFramePath("frames/ball.png", 0, 80)} == std::filesystem::path{"frames/ball-0000.png"}); + require(std::filesystem::path{captureFramePath("frames/ball.png", 79, 80)} == std::filesystem::path{"frames/ball-0079.png"}); + }); + then("an unavailable or timed out capture preserves its diagnostic", [] { + requireThrows( + [] { + saveCapture(CaptureResult{std::unexpected("window did not answer")}, "unused.png"); + }, + contains("window did not answer")); + }); + then("an unwritable destination fails", [] { + // Opening an existing directory as a file fails on every supported platform. + requireThrows( + [] { + saveCapture( + CaptureResult{ + std::vector{1, 2, 3} + }, + "."); + }, + contains("cannot write")); + }); + then("a successful capture writes every byte", [] { + const auto directory = std::filesystem::temp_directory_path() + / ("webfront-capture-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + require(std::filesystem::create_directory(directory)); + struct Cleanup { + std::filesystem::path directory; + ~Cleanup() { + std::filesystem::remove_all(directory); + } + } cleanup{directory}; + const auto path = directory / "capture.png"; + saveCapture( + CaptureResult{ + std::vector{1, 2, 3} + }, + path.string()); + std::ifstream file{path, std::ios::binary}; + std::array bytes{}; + file.read(bytes.data(), 3); + require(file.gcount() == 3); + require(bytes == std::array{1, 2, 3}); + require(file.peek() == std::char_traits::eof()); + }); #ifdef __linux__ - then("a buffered write failure also fails when the file is closed", [] { - requireThrows([] { - saveCapture(CaptureResult{std::vector{1, 2, 3}}, "/dev/full"); - }, contains("cannot write")); - }); + then("a buffered write failure also fails when the file is closed", [] { + requireThrows( + [] { + saveCapture( + CaptureResult{ + std::vector{1, 2, 3} + }, + "/dev/full"); + }, + contains("cannot write")); + }); #endif -}}; + }}; const Scenario hostLoopIntersections{"Host loop: rays meet the ball and the floor where geometry says", [] { - const Scene scene = sceneAt(0.F, false, 320, 240, 1); - then("the ball starts on the floor, at one side", [&] { - require(scene.ball.x == 2.6F); - require(scene.ball.y == 1.F); - require(scene.ball.z == 0.F); - }); - then("a ray aimed at its centre stops one radius before it, and a ray aimed away misses", [&] { - const Vec origin = scene.ball + Vec{0.F, 0.F, 5.F}; - require(std::fabs(hitBall(scene, origin, {0.F, 0.F, -1.F}) - 4.F) < 1e-4F); - require(hitBall(scene, origin, {0.F, 0.F, 1.F}) == 0.F); - require(hitBall(scene, origin, normalize({1.F, 0.F, -1.F})) == 0.F); - }); - then("a tangent ray grazes it and a ray leaving its surface does not meet it again", [&] { - require(hitBall(scene, scene.ball + Vec{1.0001F, 0.F, 5.F}, {0.F, 0.F, -1.F}) == 0.F); - require(hitBall(scene, scene.ball + Vec{0.999F, 0.F, 5.F}, {0.F, 0.F, -1.F}) > 4.F); - require(hitBall(scene, scene.ball + Vec{0.F, 1.F, 0.F}, {0.F, 1.F, 0.F}) == 0.F); - }); - then("only a descending ray meets the floor, at the height of its origin over its slope", [&] { - require(std::fabs(hitFloor({0.F, 3.F, 0.F}, normalize({0.F, -1.F, -1.F})) - 3.F * std::sqrt(2.F)) < 1e-4F); - require(hitFloor({0.F, 3.F, 0.F}, {0.F, 0.F, -1.F}) == 0.F); - require(hitFloor({0.F, 3.F, 0.F}, {0.F, 1.F, 0.F}) == 0.F); - }); -}}; + const Scene scene = sceneAt(0.F, false, 320, 240, 1); + then("the ball starts on the floor, at one side", [&] { + require(scene.ball.x == 2.6F); + require(scene.ball.y == 1.F); + require(scene.ball.z == 0.F); + }); + then("a ray aimed at its centre stops one radius before it, and a ray aimed away misses", [&] { + const Vec origin = scene.ball + Vec{0.F, 0.F, 5.F}; + require(std::fabs(hitBall(scene, origin, {0.F, 0.F, -1.F}) - 4.F) < 1e-4F); + require(hitBall(scene, origin, {0.F, 0.F, 1.F}) == 0.F); + require(hitBall(scene, origin, normalize({1.F, 0.F, -1.F})) == 0.F); + }); + then("a tangent ray grazes it and a ray leaving its surface does not meet it again", [&] { + require(hitBall(scene, scene.ball + Vec{1.0001F, 0.F, 5.F}, {0.F, 0.F, -1.F}) == 0.F); + require(hitBall(scene, scene.ball + Vec{0.999F, 0.F, 5.F}, {0.F, 0.F, -1.F}) > 4.F); + require(hitBall(scene, scene.ball + Vec{0.F, 1.F, 0.F}, {0.F, 1.F, 0.F}) == 0.F); + }); + then("only a descending ray meets the floor, at the height of its origin over its slope", [&] { + require(std::fabs(hitFloor({0.F, 3.F, 0.F}, normalize({0.F, -1.F, -1.F})) - 3.F * std::sqrt(2.F)) < 1e-4F); + require(hitFloor({0.F, 3.F, 0.F}, {0.F, 0.F, -1.F}) == 0.F); + require(hitFloor({0.F, 3.F, 0.F}, {0.F, 1.F, 0.F}) == 0.F); + }); + }}; const Scenario hostLoopAnimation{"Host loop: the animation is a function of time", [] { - then("the ball stays above the floor and between the sides, and bounces with a period of 1.2 s", [&] { - for (int tick = 0; tick < 400; ++tick) { - const Scene scene = sceneAt(static_cast(tick) * 0.05F, false, 320, 240, 1); - require(scene.ball.y >= 1.F); - require(scene.ball.y <= 3.1001F); - require(std::fabs(scene.ball.x) <= 2.6001F); - require(std::fabs(scene.spinCos * scene.spinCos + scene.spinSin * scene.spinSin - 1.F) < 1e-4F); - } - require(std::fabs(sceneAt(0.6F, false, 320, 240, 1).ball.y - 3.1F) < 1e-3F); - require(std::fabs(sceneAt(1.2F, false, 320, 240, 1).ball.y - 1.F) < 1e-3F); - }); - then("the same time gives the same scene, and another time another one", [&] { - const Scene a = sceneAt(2.5F, true, 640, 480, 2), b = sceneAt(2.5F, true, 640, 480, 2), c = sceneAt(2.6F, true, 640, 480, 2); - require(a.ball.x == b.ball.x); - require(a.ball.y == b.ball.y); - require(a.light.x == b.light.x); - require(a.ball.x != c.ball.x); - require(a.glass == 1); - }); -}}; + then("the ball stays above the floor and between the sides, and bounces with a period of 1.2 s", [&] { + for (int tick = 0; tick < 400; ++tick) { + const Scene scene = sceneAt(static_cast(tick) * 0.05F, false, 320, 240, 1); + require(scene.ball.y >= 1.F); + require(scene.ball.y <= 3.1001F); + require(std::fabs(scene.ball.x) <= 2.6001F); + require(std::fabs(scene.spinCos * scene.spinCos + scene.spinSin * scene.spinSin - 1.F) < 1e-4F); + } + require(std::fabs(sceneAt(0.6F, false, 320, 240, 1).ball.y - 3.1F) < 1e-3F); + require(std::fabs(sceneAt(1.2F, false, 320, 240, 1).ball.y - 1.F) < 1e-3F); + }); + then("the same time gives the same scene, and another time another one", [&] { + const Scene a = sceneAt(2.5F, true, 640, 480, 2), b = sceneAt(2.5F, true, 640, 480, 2), + c = sceneAt(2.6F, true, 640, 480, 2); + require(a.ball.x == b.ball.x); + require(a.ball.y == b.ball.y); + require(a.light.x == b.light.x); + require(a.ball.x != c.ball.x); + require(a.glass == 1); + }); + }}; const Scenario hostLoopCpuImage{"Host loop: the CPU image is deterministic and shows the scene", [] { - const Scene scene = sceneAt(0.1F, false, 320, 240, 1); // the ball is low: its reflection is in the image - const auto image = cpuImage(scene, 1); - const auto at = [&](std::pair where) { return rgbOf(image[static_cast(where.second * scene.width + where.first)]); }; - then("any number of threads computes the same pixels", [&] { - require(cpuImage(scene, 4) == image); - require(cpuImage(scene, 7) == image); - }); - then("every pixel is opaque", [&] { - for (const auto value : image) - require((value >> 24) == 0xffU); - }); - then("the top of the image is sky, bluer than it is red", [&] { - const auto top = at({160, 2}); - require(top.b > top.r + 20); - }); - then("the ball is a red and white checker", [&] { - int red = 0, white = 0; - for (int dy = -20; dy <= 20; dy += 4) - for (int dx = -20; dx <= 20; dx += 4) { - auto [x, y] = pixelSeeing(scene, scene.ball); - const auto color = at({x + dx, y + dy}); - red += color.r > 120 && color.g < 80 && color.b < 80; - white += color.r > 120 && color.g > 120 && color.b > 120; - } - require(red > 20); - require(white > 20); - }); - then("the floor is darker in the shadow of the ball than beside it", [&] { - // The point of the floor on the line from the light through the centre of the ball, and one well outside the shadow. - const float scale = scene.light.y / (scene.light.y - scene.ball.y); - const Vec shadow{scene.light.x + (scene.ball.x - scene.light.x) * scale, 0.F, scene.light.z + (scene.ball.z - scene.light.z) * scale}; - const Vec lit{shadow.x + 2.5F, 0.F, shadow.z}; - // Half a square away from the grid lines. - const auto between = [](float value) { return std::floor(value) + 0.5F; }; - const auto dark = at(pixelSeeing(scene, {between(shadow.x), 0.F, between(shadow.z)})); - const auto bright = at(pixelSeeing(scene, {between(lit.x), 0.F, between(lit.z)})); - require(dark.g + 20 < bright.g); - }); - then("the floor reflects the ball: without the ball the floor under it is another colour", [&] { - Scene away = scene; - away.ball.x += 100.F; - away.light = scene.light; - const auto empty = cpuImage(away, 1); - // The mirror image of the ball's centre is seen through the floor, one ball height below it. - auto [x, y] = pixelSeeing(scene, {scene.ball.x, -scene.ball.y, scene.ball.z}); - int differing = 0; - for (int dy = -6; dy <= 6; ++dy) - for (int dx = -6; dx <= 6; ++dx) { - const auto index = static_cast((y + dy) * scene.width + x + dx); - differing += image[index] != empty[index]; - } - require(differing > 80); - }); - then("glass changes the ball, dims the day and sends coloured beams through the scene", [&] { - Scene glassy = scene; - glassy.glass = 1; - const auto glass = cpuImage(glassy, 2); - require(cpuImage(glassy, 5) == glass); - auto [x, y] = pixelSeeing(scene, scene.ball); - int differing = 0; - for (int dy = -20; dy <= 20; dy += 2) - for (int dx = -20; dx <= 20; dx += 2) - differing += glass[static_cast((y + dy) * scene.width + x + dx)] != image[static_cast((y + dy) * scene.width + x + dx)]; - require(differing > 300); - // Nothing is green in the opaque image, and its sky is blue-grey. The beams tint the top of the image red in - // places, and the image green in others. - const auto tints = [&](const std::vector& pixels) { - int red = 0, green = 0; - for (std::size_t i = 0; i < pixels.size(); ++i) { - const auto color = rgbOf(pixels[i]); - red += i < 60U * 320U && color.r > color.b + 10; - green += color.g > color.b + 10 && color.g > color.r + 10; - } - return std::pair{red, green}; - }; - require(tints(image) == std::pair{0, 0}); - const auto note = info("red ", tints(glass).first, " green ", tints(glass).second); - require(tints(glass).first > 200); - require(tints(glass).second > 200); - }); - then("the flat colours of the opaque image pack into few runs, the beams of the glass one into more runs than pixels", [&] { - Scene glassy = scene; - glassy.glass = 1; - std::vector runs; - pack(image, runs); - require(runs.size() * 2 < image.size()); - require(unpacked(runs) == image); - const auto glass = cpuImage(glassy, 2); - pack(glass, runs); - require(runs.size() > glass.size()); - require(unpacked(runs) == glass); - }); - then("four rays per pixel smooth the edge of the ball", [&] { - Scene fine = scene; - fine.samples = 2; - const auto smooth = cpuImage(fine, 2); - require(smooth != image); - require(smooth[2 * 320 + 160] == image[2 * 320 + 160]); - }); -}}; + const Scene scene = sceneAt(0.1F, false, 320, 240, 1); // the ball is low: its reflection is in the image + const auto image = cpuImage(scene, 1); + const auto at = [&](std::pair where) { + return rgbOf(image[static_cast(where.second * scene.width + where.first)]); + }; + then("any number of threads computes the same pixels", [&] { + require(cpuImage(scene, 4) == image); + require(cpuImage(scene, 7) == image); + }); + then("every pixel is opaque", [&] { + for (const auto value : image) + require((value >> 24) == 0xffU); + }); + then("the top of the image is sky, bluer than it is red", [&] { + const auto top = at({160, 2}); + require(top.b > top.r + 20); + }); + then("the ball is a red and white checker", [&] { + int red = 0, white = 0; + for (int dy = -20; dy <= 20; dy += 4) + for (int dx = -20; dx <= 20; dx += 4) { + auto [x, y] = pixelSeeing(scene, scene.ball); + const auto color = at({x + dx, y + dy}); + red += color.r > 120 && color.g < 80 && color.b < 80; + white += color.r > 120 && color.g > 120 && color.b > 120; + } + require(red > 20); + require(white > 20); + }); + then("the floor is darker in the shadow of the ball than beside it", [&] { + // The point of the floor on the line from the light through the centre of the ball, and one well outside the shadow. + const float scale = scene.light.y / (scene.light.y - scene.ball.y); + const Vec shadow{scene.light.x + (scene.ball.x - scene.light.x) * scale, + 0.F, + scene.light.z + (scene.ball.z - scene.light.z) * scale}; + const Vec lit{shadow.x + 2.5F, 0.F, shadow.z}; + // Half a square away from the grid lines. + const auto between = [](float value) { + return std::floor(value) + 0.5F; + }; + const auto dark = at(pixelSeeing(scene, {between(shadow.x), 0.F, between(shadow.z)})); + const auto bright = at(pixelSeeing(scene, {between(lit.x), 0.F, between(lit.z)})); + require(dark.g + 20 < bright.g); + }); + then("the floor reflects the ball: without the ball the floor under it is another colour", [&] { + Scene away = scene; + away.ball.x += 100.F; + away.light = scene.light; + const auto empty = cpuImage(away, 1); + // The mirror image of the ball's centre is seen through the floor, one ball height below it. + auto [x, y] = pixelSeeing(scene, {scene.ball.x, -scene.ball.y, scene.ball.z}); + int differing = 0; + for (int dy = -6; dy <= 6; ++dy) + for (int dx = -6; dx <= 6; ++dx) { + const auto index = static_cast((y + dy) * scene.width + x + dx); + differing += image[index] != empty[index]; + } + require(differing > 80); + }); + then("glass changes the ball, dims the day and sends coloured beams through the scene", [&] { + Scene glassy = scene; + glassy.glass = 1; + const auto glass = cpuImage(glassy, 2); + require(cpuImage(glassy, 5) == glass); + auto [x, y] = pixelSeeing(scene, scene.ball); + int differing = 0; + for (int dy = -20; dy <= 20; dy += 2) + for (int dx = -20; dx <= 20; dx += 2) + differing += glass[static_cast((y + dy) * scene.width + x + dx)] + != image[static_cast((y + dy) * scene.width + x + dx)]; + require(differing > 300); + // Nothing is green in the opaque image, and its sky is blue-grey. The beams tint the top of the image red in + // places, and the image green in others. + const auto tints = [&](const std::vector& pixels) { + int red = 0, green = 0; + for (std::size_t i = 0; i < pixels.size(); ++i) { + const auto color = rgbOf(pixels[i]); + red += i < 60U * 320U && color.r > color.b + 10; + green += color.g > color.b + 10 && color.g > color.r + 10; + } + return std::pair{red, green}; + }; + require(tints(image) == std::pair{0, 0}); + const auto note = info("red ", tints(glass).first, " green ", tints(glass).second); + require(tints(glass).first > 200); + require(tints(glass).second > 200); + }); + then("the flat colours of the opaque image pack into few runs, the beams of the glass one into more runs than pixels", [&] { + Scene glassy = scene; + glassy.glass = 1; + std::vector runs; + pack(image, runs); + require(runs.size() * 2 < image.size()); + require(unpacked(runs) == image); + const auto glass = cpuImage(glassy, 2); + pack(glass, runs); + require(runs.size() > glass.size()); + require(unpacked(runs) == glass); + }); + then("four rays per pixel smooth the edge of the ball", [&] { + Scene fine = scene; + fine.samples = 2; + const auto smooth = cpuImage(fine, 2); + require(smooth != image); + require(smooth[2 * 320 + 160] == image[2 * 320 + 160]); + }); + }}; const Scenario hostLoopPack{"Host loop: runs of equal pixels pack into their length and the pixel", [] { - std::vector runs{7U}; - pack({}, runs); - require(runs.empty()); - pack({5U}, runs); - require(runs == std::vector{1U, 5U}); - pack({5U, 5U, 5U, 9U, 5U, 5U}, runs); - require(runs == std::vector{3U, 5U, 1U, 9U, 2U, 5U}); - require(unpacked(runs) == std::vector{5U, 5U, 5U, 9U, 5U, 5U}); -}}; + std::vector runs{7U}; + pack({}, runs); + require(runs.empty()); + pack({5U}, runs); + require(runs == std::vector{1U, 5U}); + pack({5U, 5U, 5U, 9U, 5U, 5U}, runs); + require(runs == std::vector{3U, 5U, 1U, 9U, 2U, 5U}); + require(unpacked(runs) == std::vector{5U, 5U, 5U, 9U, 5U, 5U}); + }}; const Scenario hostLoopSettings{"Host loop: settings are validated before they reach the loop", [] { - Host host{{}, 2}; - Consumer consumer; - then("the image has the size and rays of the chosen quality", [&] { - for (std::uint32_t quality = 0; quality < qualities.size(); ++quality) { - host.set({Engine::cpu, false, false, quality}); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.scene.width == qualities[quality].width); - require(consumer.last.scene.height == qualities[quality].height); - require(consumer.last.scene.samples == qualities[quality].samples); - require(consumer.last.pixels.size() == static_cast(qualities[quality].width * qualities[quality].height)); - require(consumer.last.settings.quality == quality); - require(consumer.last.computeMs > 0.); - require(consumer.last.copyMs == 0.); - } - }); - then("each change has a revision, which the images computed afterwards carry", [&] { - const auto first = host.set({Engine::cpu, false, false, 0}); - require(host.set({Engine::cpu, true, false, 0}) == first + 1); - requireThrows([&] { host.set({Engine::cpu, false, false, 99}); }); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.revision == first + 1); - }); - then("the opaque image comes with its runs, the glass one without", [&] { - host.set({Engine::cpu, true, false, 0}); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(unpacked(consumer.last.packed) == consumer.last.pixels); - require(consumer.last.packed.size() * 2 < consumer.last.pixels.size()); - host.set({Engine::cpu, true, true, 0}); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.packed.empty()); - require(consumer.last.pixels.size() == 320U * 240U); - }); - then("an unknown quality or engine is refused and changes nothing", [&] { - host.set({Engine::cpu, false, true, 0}); - requireThrows([&] { host.set({Engine::cpu, false, false, static_cast(qualities.size())}); }); - requireThrows([&] { host.set({static_cast(2), false, false, 0}); }); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.settings.glass); - require(consumer.last.settings.quality == 0U); - }); - then("CUDA is accepted where a device exists and refused, with its reason, where none does", [&] { - if (host.device().empty()) { - requireThrows([&] { host.set({Engine::cuda, false, false, 0}); }, contains("CUDA is unavailable")); - requireThrows([] { Host refused{{Engine::cuda, false, false, 0}}; }, contains("CUDA is unavailable")); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.settings.engine == Engine::cpu); - } else { - host.set({Engine::cuda, false, false, 0}); - host.request(1, consumer.deliver()); - require(host.iterate(0.)); - require(consumer.last.settings.engine == Engine::cuda); - } - }); -}}; + Host host{{}, 2}; + Consumer consumer; + then("the image has the size and rays of the chosen quality", [&] { + for (std::uint32_t quality = 0; quality < qualities.size(); ++quality) { + host.set({Engine::cpu, false, false, quality}); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.scene.width == qualities[quality].width); + require(consumer.last.scene.height == qualities[quality].height); + require(consumer.last.scene.samples == qualities[quality].samples); + require(consumer.last.pixels.size() + == static_cast(qualities[quality].width * qualities[quality].height)); + require(consumer.last.settings.quality == quality); + require(consumer.last.computeMs > 0.); + require(consumer.last.copyMs == 0.); + } + }); + then("each change has a revision, which the images computed afterwards carry", [&] { + const auto first = host.set({Engine::cpu, false, false, 0}); + require(host.set({Engine::cpu, true, false, 0}) == first + 1); + requireThrows([&] { + host.set({Engine::cpu, false, false, 99}); + }); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.revision == first + 1); + }); + then("the opaque image comes with its runs, the glass one without", [&] { + host.set({Engine::cpu, true, false, 0}); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(unpacked(consumer.last.packed) == consumer.last.pixels); + require(consumer.last.packed.size() * 2 < consumer.last.pixels.size()); + host.set({Engine::cpu, true, true, 0}); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.packed.empty()); + require(consumer.last.pixels.size() == 320U * 240U); + }); + then("an unknown quality or engine is refused and changes nothing", [&] { + host.set({Engine::cpu, false, true, 0}); + requireThrows([&] { + host.set({Engine::cpu, false, false, static_cast(qualities.size())}); + }); + requireThrows([&] { + host.set({static_cast(2), false, false, 0}); + }); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.settings.glass); + require(consumer.last.settings.quality == 0U); + }); + then("CUDA is accepted where a device exists and refused, with its reason, where none does", [&] { + if (host.device().empty()) { + requireThrows( + [&] { + host.set({Engine::cuda, false, false, 0}); + }, + contains("CUDA is unavailable")); + requireThrows( + [] { + Host refused{ + {Engine::cuda, false, false, 0} + }; + }, + contains("CUDA is unavailable")); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.settings.engine == Engine::cpu); + } else { + host.set({Engine::cuda, false, false, 0}); + host.request(1, consumer.deliver()); + require(host.iterate(0.)); + require(consumer.last.settings.engine == Engine::cuda); + } + }); + }}; const Scenario hostLoopPublication{"Host loop: a consumer receives one image per request, and none queues", [] { - Host host{{Engine::cpu, false, false, 0}, 2}; - Consumer first, second; - then("nothing is computed while no consumer asks, yet the scene goes on", [&] { - require(!host.iterate(0.5)); - require(!host.iterate(0.5)); - require(host.sceneSeconds() == 1.); - require(first.received == 0); - }); - then("a request is answered by exactly one image", [&] { - host.request(1, first.deliver()); - require(host.iterate(0.1)); - require(first.received == 1); - require(!host.iterate(0.1)); - require(!host.iterate(0.1)); - require(first.received == 1); - }); - then("a consumer that asks twice before the loop turns still receives one image", [&] { - const int before = first.received; - host.request(1, first.deliver()); - host.request(1, first.deliver()); - require(host.iterate(0.1)); - require(!host.iterate(0.1)); - require(first.received == before + 1); - }); - then("a duplicate after the batch was taken still receives only its original image", [&] { - // Consumer 1 is delivered first: consumer 2 has left waiting but has not begun receiving its image. - host.request(1, [&](const Frame& frame) { - first.deliver()(frame); - host.request(2, second.deliver()); - }); - host.request(2, second.deliver()); - require(host.iterate(0.1)); - require(first.received == 1); - require(second.received == 1); - require(!host.iterate(0.1)); - require(second.received == 1); - }); - then("a consumer can request its next image as soon as its delivery begins", [&] { - host.request(1, [&](const Frame& frame) { - first.deliver()(frame); - host.request(1, first.deliver()); - }); - require(host.iterate(0.1)); - require(host.iterate(0.1)); - require(first.received == 2); - require(!host.iterate(0.1)); - }); - then("a failed delivery releases the remaining in-flight consumers", [&] { - host.request(1, [](const Frame&) { throw std::runtime_error("delivery failed"); }); - host.request(2, second.deliver()); - requireThrows([&] { host.iterate(0.1); }); - host.request(2, second.deliver()); - require(host.iterate(0.1)); - require(second.received == 1); - }); - then("two consumers receive the same image, and a slow one misses images instead of queuing them", [&] { - first = {}; - host.request(1, first.deliver()); - host.request(2, second.deliver()); - require(host.iterate(0.1)); - require(first.last.sequence == second.last.sequence); - require(first.last.pixels == second.last.pixels); - // The first consumer asks for three more images; the second, slower, asks once at the end. - for (int i = 0; i < 3; ++i) { - host.request(1, first.deliver()); - require(host.iterate(0.1)); - } - host.request(2, second.deliver()); - require(host.iterate(0.1)); - require(first.received == 4); - require(second.received == 2); - require(second.last.sequence == first.last.sequence + 1); - }); - then("pause freezes the scene, not the answers", [&] { - host.set({Engine::cpu, true, false, 0}); - host.request(1, first.deliver()); - require(host.iterate(1.)); - const Frame still = first.last; - const double time = host.sceneSeconds(); - host.request(1, first.deliver()); - require(host.iterate(1.)); - require(host.sceneSeconds() == time); - require(first.last.pixels == still.pixels); - require(first.last.sequence == still.sequence + 1); - require(first.last.settings.paused); - host.set({Engine::cpu, false, false, 0}); - host.request(1, first.deliver()); - require(host.iterate(0.3)); - require(first.last.pixels != still.pixels); - }); -}}; + Host host{ + {Engine::cpu, false, false, 0}, + 2 + }; + Consumer first, second; + then("nothing is computed while no consumer asks, yet the scene goes on", [&] { + require(!host.iterate(0.5)); + require(!host.iterate(0.5)); + require(host.sceneSeconds() == 1.); + require(first.received == 0); + }); + then("a request is answered by exactly one image", [&] { + host.request(1, first.deliver()); + require(host.iterate(0.1)); + require(first.received == 1); + require(!host.iterate(0.1)); + require(!host.iterate(0.1)); + require(first.received == 1); + }); + then("a consumer that asks twice before the loop turns still receives one image", [&] { + const int before = first.received; + host.request(1, first.deliver()); + host.request(1, first.deliver()); + require(host.iterate(0.1)); + require(!host.iterate(0.1)); + require(first.received == before + 1); + }); + then("a duplicate after the batch was taken still receives only its original image", [&] { + // Consumer 1 is delivered first: consumer 2 has left waiting but has not begun receiving its image. + host.request(1, [&](const Frame& frame) { + first.deliver()(frame); + host.request(2, second.deliver()); + }); + host.request(2, second.deliver()); + require(host.iterate(0.1)); + require(first.received == 1); + require(second.received == 1); + require(!host.iterate(0.1)); + require(second.received == 1); + }); + then("a consumer can request its next image as soon as its delivery begins", [&] { + host.request(1, [&](const Frame& frame) { + first.deliver()(frame); + host.request(1, first.deliver()); + }); + require(host.iterate(0.1)); + require(host.iterate(0.1)); + require(first.received == 2); + require(!host.iterate(0.1)); + }); + then("a failed delivery releases the remaining in-flight consumers", [&] { + host.request(1, [](const Frame&) { + throw std::runtime_error("delivery failed"); + }); + host.request(2, second.deliver()); + requireThrows([&] { + host.iterate(0.1); + }); + host.request(2, second.deliver()); + require(host.iterate(0.1)); + require(second.received == 1); + }); + then("two consumers receive the same image, and a slow one misses images instead of queuing them", [&] { + first = {}; + host.request(1, first.deliver()); + host.request(2, second.deliver()); + require(host.iterate(0.1)); + require(first.last.sequence == second.last.sequence); + require(first.last.pixels == second.last.pixels); + // The first consumer asks for three more images; the second, slower, asks once at the end. + for (int i = 0; i < 3; ++i) { + host.request(1, first.deliver()); + require(host.iterate(0.1)); + } + host.request(2, second.deliver()); + require(host.iterate(0.1)); + require(first.received == 4); + require(second.received == 2); + require(second.last.sequence == first.last.sequence + 1); + }); + then("pause freezes the scene, not the answers", [&] { + host.set({Engine::cpu, true, false, 0}); + host.request(1, first.deliver()); + require(host.iterate(1.)); + const Frame still = first.last; + const double time = host.sceneSeconds(); + host.request(1, first.deliver()); + require(host.iterate(1.)); + require(host.sceneSeconds() == time); + require(first.last.pixels == still.pixels); + require(first.last.sequence == still.sequence + 1); + require(first.last.settings.paused); + host.set({Engine::cpu, false, false, 0}); + host.request(1, first.deliver()); + require(host.iterate(0.3)); + require(first.last.pixels != still.pixels); + }); + }}; const Scenario hostLoopRun{"Host loop: the loop answers from its own thread and releases its consumers when it ends", [] { - Host host{{Engine::cpu, false, false, 0}, 2}; - std::atomic received{0}; - std::thread::id deliveredOn; - const auto held = std::make_shared(0); - std::jthread loop([&](std::stop_token stopping) { host.run(stopping); }); - then("a request from another thread is answered on the loop's thread", [&] { - host.request(1, [&, held](const Frame&) { - deliveredOn = std::this_thread::get_id(); - ++received; - }); - requireEventually([&] { return received == 1; }); - require(deliveredOn == loop.get_id()); - require(deliveredOn != std::this_thread::get_id()); - }); - then("stop ends the loop, and a request that arrives afterwards is dropped with what it holds", [&] { - host.stop(); - loop.join(); - host.request(1, [&, held](const Frame&) { ++received; }); - require(!host.iterate(0.)); - require(held.use_count() == 1); - require(received <= 1); - }); -}}; + Host host{ + {Engine::cpu, false, false, 0}, + 2 + }; + std::atomic received{0}; + std::thread::id deliveredOn; + const auto held = std::make_shared(0); + std::jthread loop([&](std::stop_token stopping) { + host.run(stopping); + }); + then("a request from another thread is answered on the loop's thread", [&] { + host.request(1, [&, held](const Frame&) { + deliveredOn = std::this_thread::get_id(); + ++received; + }); + requireEventually([&] { + return received == 1; + }); + require(deliveredOn == loop.get_id()); + require(deliveredOn != std::this_thread::get_id()); + }); + then("stop ends the loop, and a request that arrives afterwards is dropped with what it holds", [&] { + host.stop(); + loop.join(); + host.request(1, [&, held](const Frame&) { + ++received; + }); + require(!host.iterate(0.)); + require(held.use_count() == 1); + require(received <= 1); + }); + }}; const Scenario hostLoopStopToken{"Host loop: the application's stop token ends the loop and drops a pending request", [] { - Host host{{Engine::cpu, true, false, 0}, 1}; - const auto held = std::make_shared(0); - std::jthread loop([&](std::stop_token stopping) { host.run(stopping); }); - loop.request_stop(); - loop.join(); - host.request(1, [held](const Frame&) {}); - require(held.use_count() == 1); -}}; + Host host{ + {Engine::cpu, true, false, 0}, + 1 + }; + const auto held = std::make_shared(0); + std::jthread loop([&](std::stop_token stopping) { + host.run(stopping); + }); + loop.request_stop(); + loop.join(); + host.request(1, [held](const Frame&) {}); + require(held.use_count() == 1); + }}; -const Scenario hostLoopCuda{"Host loop: CUDA computes the image of the CPU, within the rounding of the device", [] { - Host host{{}, 4}; - if (host.device().empty()) - skip("no CUDA renderer in this build, or no CUDA device on this machine"); - for (const auto quality : qualities) - for (const bool glass : {false, true}) - for (const float seconds : {0.F, 0.4F, 3.3F, 9.7F}) { - const auto note = info(quality.width, "x", quality.height, " samples ", quality.samples, " glass ", glass, " at ", seconds, " s"); - Frame cpu, cuda; - cpu.scene = cuda.scene = sceneAt(seconds, glass, quality.width, quality.height, quality.samples); - cuda.settings.engine = Engine::cuda; - render(cpu, host.threads()); - render(cuda, host.threads()); - require(cuda.pixels.size() == cpu.pixels.size()); - // The device contracts multiplications and additions and has its own acos and atan2: a channel may - // round the other way, and a pixel on the edge of a square or of a grid line may fall on the other side. - std::size_t rounded = 0, different = 0; - for (std::size_t i = 0; i < cpu.pixels.size(); ++i) { - const auto a = rgbOf(cpu.pixels[i]), b = rgbOf(cuda.pixels[i]); - const int gap = std::max({std::abs(a.r - b.r), std::abs(a.g - b.g), std::abs(a.b - b.b)}); - rounded += gap > 0; - different += gap > 2; +const Scenario hostLoopCuda{ + "Host loop: CUDA computes the image of the CPU, within the rounding of the device", + [] { + Host host{{}, 4}; + if (host.device().empty()) + skip("no CUDA renderer in this build, or no CUDA device on this machine"); + for (const auto quality : qualities) + for (const bool glass : {false, true}) + for (const float seconds : {0.F, 0.4F, 3.3F, 9.7F}) { + const auto note = info(quality.width, "x", quality.height, " samples ", quality.samples, " glass ", glass, " at ", seconds, " s"); + Frame cpu, cuda; + cpu.scene = cuda.scene = sceneAt(seconds, glass, quality.width, quality.height, quality.samples); + cuda.settings.engine = Engine::cuda; + render(cpu, host.threads()); + render(cuda, host.threads()); + require(cuda.pixels.size() == cpu.pixels.size()); + // The device contracts multiplications and additions and has its own acos and atan2: a channel may + // round the other way, and a pixel on the edge of a square or of a grid line may fall on the other side. + std::size_t rounded = 0, different = 0; + for (std::size_t i = 0; i < cpu.pixels.size(); ++i) { + const auto a = rgbOf(cpu.pixels[i]), b = rgbOf(cuda.pixels[i]); + const int gap = std::max({std::abs(a.r - b.r), std::abs(a.g - b.g), std::abs(a.b - b.b)}); + rounded += gap > 0; + different += gap > 2; + } + require(different * 1000 <= cpu.pixels.size()); // at most 0.1 % of the pixels + require(rounded * 10 <= cpu.pixels.size()); // at most 10 % differ at all + require(cuda.computeMs > 0.); + require(cuda.copyMs > 0.); } - require(different * 1000 <= cpu.pixels.size()); // at most 0.1 % of the pixels - require(rounded * 10 <= cpu.pixels.size()); // at most 10 % differ at all - require(cuda.computeMs > 0.); - require(cuda.copyMs > 0.); - } -}}; + }}; diff --git a/test/unit/HostTests.cpp b/test/unit/HostTests.cpp index feab811b..a72ef0c2 100644 --- a/test/unit/HostTests.cpp +++ b/test/unit/HostTests.cpp @@ -80,495 +80,595 @@ std::string text(const std::vector& bytes) { } // namespace const Scenario programReceives{"A program receives its arguments literally, without a shell", [] { - given("arguments with spaces, quotes, Unicode, shell metacharacters and an empty one", [&] { - const std::vector - arguments{"two words", "", "a;b|c&d $HOME `id` $(id) *", "\"quoted\"", "back\\slash\\", "caf\xC3\xA9 \xE2\x82\xAC", "--flag=x y"}; - auto spec = probeSpec({"args"}); - spec.arguments.insert(spec.arguments.end(), arguments.begin(), arguments.end()); - const auto result = run(spec); - then("each one arrives as one exact argument", [&] { - require(result.status == ProcessStatus::exited); - require(result.exitCode == 0); - std::string expected; - for (std::size_t index = 0; index < arguments.size(); ++index) - expected += "[" + std::to_string(index) + "]" + arguments[index] + "\n"; - require(result.standardOutput == expected); - }); - }); -}}; + given("arguments with spaces, quotes, Unicode, shell metacharacters and an empty one", [&] { + const std::vector arguments{"two words", + "", + "a;b|c&d $HOME `id` $(id) *", + "\"quoted\"", + "back\\slash\\", + "caf\xC3\xA9 \xE2\x82\xAC", + "--flag=x y"}; + auto spec = probeSpec({"args"}); + spec.arguments.insert(spec.arguments.end(), arguments.begin(), arguments.end()); + const auto result = run(spec); + then("each one arrives as one exact argument", [&] { + require(result.status == ProcessStatus::exited); + require(result.exitCode == 0); + std::string expected; + for (std::size_t index = 0; index < arguments.size(); ++index) + expected += "[" + std::to_string(index) + "]" + arguments[index] + "\n"; + require(result.standardOutput == expected); + }); + }); + }}; const Scenario everyWay{"Every way a program can end has a structured result", [] { - when("it exits with a non-zero code", [&] { - const auto result = run(probeSpec({"exit", "7"})); - then("the code is reported", [&] { - require(result.status == ProcessStatus::exited); - require(result.exitCode == 7); - }); - }); - when("it writes to both streams", [&] { - const auto result = run(probeSpec({"streams"})); - then("each stream is captured separately", [&] { - require(result.standardOutput == "to-stdout"); - require(result.standardError == "to-stderr"); - require(result.exitCode == 3); - }); - }); - when("the program does not exist", [&] { - ProcessSpec spec; - spec.program = probe.parent_path() / "no-such-program"; - const auto result = run(spec); - then("the launch failure is reported with a reason, not as an exit code", [&] { - require(result.status == ProcessStatus::launchFailed); - require(!result.error.empty()); - }); - }); - when("it outlives its timeout", [&] { - auto spec = probeSpec({"hang"}); - spec.timeout = 300ms; - const auto result = run(spec); - then("it is killed and reported as a timeout", [&] { - require(result.status == ProcessStatus::timeout); - require(result.duration < 5s); - }); - }); - when("the caller cancels it", [&] { - std::atomic cancel{false}; - std::thread canceller{[&] { - std::this_thread::sleep_for(200ms); - cancel = true; - }}; - const auto result = runProcess(probeSpec({"hang"}), cancel); - canceller.join(); - then("it is killed and reported as cancelled", [&] { - require(result.status == ProcessStatus::cancelled); - }); - }); + when("it exits with a non-zero code", [&] { + const auto result = run(probeSpec({"exit", "7"})); + then("the code is reported", [&] { + require(result.status == ProcessStatus::exited); + require(result.exitCode == 7); + }); + }); + when("it writes to both streams", [&] { + const auto result = run(probeSpec({"streams"})); + then("each stream is captured separately", [&] { + require(result.standardOutput == "to-stdout"); + require(result.standardError == "to-stderr"); + require(result.exitCode == 3); + }); + }); + when("the program does not exist", [&] { + ProcessSpec spec; + spec.program = probe.parent_path() / "no-such-program"; + const auto result = run(spec); + then("the launch failure is reported with a reason, not as an exit code", [&] { + require(result.status == ProcessStatus::launchFailed); + require(!result.error.empty()); + }); + }); + when("it outlives its timeout", [&] { + auto spec = probeSpec({"hang"}); + spec.timeout = 300ms; + const auto result = run(spec); + then("it is killed and reported as a timeout", [&] { + require(result.status == ProcessStatus::timeout); + require(result.duration < 5s); + }); + }); + when("the caller cancels it", [&] { + std::atomic cancel{false}; + std::thread canceller{[&] { + std::this_thread::sleep_for(200ms); + cancel = true; + }}; + const auto result = runProcess(probeSpec({"hang"}), cancel); + canceller.join(); + then("it is killed and reported as cancelled", [&] { + require(result.status == ProcessStatus::cancelled); + }); + }); #ifndef _WIN32 - when("a signal ends it", [&] { - const auto result = run(probeSpec({"kill-self"})); - then("the signal is reported", [&] { - require(result.status == ProcessStatus::signaled); - require(result.signal == SIGKILL); - }); - }); + when("a signal ends it", [&] { + const auto result = run(probeSpec({"kill-self"})); + then("the signal is reported", [&] { + require(result.status == ProcessStatus::signaled); + require(result.signal == SIGKILL); + }); + }); #endif -}}; + }}; const Scenario capturedOutput{"Captured output is bounded and the excess does not block the program", [] { - auto spec = probeSpec({"big", "5000000"}); - spec.maxOutputBytes = 1000; - const auto result = run(spec); - then("the program completes, with the first bytes and the truncation flag", [&] { - require(result.status == ProcessStatus::exited); - require(result.standardOutput == std::string(1000, 'x')); - require(result.outputTruncated); - require(!result.errorTruncated); - }); -}}; + auto spec = probeSpec({"big", "5000000"}); + spec.maxOutputBytes = 1000; + const auto result = run(spec); + then("the program completes, with the first bytes and the truncation flag", [&] { + require(result.status == ProcessStatus::exited); + require(result.standardOutput == std::string(1000, 'x')); + require(result.outputTruncated); + require(!result.errorTruncated); + }); + }}; const Scenario environmentExplicit{"The environment is explicit", [] { - when("it is not inherited", [&] { - auto spec = probeSpec({"env", "HOME"}); - then("the program sees nothing of the caller's environment", [&] { - require(run(spec).standardOutput == ""); - }); - spec = probeSpec({"env", "CHOSEN"}); - spec.environment["CHOSEN"] = "caf\xC3\xA9 value"; - then("only the entries the caller chose", [&] { - require(run(spec).standardOutput == "caf\xC3\xA9 value"); - }); - }); - when("it is inherited", [&] { - auto spec = probeSpec({"envcount"}); - spec.inheritEnvironment = true; - const auto inherited = std::stoi(run(spec).standardOutput); - auto bare = probeSpec({"envcount"}); - const auto minimal = std::stoi(run(bare).standardOutput); - then("the caller's variables are there", [&] { - require(inherited > minimal); - }); - }); -}}; + when("it is not inherited", [&] { + auto spec = probeSpec({"env", "HOME"}); + then("the program sees nothing of the caller's environment", [&] { + require(run(spec).standardOutput == ""); + }); + spec = probeSpec({"env", "CHOSEN"}); + spec.environment["CHOSEN"] = "caf\xC3\xA9 value"; + then("only the entries the caller chose", [&] { + require(run(spec).standardOutput == "caf\xC3\xA9 value"); + }); + }); + when("it is inherited", [&] { + auto spec = probeSpec({"envcount"}); + spec.inheritEnvironment = true; + const auto inherited = std::stoi(run(spec).standardOutput); + auto bare = probeSpec({"envcount"}); + const auto minimal = std::stoi(run(bare).standardOutput); + then("the caller's variables are there", [&] { + require(inherited > minimal); + }); + }); + }}; const Scenario programDescendants{"A program and its descendants end together", [] { - TempRoot root{"descendants"}; - std::filesystem::create_directories(root.path); - const auto marker = root.path / "alive.txt"; - when("the timeout kills a program that started a descendant", [&] { - auto spec = probeSpec({"spawn-later", marker.generic_string()}); - spec.timeout = 500ms; - const auto result = run(spec); - std::this_thread::sleep_for(3s); - then("the descendant did not survive to do its work", [&] { - require(result.status == ProcessStatus::timeout); - require(!std::filesystem::exists(marker)); - }); - }); - when("the program ends at once and leaves a descendant", [&] { - const auto result = run(probeSpec({"spawn-quick", marker.generic_string()})); - std::this_thread::sleep_for(3s); - then("the descendant is ended with it", [&] { - require(result.status == ProcessStatus::exited); - require(!std::filesystem::exists(marker)); - }); - }); -}}; + TempRoot root{"descendants"}; + std::filesystem::create_directories(root.path); + const auto marker = root.path / "alive.txt"; + when("the timeout kills a program that started a descendant", [&] { + auto spec = probeSpec({"spawn-later", marker.generic_string()}); + spec.timeout = 500ms; + const auto result = run(spec); + std::this_thread::sleep_for(3s); + then("the descendant did not survive to do its work", [&] { + require(result.status == ProcessStatus::timeout); + require(!std::filesystem::exists(marker)); + }); + }); + when("the program ends at once and leaves a descendant", [&] { + const auto result = run(probeSpec({"spawn-quick", marker.generic_string()})); + std::this_thread::sleep_for(3s); + then("the descendant is ended with it", [&] { + require(result.status == ProcessStatus::exited); + require(!std::filesystem::exists(marker)); + }); + }); + }}; const Scenario invalidRequests{"Invalid requests are refused before anything starts", [] { - requireThrows([&] { run(ProcessSpec{}); }); - auto nul = probeSpec({"args", std::string("a\0b", 3)}); - requireThrows([&] { run(nul); }); - auto timeout = probeSpec({"exit"}); - timeout.timeout = 0ms; - requireThrows([&] { run(timeout); }); - auto environment = probeSpec({"exit"}); - environment.environment["A=B"] = "x"; - requireThrows([&] { run(environment); }); -}}; + requireThrows([&] { + run(ProcessSpec{}); + }); + auto nul = probeSpec({"args", std::string("a\0b", 3)}); + requireThrows([&] { + run(nul); + }); + auto timeout = probeSpec({"exit"}); + timeout.timeout = 0ms; + requireThrows([&] { + run(timeout); + }); + auto environment = probeSpec({"exit"}); + environment.environment["A=B"] = "x"; + requireThrows([&] { + run(environment); + }); + }}; const Scenario hostConfigurationStrict{"The host configuration is strict", [] { - using webfront::testing::detail::hostConfiguration; - const auto absolute = webfront::json::quote((std::filesystem::temp_directory_path() / "x").generic_string()); - requireNothrow([&] { hostConfiguration(R"({"programs":[],"temporary":)" + absolute + "}"); }); - for (const auto* bad : {R"({"programs":["relative"],"temporary":"/tmp/x"})", - R"({"programs":[]})", - R"({"programs":[],"temporary":"relative"})", - R"({"programs":[],"temporary":"/t","shell":true})", - R"({"programs":[],"programs":[],"temporary":"/t"})"}) - requireThrows([&] { hostConfiguration(bad); }); -}}; + using webfront::testing::detail::hostConfiguration; + const auto absolute = webfront::json::quote((std::filesystem::temp_directory_path() / "x").generic_string()); + requireNothrow([&] { + hostConfiguration(R"({"programs":[],"temporary":)" + absolute + "}"); + }); + for (const auto* bad : {R"({"programs":["relative"],"temporary":"/tmp/x"})", + R"({"programs":[]})", + R"({"programs":[],"temporary":"relative"})", + R"({"programs":[],"temporary":"/t","shell":true})", + R"({"programs":[],"programs":[],"temporary":"/t"})"}) + requireThrows([&] { + hostConfiguration(bad); + }); + }}; const Scenario onlyOwner{"Only the owner's programs run, whatever the spec writes", [] { - TempRoot root{"authorization"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto request = [](const std::string& program) { - return "{\"program\":" + webfront::json::quote(program) + ",\"args\":[\"exit\",\"0\"]}"; - }; - then("the authorized program runs", [&] { - const auto id = host.runStart(request(probe.generic_string())); - require(field(waitFor(host, id), "status") == "exited"); - host.runRelease(id); - }); - then("another program, a relative name, a shell or a missing program is refused", [&] { - requireThrows([&] { (void)host.runStart(request("/bin/sh")); }, contains("not authorized")); - requireThrows([&] { (void)host.runStart(request("host_probe")); }, contains("not authorized")); - requireThrows([&] { (void)host.runStart(request("")); }, contains("not authorized")); - requireThrows([&] { (void)host.runStart(request((probe.parent_path() / "missing").generic_string())); }, contains("not authorized")); - }); - then("unknown options and out-of-range limits are refused", [&] { - const auto base = webfront::json::quote(probe.generic_string()); - requireThrows([&] { (void)host.runStart("{\"program\":" + base + ",\"shell\":true}"); }); - requireThrows([&] { (void)host.runStart("{\"program\":" + base + ",\"timeoutMs\":0}"); }); - requireThrows([&] { (void)host.runStart("{\"program\":" + base + ",\"timeoutMs\":3600001}"); }); - requireThrows([&] { (void)host.runStart("{\"program\":" + base + ",\"maxOutputBytes\":1.5}"); }); - requireThrows([&] { (void)host.runStart("{\"program\":" + base + ",\"cwd\":\"/\"}"); }); - }); -}}; + TempRoot root{"authorization"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto request = [](const std::string& program) { + return "{\"program\":" + webfront::json::quote(program) + ",\"args\":[\"exit\",\"0\"]}"; + }; + then("the authorized program runs", [&] { + const auto id = host.runStart(request(probe.generic_string())); + require(field(waitFor(host, id), "status") == "exited"); + host.runRelease(id); + }); + then("another program, a relative name, a shell or a missing program is refused", [&] { + requireThrows( + [&] { + (void)host.runStart(request("/bin/sh")); + }, + contains("not authorized")); + requireThrows( + [&] { + (void)host.runStart(request("host_probe")); + }, + contains("not authorized")); + requireThrows( + [&] { + (void)host.runStart(request("")); + }, + contains("not authorized")); + requireThrows( + [&] { + (void)host.runStart(request((probe.parent_path() / "missing").generic_string())); + }, + contains("not authorized")); + }); + then("unknown options and out-of-range limits are refused", [&] { + const auto base = webfront::json::quote(probe.generic_string()); + requireThrows([&] { + (void)host.runStart("{\"program\":" + base + ",\"shell\":true}"); + }); + requireThrows([&] { + (void)host.runStart("{\"program\":" + base + ",\"timeoutMs\":0}"); + }); + requireThrows([&] { + (void)host.runStart("{\"program\":" + base + ",\"timeoutMs\":3600001}"); + }); + requireThrows([&] { + (void)host.runStart("{\"program\":" + base + ",\"maxOutputBytes\":1.5}"); + }); + requireThrows([&] { + (void)host.runStart("{\"program\":" + base + ",\"cwd\":\"/\"}"); + }); + }); + }}; const Scenario programAuthorized{"A program authorized by no configuration is never reachable", [] { - TempRoot root{"empty-grant"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {}))}; - requireThrows([&] { (void)host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + "}"); }, contains("not authorized")); -}}; + TempRoot root{"empty-grant"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {}))}; + requireThrows( + [&] { + (void)host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + "}"); + }, + contains("not authorized")); + }}; const Scenario temporarySpaces{"Temporary spaces are private, confined and removed", [] { - TempRoot root{"spaces"}; - std::string first, second; - { - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - first = host.makeTemp(); - second = host.makeTemp(); - then("two spaces are distinct directories under the root", [&] { - require(first != second); - require(std::filesystem::is_directory(webfront::testing::detail::pathFromUtf8(first))); - require(std::filesystem::is_directory(webfront::testing::detail::pathFromUtf8(second))); - }); - then("files are written and read in chunks, including Unicode names and empty files", [&] { - const auto file = first + "/caf\xC3\xA9 espace.json"; - std::vector a(HostSession::chunkSize, 'a'), b{'b', 'c'}; - host.writeFile(file, 0, a); - host.writeFile(file, static_cast(a.size()), b); - const auto whole = host.readFile(file, 0); - require(whole.size() == HostSession::chunkSize); - require(text(host.readFile(file, static_cast(a.size()))) == "bc"); - host.writeFile(first + "/empty", 0, {}); - require(host.readFile(first + "/empty", 0).empty()); - requireThrows([&] { host.writeFile(file, 5, b); }); // A chunk must continue the file. - }); - then("paths outside the spaces are refused, however they are spelled", [&] { - requireThrows([&] { host.writeFile(root.path.generic_string() + "/loose", 0, {}); }); - requireThrows([&] { host.writeFile(first + "/../loose", 0, {}); }); - requireThrows([&] { host.writeFile(first + "/../../escape", 0, {}); }); - requireThrows([&] { host.writeFile("relative", 0, {}); }); - requireThrows([&] { (void)host.readFile((std::filesystem::temp_directory_path() / "nothing-here").generic_string(), 0); }); - requireThrows([&] { host.writeFile(first, 0, {}); }); // The space itself is not a file. - }); + TempRoot root{"spaces"}; + std::string first, second; + { + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + first = host.makeTemp(); + second = host.makeTemp(); + then("two spaces are distinct directories under the root", [&] { + require(first != second); + require(std::filesystem::is_directory(webfront::testing::detail::pathFromUtf8(first))); + require(std::filesystem::is_directory(webfront::testing::detail::pathFromUtf8(second))); + }); + then("files are written and read in chunks, including Unicode names and empty files", [&] { + const auto file = first + "/caf\xC3\xA9 espace.json"; + std::vector a(HostSession::chunkSize, 'a'), b{'b', 'c'}; + host.writeFile(file, 0, a); + host.writeFile(file, static_cast(a.size()), b); + const auto whole = host.readFile(file, 0); + require(whole.size() == HostSession::chunkSize); + require(text(host.readFile(file, static_cast(a.size()))) == "bc"); + host.writeFile(first + "/empty", 0, {}); + require(host.readFile(first + "/empty", 0).empty()); + requireThrows([&] { + host.writeFile(file, 5, b); + }); // A chunk must continue the file. + }); + then("paths outside the spaces are refused, however they are spelled", [&] { + requireThrows([&] { + host.writeFile(root.path.generic_string() + "/loose", 0, {}); + }); + requireThrows([&] { + host.writeFile(first + "/../loose", 0, {}); + }); + requireThrows([&] { + host.writeFile(first + "/../../escape", 0, {}); + }); + requireThrows([&] { + host.writeFile("relative", 0, {}); + }); + requireThrows([&] { + (void)host.readFile((std::filesystem::temp_directory_path() / "nothing-here").generic_string(), 0); + }); + requireThrows([&] { + host.writeFile(first, 0, {}); + }); // The space itself is not a file. + }); #ifndef _WIN32 - then("a link to the outside does not open a way out", [&] { - std::filesystem::create_directory_symlink(std::filesystem::temp_directory_path(), webfront::testing::detail::pathFromUtf8(first) / "out"); - requireThrows([&] { host.writeFile(first + "/out/webfront-host-escape", 0, {}); }); - require(!std::filesystem::exists(std::filesystem::temp_directory_path() / "webfront-host-escape")); - }); + then("a link to the outside does not open a way out", [&] { + std::filesystem::create_directory_symlink(std::filesystem::temp_directory_path(), + webfront::testing::detail::pathFromUtf8(first) / "out"); + requireThrows([&] { + host.writeFile(first + "/out/webfront-host-escape", 0, {}); + }); + require(!std::filesystem::exists(std::filesystem::temp_directory_path() / "webfront-host-escape")); + }); #endif - then("a program works in a space and a working directory outside is refused", [&] { - host.writeFile(first + "/in.txt", 0, {'h', 'i'}); - const auto id = host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + ",\"args\":[\"cat\"," - + webfront::json::quote(first + "/in.txt") + "],\"cwd\":" + webfront::json::quote(first) + "}"); - const auto summary = waitFor(host, id); - require(field(summary, "status") == "exited"); - require(text(host.runRead(id, 1, 0)) == "hi"); - host.runRelease(id); - requireThrows([&] { (void)host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) - + ",\"cwd\":" + webfront::json::quote(std::filesystem::temp_directory_path().generic_string()) + "}"); }); - }); - then("removing a space deletes it, and only a space of this run", [&] { - host.removeTemp(second); - require(!std::filesystem::exists(webfront::testing::detail::pathFromUtf8(second))); - requireThrows([&] { host.removeTemp(second); }); - requireThrows([&] { host.removeTemp(root.path.generic_string()); }); - }); - } - then("ending the session removes every space left", [&] { - require(!std::filesystem::exists(webfront::testing::detail::pathFromUtf8(first))); - }); -}}; + then("a program works in a space and a working directory outside is refused", [&] { + host.writeFile(first + "/in.txt", 0, {'h', 'i'}); + const auto id = host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + ",\"args\":[\"cat\"," + + webfront::json::quote(first + "/in.txt") + + "],\"cwd\":" + webfront::json::quote(first) + "}"); + const auto summary = waitFor(host, id); + require(field(summary, "status") == "exited"); + require(text(host.runRead(id, 1, 0)) == "hi"); + host.runRelease(id); + requireThrows([&] { + (void)host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + ",\"cwd\":" + + webfront::json::quote(std::filesystem::temp_directory_path().generic_string()) + "}"); + }); + }); + then("removing a space deletes it, and only a space of this run", [&] { + host.removeTemp(second); + require(!std::filesystem::exists(webfront::testing::detail::pathFromUtf8(second))); + requireThrows([&] { + host.removeTemp(second); + }); + requireThrows([&] { + host.removeTemp(root.path.generic_string()); + }); + }); + } + then("ending the session removes every space left", [&] { + require(!std::filesystem::exists(webfront::testing::detail::pathFromUtf8(first))); + }); + }}; const Scenario twoSessions{"Two sessions on one root keep separate spaces", [] { - TempRoot root{"concurrent"}; - HostSession one{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - HostSession two{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto a = one.makeTemp(); - const auto b = two.makeTemp(); - require(a != b); - requireThrows([&] { one.writeFile(b + "/x", 0, {}); }); -}}; + TempRoot root{"concurrent"}; + HostSession one{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + HostSession two{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto a = one.makeTemp(); + const auto b = two.makeTemp(); + require(a != b); + requireThrows([&] { + one.writeFile(b + "/x", 0, {}); + }); + }}; const Scenario runsBounded{"Runs are bounded, cancellable and released", [] { - TempRoot root{"runs"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto hang = "{\"program\":" + webfront::json::quote(probe.generic_string()) + ",\"args\":[\"hang\"],\"timeoutMs\":60000}"; - then("a cancelled run reports it, and its output stays readable until released", [&] { - const auto id = host.runStart(hang); - std::this_thread::sleep_for(100ms); - require(!host.runPoll(id)); - requireThrows([&] { (void)host.runRead(id, 1, 0); }); - host.runCancel(id); - require(field(waitFor(host, id), "status") == "cancelled"); - host.runRelease(id); - requireThrows([&] { (void)host.runPoll(id); }); - }); - then("too many simultaneous runs are refused", [&] { - std::vector ids; - for (std::size_t count = 0; count < HostSession::maxActiveRuns; ++count) - ids.push_back(host.runStart(hang)); - requireThrows([&] { (void)host.runStart(hang); }); - for (const auto id : ids) - host.runRelease(id); - }); - then("a session destroyed with a running program kills it", [&] { - auto owned = std::make_unique(webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))); - (void)owned->runStart(hang); - const auto begin = std::chrono::steady_clock::now(); - owned.reset(); - require(std::chrono::steady_clock::now() - begin < 10s); - }); -}}; + TempRoot root{"runs"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto hang = "{\"program\":" + webfront::json::quote(probe.generic_string()) + ",\"args\":[\"hang\"],\"timeoutMs\":60000}"; + then("a cancelled run reports it, and its output stays readable until released", [&] { + const auto id = host.runStart(hang); + std::this_thread::sleep_for(100ms); + require(!host.runPoll(id)); + requireThrows([&] { + (void)host.runRead(id, 1, 0); + }); + host.runCancel(id); + require(field(waitFor(host, id), "status") == "cancelled"); + host.runRelease(id); + requireThrows([&] { + (void)host.runPoll(id); + }); + }); + then("too many simultaneous runs are refused", [&] { + std::vector ids; + for (std::size_t count = 0; count < HostSession::maxActiveRuns; ++count) + ids.push_back(host.runStart(hang)); + requireThrows([&] { + (void)host.runStart(hang); + }); + for (const auto id : ids) + host.runRelease(id); + }); + then("a session destroyed with a running program kills it", [&] { + auto owned = std::make_unique(webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))); + (void)owned->runStart(hang); + const auto begin = std::chrono::steady_clock::now(); + owned.reset(); + require(std::chrono::steady_clock::now() - begin < 10s); + }); + }}; #ifndef _WIN32 const Scenario programStill{"A program is still bounded when the application ignores SIGCHLD", [] { - const auto previous = std::signal(SIGCHLD, SIG_IGN); - auto spec = probeSpec({"exit", "0"}); - spec.timeout = 100ms; - const auto begin = std::chrono::steady_clock::now(); - const auto result = run(spec); - std::signal(SIGCHLD, previous); - then("the call ends promptly and never reports an exit status it could not read", [&] { - require(std::chrono::steady_clock::now() - begin < 5s); - require(result.status != ProcessStatus::launchFailed); - require((result.status == ProcessStatus::exited ? result.exitCode == 0 || !result.error.empty() : true)); - }); -}}; + const auto previous = std::signal(SIGCHLD, SIG_IGN); + auto spec = probeSpec({"exit", "0"}); + spec.timeout = 100ms; + const auto begin = std::chrono::steady_clock::now(); + const auto result = run(spec); + std::signal(SIGCHLD, previous); + then("the call ends promptly and never reports an exit status it could not read", [&] { + require(std::chrono::steady_clock::now() - begin < 5s); + require(result.status != ProcessStatus::launchFailed); + require((result.status == ProcessStatus::exited ? result.exitCode == 0 || !result.error.empty() : true)); + }); + }}; const Scenario temporarySpacesClosed{"Temporary spaces are closed to other users", [] { - TempRoot root{"private"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto space = webfront::testing::detail::pathFromUtf8(host.makeTemp()); - namespace fs = std::filesystem; - for (const auto& path : {root.path, space}) - require((fs::status(path).permissions() & (fs::perms::group_all | fs::perms::others_all)) == fs::perms::none); -}}; + TempRoot root{"private"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto space = webfront::testing::detail::pathFromUtf8(host.makeTemp()); + namespace fs = std::filesystem; + for (const auto& path : {root.path, space}) + require((fs::status(path).permissions() & (fs::perms::group_all | fs::perms::others_all)) == fs::perms::none); + }}; const Scenario programCannot{"A program that cannot start through exec is reported, with a reason", [] { - ProcessSpec spec; - spec.program = probe.parent_path(); // A directory: exec fails with EACCES. - const auto result = run(spec); - require(result.status == ProcessStatus::launchFailed); - require(!result.error.empty()); -}}; + ProcessSpec spec; + spec.program = probe.parent_path(); // A directory: exec fails with EACCES. + const auto result = run(spec); + require(result.status == ProcessStatus::launchFailed); + require(!result.error.empty()); + }}; #endif #ifdef __linux__ const Scenario programDoes{"A program does not outlive an application killed without a destructor", [] { - TempRoot root{"orphan"}; - std::filesystem::create_directories(root.path); - const auto marker = root.path / "alive.txt"; - const auto child = ::fork(); - if (child == 0) { // The application: starts a long program, then is killed like a CTest deadline kills it. - auto spec = probeSpec({"write-later", marker.generic_string()}); - spec.timeout = 60s; - (void)run(spec); - ::_exit(0); - } - require(child > 0); - std::this_thread::sleep_for(500ms); - ::kill(child, SIGKILL); - ::waitpid(child, nullptr, 0); - std::this_thread::sleep_for(3s); - then("the program was ended with it", [&] { - require(!std::filesystem::exists(marker)); - }); -}}; + TempRoot root{"orphan"}; + std::filesystem::create_directories(root.path); + const auto marker = root.path / "alive.txt"; + const auto child = ::fork(); + if (child == 0) { // The application: starts a long program, then is killed like a CTest deadline kills it. + auto spec = probeSpec({"write-later", marker.generic_string()}); + spec.timeout = 60s; + (void)run(spec); + ::_exit(0); + } + require(child > 0); + std::this_thread::sleep_for(500ms); + ::kill(child, SIGKILL); + ::waitpid(child, nullptr, 0); + std::this_thread::sleep_for(3s); + then("the program was ended with it", [&] { + require(!std::filesystem::exists(marker)); + }); + }}; #endif const Scenario programKeeps{"A program that keeps its pipes full cannot hold off the deadline", [] { - for (const auto delay : {0, 1000}) { - when("the child delays its first write by " + std::to_string(delay) + " milliseconds", [&] { - auto spec = probeSpec({"flood", std::to_string(delay)}); - spec.timeout = 300ms; - spec.maxOutputBytes = 1000; - const auto begin = std::chrono::steady_clock::now(); - const auto result = run(spec); - then("the timeout is honoured and any captured output stays bounded", [&] { - require(result.status == ProcessStatus::timeout); - require(std::chrono::steady_clock::now() - begin < 5s); - // The deadline includes child startup: a busy runner may kill it before its first write. - require(result.standardOutput.size() <= spec.maxOutputBytes); - require(result.standardError.size() <= spec.maxOutputBytes); - }); - }); - } -}}; + for (const auto delay : {0, 1000}) { + when("the child delays its first write by " + std::to_string(delay) + " milliseconds", [&] { + auto spec = probeSpec({"flood", std::to_string(delay)}); + spec.timeout = 300ms; + spec.maxOutputBytes = 1000; + const auto begin = std::chrono::steady_clock::now(); + const auto result = run(spec); + then("the timeout is honoured and any captured output stays bounded", [&] { + require(result.status == ProcessStatus::timeout); + require(std::chrono::steady_clock::now() - begin < 5s); + // The deadline includes child startup: a busy runner may kill it before its first write. + require(result.standardOutput.size() <= spec.maxOutputBytes); + require(result.standardError.size() <= spec.maxOutputBytes); + }); + }); + } + }}; const Scenario finiteFlood{"A finite flood drains both pipes and truncates each captured stream", [] { - auto spec = probeSpec({"flood-finite"}); - spec.maxOutputBytes = 1000; - const auto result = run(spec); - then("both streams reach the limit and the child completes without blocking", [&] { - require(result.status == ProcessStatus::exited); - require(result.exitCode == 0); - require(result.standardOutput == std::string(1000, 'f')); - require(result.standardError == std::string(1000, 'f')); - require(result.outputTruncated); - require(result.errorTruncated); - }); -}}; + auto spec = probeSpec({"flood-finite"}); + spec.maxOutputBytes = 1000; + const auto result = run(spec); + then("both streams reach the limit and the child completes without blocking", [&] { + require(result.status == ProcessStatus::exited); + require(result.exitCode == 0); + require(result.standardOutput == std::string(1000, 'f')); + require(result.standardError == std::string(1000, 'f')); + require(result.outputTruncated); + require(result.errorTruncated); + }); + }}; const Scenario authorizedProgram{"An authorized program that is missing cannot start, and is not called unauthorized", [] { - TempRoot root{"missing-grant"}; - const auto absent = probe.parent_path() / "not-built-yet"; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {absent}))}; - const auto id = host.runStart("{\"program\":" + webfront::json::quote(absent.generic_string()) + "}"); - const auto summary = waitFor(host, id); - then("it is a launch failure with a reason", [&] { - require(field(summary, "status") == "launchFailed"); - require(!field(summary, "error").empty()); - }); - host.runRelease(id); - requireThrows([&] { (void)host.runStart("{\"program\":" + webfront::json::quote((absent.parent_path() / "other").generic_string()) + "}"); }, contains("not authorized")); -}}; + TempRoot root{"missing-grant"}; + const auto absent = probe.parent_path() / "not-built-yet"; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {absent}))}; + const auto id = host.runStart("{\"program\":" + webfront::json::quote(absent.generic_string()) + "}"); + const auto summary = waitFor(host, id); + then("it is a launch failure with a reason", [&] { + require(field(summary, "status") == "launchFailed"); + require(!field(summary, "error").empty()); + }); + host.runRelease(id); + requireThrows( + [&] { + (void)host.runStart("{\"program\":" + webfront::json::quote((absent.parent_path() / "other").generic_string()) + + "}"); + }, + contains("not authorized")); + }}; #ifndef _WIN32 const Scenario temporarySpace{"A temporary space that cannot be removed is reported and stays registered", [] { - if (::geteuid() == 0) - skip("permissions do not stop root"); - TempRoot root{"locked"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto name = host.makeTemp(); - const auto space = webfront::testing::detail::pathFromUtf8(name); - namespace fs = std::filesystem; - fs::create_directory(space / "locked"); - std::ofstream{space / "locked" / "file"} << "x"; - fs::permissions(space / "locked", fs::perms::owner_read | fs::perms::owner_exec, fs::perm_options::replace); - then("removeTemp fails instead of pretending, and a later attempt can succeed", [&] { - requireThrows([&] { host.removeTemp(name); }, contains("Cannot remove")); - require(fs::exists(space)); - fs::permissions(space / "locked", fs::perms::owner_all, fs::perm_options::replace); - requireNothrow([&] { host.removeTemp(name); }); - require(!fs::exists(space)); - }); -}}; + if (::geteuid() == 0) + skip("permissions do not stop root"); + TempRoot root{"locked"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto name = host.makeTemp(); + const auto space = webfront::testing::detail::pathFromUtf8(name); + namespace fs = std::filesystem; + fs::create_directory(space / "locked"); + std::ofstream{space / "locked" / "file"} << "x"; + fs::permissions(space / "locked", fs::perms::owner_read | fs::perms::owner_exec, fs::perm_options::replace); + then("removeTemp fails instead of pretending, and a later attempt can succeed", [&] { + requireThrows( + [&] { + host.removeTemp(name); + }, + contains("Cannot remove")); + require(fs::exists(space)); + fs::permissions(space / "locked", fs::perms::owner_all, fs::perm_options::replace); + requireNothrow([&] { + host.removeTemp(name); + }); + require(!fs::exists(space)); + }); + }}; #endif const Scenario requestProcess{"A request the process runner would refuse is refused before any run exists", [] { - TempRoot root{"early-validation"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto base = "{\"program\":" + webfront::json::quote(probe.generic_string()); - requireThrows([&] { (void)host.runStart(base + ",\"env\":{\"A=B\":\"x\"}}"); }); - requireThrows([&] { (void)host.runStart(base + ",\"env\":{\"\":\"x\"}}"); }); - requireThrows([&] { (void)host.runStart(base + ",\"args\":[\"a\\u0000b\"]}"); }); -}}; + TempRoot root{"early-validation"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto base = "{\"program\":" + webfront::json::quote(probe.generic_string()); + requireThrows([&] { + (void)host.runStart(base + ",\"env\":{\"A=B\":\"x\"}}"); + }); + requireThrows([&] { + (void)host.runStart(base + ",\"env\":{\"\":\"x\"}}"); + }); + requireThrows([&] { + (void)host.runStart(base + ",\"args\":[\"a\\u0000b\"]}"); + }); + }}; #ifndef _WIN32 const Scenario programStarts{"A program starts with default signal dispositions, whatever the application ignores", [] { - const auto pipe = std::signal(SIGPIPE, SIG_IGN); - const auto child = std::signal(SIGCHLD, SIG_IGN); - auto spec = probeSpec({"dispositions"}); - spec.timeout = 5s; - const auto result = run(spec); - std::signal(SIGPIPE, pipe); - std::signal(SIGCHLD, child); - then("neither is ignored in the program", [&] { - require(result.status == ProcessStatus::exited); - require(result.standardOutput == "default default "); - }); -}}; + const auto pipe = std::signal(SIGPIPE, SIG_IGN); + const auto child = std::signal(SIGCHLD, SIG_IGN); + auto spec = probeSpec({"dispositions"}); + spec.timeout = 5s; + const auto result = run(spec); + std::signal(SIGPIPE, pipe); + std::signal(SIGCHLD, child); + then("neither is ignored in the program", [&] { + require(result.status == ProcessStatus::exited); + require(result.standardOutput == "default default "); + }); + }}; #endif const Scenario fileLarger{"A file larger than the limit is not read", [] { - TempRoot root{"large"}; - HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; - const auto space = host.makeTemp(); - const auto file = webfront::testing::detail::pathFromUtf8(space) / "big.bin"; - std::ofstream{file, std::ios::binary} << "x"; - std::filesystem::resize_file(file, HostSession::maxFileBytes + 1); // Sparse where the system allows it. - requireThrows([&] { (void)host.readFile(space + "/big.bin", 0); }, contains("64 MiB")); - std::filesystem::resize_file(file, 10); - require(host.readFile(space + "/big.bin", 0).size() == 10); -}}; + TempRoot root{"large"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {probe}))}; + const auto space = host.makeTemp(); + const auto file = webfront::testing::detail::pathFromUtf8(space) / "big.bin"; + std::ofstream{file, std::ios::binary} << "x"; + std::filesystem::resize_file(file, HostSession::maxFileBytes + 1); // Sparse where the system allows it. + requireThrows( + [&] { + (void)host.readFile(space + "/big.bin", 0); + }, + contains("64 MiB")); + std::filesystem::resize_file(file, 10); + require(host.readFile(space + "/big.bin", 0).size() == 10); + }}; #ifndef _WIN32 const Scenario programOutput{"A program's output is captured when the application closed its standard descriptors", [] { - const auto child = ::fork(); - if (child == 0) { - ::close(0); - ::close(1); - ::close(2); - const auto result = run(probeSpec({"args", "hello"})); - ::_exit(result.status == ProcessStatus::exited && result.standardOutput == "[0]hello\n" ? 0 : 1); - } - require(child > 0); - int status = 0; - ::waitpid(child, &status, 0); - require(WIFEXITED(status)); - require(WEXITSTATUS(status) == 0); -}}; + const auto child = ::fork(); + if (child == 0) { + ::close(0); + ::close(1); + ::close(2); + const auto result = run(probeSpec({"args", "hello"})); + ::_exit(result.status == ProcessStatus::exited && result.standardOutput == "[0]hello\n" ? 0 : 1); + } + require(child > 0); + int status = 0; + ::waitpid(child, &status, 0); + require(WIFEXITED(status)); + require(WEXITSTATUS(status) == 0); + }}; #endif #ifdef __linux__ const Scenario failedLaunch{"A failed launch is reported as one when the application closed its standard descriptors", [] { - const auto child = ::fork(); - if (child == 0) { - ::close(0); - ::close(1); - ProcessSpec spec; - spec.program = probe.parent_path() / "no-such-program"; - const auto result = run(spec); - ::_exit(result.status == ProcessStatus::launchFailed && !result.error.empty() ? 0 : 1); - } - require(child > 0); - int status = 0; - ::waitpid(child, &status, 0); - require(WIFEXITED(status)); - require(WEXITSTATUS(status) == 0); -}}; + const auto child = ::fork(); + if (child == 0) { + ::close(0); + ::close(1); + ProcessSpec spec; + spec.program = probe.parent_path() / "no-such-program"; + const auto result = run(spec); + ::_exit(result.status == ProcessStatus::launchFailed && !result.error.empty() ? 0 : 1); + } + require(child > 0); + int status = 0; + ::waitpid(child, &status, 0); + require(WIFEXITED(status)); + require(WEXITSTATUS(status) == 0); + }}; #endif diff --git a/test/unit/IndexFSTests.cpp b/test/unit/IndexFSTests.cpp index bfdbdfd9..61fdffbc 100644 --- a/test/unit/IndexFSTests.cpp +++ b/test/unit/IndexFSTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -12,83 +12,87 @@ using namespace std; using namespace webfront; const Scenario indexFileSystemProvides{"IndexFileSystem provides basic files for browser support", [] { - given("An IndexFS", [&] { - using FS = fs::IndexFS; - when("Requesting index.html", [&] { - auto indexFile = FS::open("index.html"); - then("A correct HTML5 file loading WebFront.js and the fallback module is returned", [&] { - require(indexFile.has_value()); + given("An IndexFS", [&] { + using FS = fs::IndexFS; + when("Requesting index.html", [&] { + auto indexFile = FS::open("index.html"); + then("A correct HTML5 file loading WebFront.js and the fallback module is returned", [&] { + require(indexFile.has_value()); - // The readable source (js/core/fallback/index.html) is embedded raw, like WebFront.js, - // so it is never Brotli-encoded; read it in full rather than assuming it fits a - // single fixed-size buffer. - require(!indexFile->isEncoded()); - string html; - array buffer; - while (auto readSize = indexFile->read(buffer)) html.append(buffer.data(), readSize); + // The readable source (js/core/fallback/index.html) is embedded raw, like WebFront.js, + // so it is never Brotli-encoded; read it in full rather than assuming it fits a + // single fixed-size buffer. + require(!indexFile->isEncoded()); + string html; + array buffer; + while (auto readSize = indexFile->read(buffer)) + html.append(buffer.data(), readSize); - require(html.starts_with("")); - // A script element that names the source: no std::regex, whose GCC 13 header reports a false - // -Wmaybe-uninitialized when it is instantiated (#628). - const auto hasScript = [&](string_view source) { - for (auto tag = html.find("', tag); - if (end != string::npos && string_view(html).substr(tag, end - tag).find(source) != string_view::npos) return true; - } - return false; - }; - require(hasScript("src=\"WebFront.js\"")); - require(hasScript("src=\"webfront-fallback.mjs\"")); - }); - }); + require(html.starts_with("")); + // A script element that names the source: no std::regex, whose GCC 13 header reports a false + // -Wmaybe-uninitialized when it is instantiated (#628). + const auto hasScript = [&](string_view source) { + for (auto tag = html.find("', tag); + if (end != string::npos + && string_view(html).substr(tag, end - tag).find(source) != string_view::npos) + return true; + } + return false; + }; + require(hasScript("src=\"WebFront.js\"")); + require(hasScript("src=\"webfront-fallback.mjs\"")); + }); + }); - when("Requesting webfront-fallback.mjs", [&] { - auto moduleFile = FS::open("webfront-fallback.mjs"); - then("The fallback module awaiting webFront.ready is returned", [&] { - require(moduleFile.has_value()); - require(!moduleFile->isEncoded()); - require(moduleFile->getEncoding().empty()); + when("Requesting webfront-fallback.mjs", [&] { + auto moduleFile = FS::open("webfront-fallback.mjs"); + then("The fallback module awaiting webFront.ready is returned", [&] { + require(moduleFile.has_value()); + require(!moduleFile->isEncoded()); + require(moduleFile->getEncoding().empty()); - string source; - array buffer; - while (auto readSize = moduleFile->read(buffer)) source.append(buffer.data(), readSize); - require(source.find("webFront.ready") != string::npos); - }); - }); + string source; + array buffer; + while (auto readSize = moduleFile->read(buffer)) + source.append(buffer.data(), readSize); + require(source.find("webFront.ready") != string::npos); + }); + }); - when("Requesting favicon.ico", [&] { - auto faviconFile = FS::open("favicon.ico"); - then("correct data is returned", [&] { - require(faviconFile.has_value()); - array buffer; - auto readSize = faviconFile->read(span(reinterpret_cast(buffer.data()), buffer.size())); - array head, tail; - require(!faviconFile->isEncoded()); - require(faviconFile->getEncoding().empty()); - require(readSize == 766); - head = {0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x20, 0x20, 0x10, 0x00, 0x01, 0x00, 0x04, 0x00, 0xE8, 0x02}; - tail = {0X00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x07}; - require(equal(head.begin(), head.end(), buffer.begin())); - require(equal(tail.begin(), tail.end(), buffer.begin() + readSize - tail.size())); - readSize = faviconFile->read(span(reinterpret_cast(buffer.data()), buffer.size())); - require(readSize == 0); - }); - }); - when("Requesting WebFront.js", [&] { - auto webfrontJSFile = FS::open("WebFront.js"); - then("Wbefront.js V0.0.1 content should be returned", [&] { - require(webfrontJSFile.has_value()); + when("Requesting favicon.ico", [&] { + auto faviconFile = FS::open("favicon.ico"); + then("correct data is returned", [&] { + require(faviconFile.has_value()); + array buffer; + auto readSize = faviconFile->read(span(reinterpret_cast(buffer.data()), buffer.size())); + array head, tail; + require(!faviconFile->isEncoded()); + require(faviconFile->getEncoding().empty()); + require(readSize == 766); + head = {0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x20, 0x20, 0x10, 0x00, 0x01, 0x00, 0x04, 0x00, 0xE8, 0x02}; + tail = {0X00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x00, 0x00, 0x07}; + require(equal(head.begin(), head.end(), buffer.begin())); + require(equal(tail.begin(), tail.end(), buffer.begin() + readSize - tail.size())); + readSize = faviconFile->read(span(reinterpret_cast(buffer.data()), buffer.size())); + require(readSize == 0); + }); + }); + when("Requesting WebFront.js", [&] { + auto webfrontJSFile = FS::open("WebFront.js"); + then("Wbefront.js V0.0.1 content should be returned", [&] { + require(webfrontJSFile.has_value()); - // WebFront.js is embedded verbatim rather than pre-compressed: deflate streams are not - // reproducible across platforms, so the raw bytes are what the build can verify. Nothing - // downstream advertises a Content-Encoding for it (see HTTPServer::handleRequest). - require(!webfrontJSFile->isEncoded()); - require(webfrontJSFile->getEncoding().empty()); + // WebFront.js is embedded verbatim rather than pre-compressed: deflate streams are not + // reproducible across platforms, so the raw bytes are what the build can verify. Nothing + // downstream advertises a Content-Encoding for it (see HTTPServer::handleRequest). + require(!webfrontJSFile->isEncoded()); + require(webfrontJSFile->getEncoding().empty()); - array sourceHeader{}; - webfrontJSFile->read(sourceHeader); - require(sourceHeader == array{'/', '/', '/'}); - }); - }); - }); -}}; + array sourceHeader{}; + webfrontJSFile->read(sourceHeader); + require(sourceHeader == array{'/', '/', '/'}); + }); + }); + }); + }}; diff --git a/test/unit/InjectableNetworking.hpp b/test/unit/InjectableNetworking.hpp index aef2a8b6..bea7ff52 100644 --- a/test/unit/InjectableNetworking.hpp +++ b/test/unit/InjectableNetworking.hpp @@ -1,13 +1,13 @@ /// @brief Socket mock driving a WebLink from the test thread, with injectable write failures. #pragma once #include "InlineTaskScope.hpp" -#include #include #include +#include #include -#include #include +#include #include #include #include @@ -34,9 +34,8 @@ class ManualSender { std::function stop; }; using sender_concept = networking::ex::sender_t; - using completion_signatures = networking::ex::completion_signatures; + using completion_signatures = networking::ex:: + completion_signatures; explicit ManualSender(std::function start) : onStart(std::move(start)) {} @@ -46,12 +45,16 @@ class ManualSender { using StopToken = networking::ex::stop_token_of_t>; struct OnStop { Operation* operation; - void operator()() noexcept { operation->finish([](Receiver& receiver) { networking::ex::set_stopped(std::move(receiver)); }); } + void operator()() noexcept { + operation->finish([](Receiver& receiver) { + networking::ex::set_stopped(std::move(receiver)); + }); + } }; - Receiver receiver; - std::function onStart; - std::shared_ptr finished = std::make_shared(false); // outlives the operation + Receiver receiver; + std::function onStart; + std::shared_ptr finished = std::make_shared(false); // outlives the operation std::optional> stopCallback; Operation(Receiver r, std::function start) : receiver(std::move(r)), onStart(std::move(start)) {} @@ -59,24 +62,33 @@ class ManualSender { void start() noexcept { auto token = networking::ex::get_stop_token(networking::ex::get_env(receiver)); if (token.stop_requested()) { - finish([](Receiver& r) { networking::ex::set_stopped(std::move(r)); }); + finish([](Receiver& r) { + networking::ex::set_stopped(std::move(r)); + }); return; // completing may destroy this operation: touch no member afterwards } stopCallback.emplace(std::move(token), OnStop{this}); onStart({[this, done = finished](std::error_code error, std::size_t size) { - if (*done) return; + if (*done) + return; finish([&](Receiver& r) { - if (error) networking::ex::set_error(std::move(r), error); - else networking::ex::set_value(std::move(r), size); + if (error) + networking::ex::set_error(std::move(r), error); + else + networking::ex::set_value(std::move(r), size); }); }, [this, done = finished] { - if (!*done) finish([](Receiver& r) { networking::ex::set_stopped(std::move(r)); }); + if (!*done) + finish([](Receiver& r) { + networking::ex::set_stopped(std::move(r)); + }); }}); } void finish(auto signal) { - if (*finished) return; + if (*finished) + return; *finished = true; stopCallback.reset(); signal(receiver); @@ -114,19 +126,27 @@ class InjectableSocket : public networking::SocketBaseMock { } void close() {} - void shutdown(shutdown_type) { ++shutdowns; } + void shutdown(shutdown_type) { + ++shutdowns; + } /// The peer address of the next accepted connection, as the server reads it for trustLoopbackClients. static inline std::atomic peerIsLoopback{false}; struct PeerAddress { bool loopback; - bool is_loopback() const { return loopback; } + bool is_loopback() const { + return loopback; + } }; struct PeerEndpoint { bool loopback; - PeerAddress address() const { return {loopback}; } + PeerAddress address() const { + return {loopback}; + } }; - PeerEndpoint remote_endpoint(std::error_code&) const { return {peerIsLoopback.load()}; } + PeerEndpoint remote_endpoint(std::error_code&) const { + return {peerIsLoopback.load()}; + } /// The read the WebSocket is waiting for: the test completes it, or the task is stopped. static ManualSender read(networking::buffers::MutableBuffer buffer) { @@ -152,7 +172,8 @@ class InjectableSocket : public networking::SocketBaseMock { /// Stops a pending read, as the WebSocket does when it is stopped. static void reset() { - if (readCompletion.stop) std::exchange(readCompletion, {}).stop(); + if (readCompletion.stop) + std::exchange(readCompletion, {}).stop(); std::lock_guard lock(mutex); written.clear(); writeError = {}; @@ -165,7 +186,9 @@ class InjectableSocket : public networking::SocketBaseMock { } /// How many times the server shut a socket down: the end of a connection it answered. - static int shutdownCount() { return shutdowns; } + static int shutdownCount() { + return shutdowns; + } /// Everything the server wrote. static std::string writtenText() { @@ -178,9 +201,13 @@ class InjectableSocket : public networking::SocketBaseMock { std::lock_guard lock(mutex); discarding = true; } - static std::uint64_t discardedBytes() { return discarded; } + static std::uint64_t discardedBytes() { + return discarded; + } - static int readCallCount() { return readCalls; } + static int readCallCount() { + return readCalls; + } static bool hasWrittenData() { std::lock_guard lock(mutex); @@ -232,8 +259,8 @@ class InjectableSocket : public networking::SocketBaseMock { /// The write of these buffers: complete at once, or when completeDeferredWrites() runs. static ManualSender write(const auto& buffers) { - std::error_code error; - std::size_t transferred = 0; + std::error_code error; + std::size_t transferred = 0; InjectableSocket socket; for (const auto& buffer : buffers) { transferred += socket.write_some(buffer, error); @@ -244,7 +271,9 @@ class InjectableSocket : public networking::SocketBaseMock { { std::lock_guard lock(mutex); if (deferring) { - deferred.push_back([completion, error, transferred] { completion.complete(error, transferred); }); + deferred.push_back([completion, error, transferred] { + completion.complete(error, transferred); + }); return; } } @@ -260,7 +289,7 @@ class InjectableSocket : public networking::SocketBaseMock { inline static std::error_code writeError; inline static bool deferring = false; inline static std::vector> deferred; - inline static int readCalls = 0; + inline static int readCalls = 0; inline static std::atomic shutdowns{0}; inline static bool discarding = false; inline static std::atomic discarded{0}; @@ -270,8 +299,12 @@ class InjectableNetworking : public networking::NetworkingMock { public: using Socket = InjectableSocket; - static ManualSender Receive(Socket&, MutableBuffer buffer) { return InjectableSocket::read(buffer); } - static ManualSender Send(Socket&, const auto& buffers) { return InjectableSocket::write(buffers); } + static ManualSender Receive(Socket&, MutableBuffer buffer) { + return InjectableSocket::read(buffer); + } + static ManualSender Send(Socket&, const auto& buffers) { + return InjectableSocket::write(buffers); + } }; /// Mask a browser-to-server frame: by default a binary message in one frame (FIN set, opcode 2). diff --git a/test/unit/JSFunctionTests.cpp b/test/unit/JSFunctionTests.cpp index b627b36f..84b8f019 100644 --- a/test/unit/JSFunctionTests.cpp +++ b/test/unit/JSFunctionTests.cpp @@ -1,7 +1,7 @@ -#include #include #include #include +#include #include #include @@ -94,79 +94,81 @@ struct WebFrontMock { }; const Scenario jsFunctionScenario{"JsFunction", [] { - WebFrontMock webFront; - WebLinkId id{1}; - - given("A print JsFunction", [&] { - JsFunction print("print", webFront, id, 1); - std::string text{"maFunction"}; - - when("print is called with a boolean (true) parameter", [&] { - print(true); - then("encoded data should be", [&] { - require(checkType(0, msg::CodedType::smallString)); - require(checkSize8(1, 5)); - require(checkString(2, "print")); - require(checkType(7, msg::CodedType::booleanTrue)); - }); - }); - - when("print is called with a bunch of different types of parameters", [&] { - print(false, "text data", 45, text, bigText); - then("encoded data should be", [&] { - require(checkType(0, msg::CodedType::smallString)); - require(checkSize8(1, 5)); - require(checkString(2, "print")); - require(checkType(7, msg::CodedType::booleanFalse)); - require(checkType(8, msg::CodedType::smallString)); - require(checkSize8(9, 9)); - require(checkString(10, "text data")); - require(checkType(19, msg::CodedType::number)); - require(checkNumber(20, 45)); - require(checkType(28, msg::CodedType::smallString)); - require(checkSize8(29, 10)); - require(checkString(30, "maFunction")); - require(checkType(40, msg::CodedType::string)); - require(checkSize16(41, 1980)); - }); - }); - - when("print is called with a string too long for a message", [&] { - encodedBuffer.assign(1, 0xEE); - then("the call throws before anything is sent", [&] { - requireThrows([&] { print(std::string(http::defaultMaxMessageSize, 'x')); }); - require(encodedBuffer == std::vector{0xEE}); - }); - }); - - when("print is reused for numeric arrays", [&] { - vector values{1, 256, 65535}; - print(values); - - then("the array uses its typed wire representation", [&] { - require(checkType(7, msg::CodedType::arrayU16)); - require(checkSize32(8, 3)); - uint16_t first{}; - uint16_t second{}; - uint16_t third{}; - copy_n(&encodedBuffer[12], 2, reinterpret_cast(&first)); - copy_n(&encodedBuffer[14], 2, reinterpret_cast(&second)); - copy_n(&encodedBuffer[16], 2, reinterpret_cast(&third)); - require(array{first, second, third} == array{1, 256, 65535}); - }); - - when("the same function object is called again", [&] { - array next{4, 5}; - print(span{next}); - - then("message counters and payload offsets are reset", [&] { - require(checkType(7, msg::CodedType::smallArrayU8)); - require(checkSize8(8, 2)); - require(encodedBuffer[9] == 4); - require(encodedBuffer[10] == 5); - require(encodedBuffer.size() == 11); - }); - }); - }); - }); -}}; + WebFrontMock webFront; + WebLinkId id{1}; + + given("A print JsFunction", [&] { + JsFunction print("print", webFront, id, 1); + std::string text{"maFunction"}; + + when("print is called with a boolean (true) parameter", [&] { + print(true); + then("encoded data should be", [&] { + require(checkType(0, msg::CodedType::smallString)); + require(checkSize8(1, 5)); + require(checkString(2, "print")); + require(checkType(7, msg::CodedType::booleanTrue)); + }); + }); + + when("print is called with a bunch of different types of parameters", [&] { + print(false, "text data", 45, text, bigText); + then("encoded data should be", [&] { + require(checkType(0, msg::CodedType::smallString)); + require(checkSize8(1, 5)); + require(checkString(2, "print")); + require(checkType(7, msg::CodedType::booleanFalse)); + require(checkType(8, msg::CodedType::smallString)); + require(checkSize8(9, 9)); + require(checkString(10, "text data")); + require(checkType(19, msg::CodedType::number)); + require(checkNumber(20, 45)); + require(checkType(28, msg::CodedType::smallString)); + require(checkSize8(29, 10)); + require(checkString(30, "maFunction")); + require(checkType(40, msg::CodedType::string)); + require(checkSize16(41, 1980)); + }); + }); + + when("print is called with a string too long for a message", [&] { + encodedBuffer.assign(1, 0xEE); + then("the call throws before anything is sent", [&] { + requireThrows([&] { + print(std::string(http::defaultMaxMessageSize, 'x')); + }); + require(encodedBuffer == std::vector{0xEE}); + }); + }); + + when("print is reused for numeric arrays", [&] { + vector values{1, 256, 65535}; + print(values); + + then("the array uses its typed wire representation", [&] { + require(checkType(7, msg::CodedType::arrayU16)); + require(checkSize32(8, 3)); + uint16_t first{}; + uint16_t second{}; + uint16_t third{}; + copy_n(&encodedBuffer[12], 2, reinterpret_cast(&first)); + copy_n(&encodedBuffer[14], 2, reinterpret_cast(&second)); + copy_n(&encodedBuffer[16], 2, reinterpret_cast(&third)); + require(array{first, second, third} == array{1, 256, 65535}); + }); + + when("the same function object is called again", [&] { + array next{4, 5}; + print(span{next}); + + then("message counters and payload offsets are reset", [&] { + require(checkType(7, msg::CodedType::smallArrayU8)); + require(checkSize8(8, 2)); + require(encodedBuffer[9] == 4); + require(encodedBuffer[10] == 5); + require(encodedBuffer.size() == 11); + }); + }); + }); + }); + }}; diff --git a/test/unit/JasmineConsumerTests.cpp b/test/unit/JasmineConsumerTests.cpp index 5045799e..854d2d0e 100644 --- a/test/unit/JasmineConsumerTests.cpp +++ b/test/unit/JasmineConsumerTests.cpp @@ -12,21 +12,23 @@ using namespace webfront::bdd; const Scenario consumerJasmine{"Consumer Jasmine configuration is bounded and rejects ambiguous or incomplete input", [] { - using webfront::testing::detail::jasmineConfiguration; - given("a runtime, a spec and an explicit report destination", [&] { - const auto config = jasmineConfiguration(R"({"files":["jasmine.js","board.spec.js"],"report":"report.json"})"); - require(config.files == std::vector{"jasmine.js", "board.spec.js"}); - require(config.report == "report.json"); - }); - given("an invalid or ambiguous configuration", [&] { - for (const auto text : {R"({"files":["jasmine.js"],"report":"r"})", - R"({"files":["j","s"]})", - R"({"files":["j","s"],"report":"r","report":"other"})", - R"({"files":["j","s"],"report":"r","shell":true})", - "{} trailing"}) - requireThrows([&] { jasmineConfiguration(text); }); - }); -}}; + using webfront::testing::detail::jasmineConfiguration; + given("a runtime, a spec and an explicit report destination", [&] { + const auto config = jasmineConfiguration(R"({"files":["jasmine.js","board.spec.js"],"report":"report.json"})"); + require(config.files == std::vector{"jasmine.js", "board.spec.js"}); + require(config.report == "report.json"); + }); + given("an invalid or ambiguous configuration", [&] { + for (const auto text : {R"({"files":["jasmine.js"],"report":"r"})", + R"({"files":["j","s"]})", + R"({"files":["j","s"],"report":"r","report":"other"})", + R"({"files":["j","s"],"report":"r","shell":true})", + "{} trailing"}) + requireThrows([&] { + jasmineConfiguration(text); + }); + }); + }}; namespace { using webfront::testing::detail::JasmineSession; @@ -49,86 +51,118 @@ struct ReportFile { } // namespace const Scenario jasmineSession{"A Jasmine session serves its files in bounded chunks to the instrumented page only", [] { - static constexpr auto chunk = JasmineSession<>::chunkSize; - ReportFile report{"chunks"}; - given("a file that is an exact multiple of the chunk size, an empty file and a short one", [&] { - JasmineSession session{{std::string(chunk * 2, 'a'), "", "short"}, report.path}; - require(session.attach(7)); - require(session.count(7) == 3); - then("every chunk is full until an empty read ends the file", [&] { - require(session.read(7, 0, 0).size() == chunk); - require(session.read(7, 0, static_cast(chunk)).size() == chunk); - require(session.read(7, 0, static_cast(chunk * 2)).empty()); - require(session.read(7, 1, 0).empty()); - require(session.read(7, 2, 2).size() == 3); - }); - then("indexes and offsets outside the file are rejected", [&] { - for (const auto& [index, offset] : {std::pair{-1.0, 0.0}, {3.0, 0.0}, {0.5, 0.0}, {0.0, -1.0}, {0.0, 0.5}, - {0.0, static_cast(chunk * 2 + 1)}, {std::nan(""), 0.0}, {0.0, std::nan("")}, - {0.0, HUGE_VAL}}) - requireThrows([&] { (void)session.read(7, index, offset); }); - }); - then("another page cannot read, count or report", [&] { - requireThrows([&] { (void)session.count(8); }); - requireThrows([&] { (void)session.read(8, 0, 0); }); - requireThrows([&] { session.result(8, R"({"status":"passed"})"); }); - }); - }); - given("a page that was never attached", [&] { - JasmineSession session{{"x"}, report.path}; - requireThrows([&] { (void)session.count(1); }); - }); -}}; + static constexpr auto chunk = JasmineSession<>::chunkSize; + ReportFile report{"chunks"}; + given("a file that is an exact multiple of the chunk size, an empty file and a short one", [&] { + JasmineSession session{ + {std::string(chunk * 2, 'a'), "", "short"}, + report.path + }; + require(session.attach(7)); + require(session.count(7) == 3); + then("every chunk is full until an empty read ends the file", [&] { + require(session.read(7, 0, 0).size() == chunk); + require(session.read(7, 0, static_cast(chunk)).size() == chunk); + require(session.read(7, 0, static_cast(chunk * 2)).empty()); + require(session.read(7, 1, 0).empty()); + require(session.read(7, 2, 2).size() == 3); + }); + then("indexes and offsets outside the file are rejected", [&] { + for (const auto& [index, offset] : { + std::pair{ -1.0, 0.0}, + { 3.0, 0.0}, + { 0.5, 0.0}, + { 0.0, -1.0}, + { 0.0, 0.5}, + { 0.0, static_cast(chunk * 2 + 1)}, + {std::nan(""), 0.0}, + { 0.0, std::nan("")}, + { 0.0, HUGE_VAL} + }) + requireThrows([&] { + (void)session.read(7, index, offset); + }); + }); + then("another page cannot read, count or report", [&] { + requireThrows([&] { + (void)session.count(8); + }); + requireThrows([&] { + (void)session.read(8, 0, 0); + }); + requireThrows([&] { + session.result(8, R"({"status":"passed"})"); + }); + }); + }); + given("a page that was never attached", [&] { + JasmineSession session{{"x"}, report.path}; + requireThrows([&] { + (void)session.count(1); + }); + }); + }}; const Scenario reloadedPage{"A reloaded page replaces the previous one, and nothing attaches after completion", [] { - ReportFile report{"reload"}; - JasmineSession session{{"x"}, report.path}; - require(session.attach(1)); - require(session.attach(2)); - requireThrows([&] { (void)session.count(1); }); - require(session.count(2) == 1); - session.result(2, R"({"status":"passed"})"); - require(!session.attach(3)); -}}; - -const Scenario jasmineSessionValidates{"A Jasmine session validates and records exactly one result", [] { - ReportFile report{"result"}; - given("an attached page", [&] { - JasmineSession session{{"x"}, report.path}; - require(session.exitCode() == 1); - require(session.attach(1)); - then("a malformed or ambiguous result is rejected and leaves the run failed", [&] { - for (const auto text : {"", "{}", R"({"status":"ok"})", R"({"status":"passed","status":"passed"})", "[]", R"({"status":"passed"} x)"}) - requireThrows([&] { session.result(1, text); }); + ReportFile report{"reload"}; + JasmineSession session{{"x"}, report.path}; + require(session.attach(1)); + require(session.attach(2)); + requireThrows([&] { + (void)session.count(1); + }); + require(session.count(2) == 1); + session.result(2, R"({"status":"passed"})"); + require(!session.attach(3)); + }}; + +const Scenario jasmineSessionValidates{ + "A Jasmine session validates and records exactly one result", + [] { + ReportFile report{"result"}; + given("an attached page", [&] { + JasmineSession session{{"x"}, report.path}; require(session.exitCode() == 1); - require(!std::filesystem::exists(report.path)); - }); - then("a passing result is written once and a second one is refused", [&] { - session.result(1, R"({"format":1,"status":"passed","total":1})"); - require(session.exitCode() == 0); - require(report.text() == "{\"format\":1,\"status\":\"passed\",\"total\":1}\n"); - requireThrows([&] { session.result(1, R"({"status":"failed"})"); }); - require(session.exitCode() == 0); + require(session.attach(1)); + then("a malformed or ambiguous result is rejected and leaves the run failed", [&] { + for (const auto text : {"", "{}", R"({"status":"ok"})", R"({"status":"passed","status":"passed"})", "[]", R"({"status":"passed"} x)"}) + requireThrows([&] { + session.result(1, text); + }); + require(session.exitCode() == 1); + require(!std::filesystem::exists(report.path)); + }); + then("a passing result is written once and a second one is refused", [&] { + session.result(1, R"({"format":1,"status":"passed","total":1})"); + require(session.exitCode() == 0); + require(report.text() == "{\"format\":1,\"status\":\"passed\",\"total\":1}\n"); + requireThrows([&] { + session.result(1, R"({"status":"failed"})"); + }); + require(session.exitCode() == 0); + }); + then("failed and error results keep a nonzero status", [&] { + session.result(1, R"({"status":"error","error":"boom"})"); + require(session.exitCode() == 1); + }); }); - then("failed and error results keep a nonzero status", [&] { - session.result(1, R"({"status":"error","error":"boom"})"); + given("a report that cannot be written", [&] { + JasmineSession session{{"x"}, std::filesystem::temp_directory_path() / "webfront-missing-dir" / "report.json"}; + require(session.attach(1)); + requireThrows([&] { + session.result(1, R"({"status":"passed"})"); + }); require(session.exitCode() == 1); }); - }); - given("a report that cannot be written", [&] { - JasmineSession session{{"x"}, std::filesystem::temp_directory_path() / "webfront-missing-dir" / "report.json"}; - require(session.attach(1)); - requireThrows([&] { session.result(1, R"({"status":"passed"})"); }); - require(session.exitCode() == 1); - }); -}}; + }}; const Scenario injectedScript{"The injected script reads in the same chunk size the session serves and reports load errors", [] { - const auto script = webfront::testing::detail::jasmineScript(); - require(script.starts_with("const CHUNK = " + std::to_string(JasmineSession<>::chunkSize) + ";")); - require(script.find("49152", script.find("49152") + 1) == std::string::npos); // the number appears only in the CHUNK definition - require(script.find("failed to load") != std::string_view::npos); -}}; + const auto script = webfront::testing::detail::jasmineScript(); + require(script.starts_with("const CHUNK = " + std::to_string(JasmineSession<>::chunkSize) + ";")); + require(script.find("49152", script.find("49152") + 1) + == std::string::npos); // the number appears only in the CHUNK definition + require(script.find("failed to load") != std::string_view::npos); + }}; namespace { @@ -156,79 +190,101 @@ bool fileExists(const std::filesystem::path& path) { } // namespace const Scenario captureStoreScenario{"A capture store writes images only below its directory", [] { - CaptureDirectory directory{"names"}; - given("a store with a window that answers", [&] { - CaptureStore store{directory.path, fakeImage}; - then("a valid name becomes a PNG file", [&] { - require(store.screenshot("board-1_a") == 4); - require(std::filesystem::file_size(directory.path / "board-1_a.png") == 4); - }); - then("a name that could leave the directory or add an extension is refused", [&] { - for (const auto* name : {"", "../x", "a/b", "a\\b", "a.png", ".", "..", "a b", "caf\xC3\xA9", "\xE9"}) - requireThrows([&] { store.screenshot(name); }); - requireThrows([&] { store.screenshot(std::string(65, 'a')); }); - require(!std::filesystem::exists(directory.path)); - }); - }); - given("a window that cannot be captured", [&] { - CaptureStore store{directory.path, [](std::chrono::milliseconds) -> CaptureResult { - return std::unexpected("no window"); - }}; - then("the diagnostic reaches the caller and nothing is written", [&] { - requireThrows([&] { store.screenshot("x"); }, equals("Capture failed: no window")); - require(!std::filesystem::exists(directory.path / "x.png")); - }); - }); -}}; + CaptureDirectory directory{"names"}; + given("a store with a window that answers", [&] { + CaptureStore store{directory.path, fakeImage}; + then("a valid name becomes a PNG file", [&] { + require(store.screenshot("board-1_a") == 4); + require(std::filesystem::file_size(directory.path / "board-1_a.png") == 4); + }); + then("a name that could leave the directory or add an extension is refused", [&] { + for (const auto* name : {"", "../x", "a/b", "a\\b", "a.png", ".", "..", "a b", "caf\xC3\xA9", "\xE9"}) + requireThrows([&] { + store.screenshot(name); + }); + requireThrows([&] { + store.screenshot(std::string(65, 'a')); + }); + require(!std::filesystem::exists(directory.path)); + }); + }); + given("a window that cannot be captured", [&] { + CaptureStore store{directory.path, [](std::chrono::milliseconds) -> CaptureResult { + return std::unexpected("no window"); + }}; + then("the diagnostic reaches the caller and nothing is written", [&] { + requireThrows( + [&] { + store.screenshot("x"); + }, + equals("Capture failed: no window")); + require(!std::filesystem::exists(directory.path / "x.png")); + }); + }); + }}; const Scenario captureStoreRecords{"A capture store records numbered images at a bounded rate", [] { - CaptureDirectory directory{"record"}; - std::atomic calls = 0; - CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { - ++calls; - return std::vector{1, 2, 3}; - }}; - given("a recording at 20 images per second", [&] { - store.startRecording("run", 20); - then("a second recording is refused while it runs", [&] { - requireThrows([&] { store.startRecording("other", 10); }); - }); - requireEventually([&] { - return calls >= 4; - }); - const auto frames = store.stopRecording(); - then("the images are numbered from 0001 and roughly match the rate", [&] { - require(frames >= 4); - require(frames <= 12); - require(std::filesystem::exists(directory.path / "run" / "0001.png")); - require(std::filesystem::exists(directory.path / "run" / "0004.png")); - require(frames == static_cast(calls.load())); - }); - then("stopping again is an error", [&] { - requireThrows([&] { store.stopRecording(); }); - }); - }); - given("a rate outside 1 to 30 or an invalid name", [&] { - requireThrows([&] { store.startRecording("run", 0); }); - requireThrows([&] { store.startRecording("run", 31); }); - requireThrows([&] { store.startRecording("../run", 10); }); - }); -}}; + CaptureDirectory directory{"record"}; + std::atomic calls = 0; + CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { + ++calls; + return std::vector{1, 2, 3}; + }}; + given("a recording at 20 images per second", [&] { + store.startRecording("run", 20); + then("a second recording is refused while it runs", [&] { + requireThrows([&] { + store.startRecording("other", 10); + }); + }); + requireEventually([&] { + return calls >= 4; + }); + const auto frames = store.stopRecording(); + then("the images are numbered from 0001 and roughly match the rate", [&] { + require(frames >= 4); + require(frames <= 12); + require(std::filesystem::exists(directory.path / "run" / "0001.png")); + require(std::filesystem::exists(directory.path / "run" / "0004.png")); + require(frames == static_cast(calls.load())); + }); + then("stopping again is an error", [&] { + requireThrows([&] { + store.stopRecording(); + }); + }); + }); + given("a rate outside 1 to 30 or an invalid name", [&] { + requireThrows([&] { + store.startRecording("run", 0); + }); + requireThrows([&] { + store.startRecording("run", 31); + }); + requireThrows([&] { + store.startRecording("../run", 10); + }); + }); + }}; const Scenario recordingLoses{"A recording that loses its window reports the failure when it is stopped", [] { - CaptureDirectory directory{"failure"}; - std::atomic calls = 0; - CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { - if (++calls > 2) - return std::unexpected("the window is closed"); - return std::vector{1}; - }}; - store.startRecording("lost", 30); - requireEventually([&] { - return calls > 2; - }); - requireThrows([&] { store.stopRecording(); }, equals("Recording stopped: Capture failed: the window is closed")); -}}; + CaptureDirectory directory{"failure"}; + std::atomic calls = 0; + CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { + if (++calls > 2) + return std::unexpected("the window is closed"); + return std::vector{1}; + }}; + store.startRecording("lost", 30); + requireEventually([&] { + return calls > 2; + }); + requireThrows( + [&] { + store.stopRecording(); + }, + equals("Recording stopped: Capture failed: the window is closed")); + }}; namespace { template @@ -245,169 +301,195 @@ double pollUntilDone(Poll poll, std::source_location location = std::source_loca } // namespace const Scenario captureStoreTakes{"A capture store takes a screenshot without making the caller wait for the window", [] { - CaptureDirectory directory{"async"}; - std::atomic release = false; - CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { - while (!release) - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - return std::vector{1, 2, 3}; - }}; - given("a window that has not answered yet", [&] { - store.beginScreenshot("slow"); // returns at once - then("it is pending, a second one is refused, and the result arrives later", [&] { - require(!store.pollScreenshot().has_value()); - requireThrows([&] { store.beginScreenshot("other"); }); - release = true; - std::optional size; - requireEventually([&] { return (size = store.pollScreenshot()).has_value(); }); - require(size == 3); - require(std::filesystem::exists(directory.path / "slow.png")); - requireThrows([&] { store.pollScreenshot(); }); - }); - }); - given("an invalid name", [&] { - requireThrows([&] { store.beginScreenshot("../x"); }); - }); - release = true; -}}; + CaptureDirectory directory{"async"}; + std::atomic release = false; + CaptureStore store{directory.path, [&](std::chrono::milliseconds) -> CaptureResult { + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + return std::vector{1, 2, 3}; + }}; + given("a window that has not answered yet", [&] { + store.beginScreenshot("slow"); // returns at once + then("it is pending, a second one is refused, and the result arrives later", [&] { + require(!store.pollScreenshot().has_value()); + requireThrows([&] { + store.beginScreenshot("other"); + }); + release = true; + std::optional size; + requireEventually([&] { + return (size = store.pollScreenshot()).has_value(); + }); + require(size == 3); + require(std::filesystem::exists(directory.path / "slow.png")); + requireThrows([&] { + store.pollScreenshot(); + }); + }); + }); + given("an invalid name", [&] { + requireThrows([&] { + store.beginScreenshot("../x"); + }); + }); + release = true; + }}; const Scenario asynchronousScreenshot{"An asynchronous screenshot reports a capture failure when polled", [] { - CaptureDirectory directory{"asyncfail"}; - CaptureStore store{directory.path, [](std::chrono::milliseconds) -> CaptureResult { - return std::unexpected("no window"); - }}; - store.beginScreenshot("x"); - std::optional size; - requireThrows( - [&] { - [&] { - waitUntil([&] { - return (size = store.pollScreenshot()).has_value(); - }); - }(); - }, - equals("Capture failed: no window")); -}}; + CaptureDirectory directory{"asyncfail"}; + CaptureStore store{directory.path, [](std::chrono::milliseconds) -> CaptureResult { + return std::unexpected("no window"); + }}; + store.beginScreenshot("x"); + std::optional size; + requireThrows( + [&] { + [&] { + waitUntil([&] { + return (size = store.pollScreenshot()).has_value(); + }); + }(); + }, + equals("Capture failed: no window")); + }}; const Scenario recordingStops{"A recording stops on request and reports its count by polling", [] { - CaptureDirectory directory{"stop"}; - CaptureStore store{directory.path, fakeImage}; - store.startRecording("run", 30); - requireEventually([&] { - return fileExists(directory.path / "run" / "0002.png"); - }); - store.requestStop(); - std::optional frames; - requireEventually([&] { return (frames = store.pollRecording()).has_value(); }); - require(frames.has_value()); - require(*frames >= 2); - requireThrows([&] { store.requestStop(); }); - requireThrows([&] { store.pollRecording(); }); -}}; + CaptureDirectory directory{"stop"}; + CaptureStore store{directory.path, fakeImage}; + store.startRecording("run", 30); + requireEventually([&] { + return fileExists(directory.path / "run" / "0002.png"); + }); + store.requestStop(); + std::optional frames; + requireEventually([&] { + return (frames = store.pollRecording()).has_value(); + }); + require(frames.has_value()); + require(*frames >= 2); + requireThrows([&] { + store.requestStop(); + }); + requireThrows([&] { + store.pollRecording(); + }); + }}; const Scenario recordingEnds{"A recording ends by itself at the image limit and can still be collected", [] { - CaptureDirectory directory{"limit"}; - CaptureStore store{directory.path, fakeImage, 3}; - store.startRecording("run", 30); - requireEventually([&] { - return fileExists(directory.path / "run" / "0003.png"); - }); - store.requestStop(); // finished or about to: not an error - std::optional frames; - requireEventually([&] { return (frames = store.pollRecording()).has_value(); }); - require(frames == 3); - require(!std::filesystem::exists(directory.path / "run" / "0004.png")); - store.startRecording("again", 30); // the slot is free once collected - require(store.stopRecording() <= 3); -}}; + CaptureDirectory directory{"limit"}; + CaptureStore store{directory.path, fakeImage, 3}; + store.startRecording("run", 30); + requireEventually([&] { + return fileExists(directory.path / "run" / "0003.png"); + }); + store.requestStop(); // finished or about to: not an error + std::optional frames; + requireEventually([&] { + return (frames = store.pollRecording()).has_value(); + }); + require(frames == 3); + require(!std::filesystem::exists(directory.path / "run" / "0004.png")); + store.startRecording("again", 30); // the slot is free once collected + require(store.stopRecording() <= 3); + }}; const Scenario captureNobody{"A capture that nobody collects does not block the next one", [] { - CaptureDirectory directory{"uncollected"}; - CaptureStore store{directory.path, fakeImage, 2}; - given("a screenshot that finished but was never polled", [&] { - store.beginScreenshot("a"); - then("a concurrent request cannot take over its result", [&] { - requireEventually([&] { return fileExists(directory.path / "a.png"); }); - requireThrows([&] { store.beginScreenshot("b"); }); - require(pollUntilDone([&] { - const auto size = store.pollScreenshot(); - return size ? static_cast(*size) : -1.0; - }) == 4); - require(std::filesystem::exists(directory.path / "a.png")); - require(!std::filesystem::exists(directory.path / "b.png")); - }); - }); - given("a screenshot that finished but whose page was replaced", [&] { - store.beginScreenshot("a"); - then("abandon frees the slot and the next screenshot starts and can be polled", [&] { - requireEventually([&] { // abandon frees the slot as soon as the first worker has ended - store.abandon(); - try { - store.beginScreenshot("b"); - return true; - } catch (const std::logic_error&) { - return false; - } - }); - require(pollUntilDone([&] { - const auto size = store.pollScreenshot(); - return size ? static_cast(*size) : -1.0; - }) == 4); - require(std::filesystem::exists(directory.path / "b.png")); - }); - }); - given("a recording that ended by itself and was never collected", [&] { - store.startRecording("first", 30); - then("another recording starts, and the first one keeps its images", [&] { - requireEventually([&] { // the slot is free as soon as the first worker has ended - try { - store.startRecording("second", 30); - return true; - } catch (const std::logic_error&) { - return false; - } - }); - require(store.stopRecording() <= 2); - require(std::filesystem::exists(directory.path / "first" / "0002.png")); - }); - }); -}}; + CaptureDirectory directory{"uncollected"}; + CaptureStore store{directory.path, fakeImage, 2}; + given("a screenshot that finished but was never polled", [&] { + store.beginScreenshot("a"); + then("a concurrent request cannot take over its result", [&] { + requireEventually([&] { + return fileExists(directory.path / "a.png"); + }); + requireThrows([&] { + store.beginScreenshot("b"); + }); + require(pollUntilDone([&] { + const auto size = store.pollScreenshot(); + return size ? static_cast(*size) : -1.0; + }) + == 4); + require(std::filesystem::exists(directory.path / "a.png")); + require(!std::filesystem::exists(directory.path / "b.png")); + }); + }); + given("a screenshot that finished but whose page was replaced", [&] { + store.beginScreenshot("a"); + then("abandon frees the slot and the next screenshot starts and can be polled", [&] { + requireEventually([&] { // abandon frees the slot as soon as the first worker has ended + store.abandon(); + try { + store.beginScreenshot("b"); + return true; + } catch (const std::logic_error&) { + return false; + } + }); + require(pollUntilDone([&] { + const auto size = store.pollScreenshot(); + return size ? static_cast(*size) : -1.0; + }) + == 4); + require(std::filesystem::exists(directory.path / "b.png")); + }); + }); + given("a recording that ended by itself and was never collected", [&] { + store.startRecording("first", 30); + then("another recording starts, and the first one keeps its images", [&] { + requireEventually([&] { // the slot is free as soon as the first worker has ended + try { + store.startRecording("second", 30); + return true; + } catch (const std::logic_error&) { + return false; + } + }); + require(store.stopRecording() <= 2); + require(std::filesystem::exists(directory.path / "first" / "0002.png")); + }); + }); + }}; const Scenario recordingNever{"A recording never erases the images of an earlier recording of the same run", [] { - CaptureDirectory directory{"duplicate"}; - CaptureStore store{directory.path, fakeImage}; - store.startRecording("run", 30); - requireEventually([&] { - return fileExists(directory.path / "run" / "0001.png"); - }); - const auto frames = store.stopRecording(); - require(frames >= 1); - requireThrows([&] { store.startRecording("run", 30); }); - require(std::filesystem::exists(directory.path / "run" / "0001.png")); - given("images left by an earlier run in a fresh store", [&] { - CaptureStore fresh{directory.path, fakeImage}; - then("the first recording of that name replaces them", [&] { - std::ofstream{directory.path / "run" / "stale.png"} << "x"; - fresh.startRecording("run", 30); - fresh.stopRecording(); - require(!std::filesystem::exists(directory.path / "run" / "stale.png")); - }); - }); -}}; + CaptureDirectory directory{"duplicate"}; + CaptureStore store{directory.path, fakeImage}; + store.startRecording("run", 30); + requireEventually([&] { + return fileExists(directory.path / "run" / "0001.png"); + }); + const auto frames = store.stopRecording(); + require(frames >= 1); + requireThrows([&] { + store.startRecording("run", 30); + }); + require(std::filesystem::exists(directory.path / "run" / "0001.png")); + given("images left by an earlier run in a fresh store", [&] { + CaptureStore fresh{directory.path, fakeImage}; + then("the first recording of that name replaces them", [&] { + std::ofstream{directory.path / "run" / "stale.png"} << "x"; + fresh.startRecording("run", 30); + fresh.stopRecording(); + require(!std::filesystem::exists(directory.path / "run" / "stale.png")); + }); + }); + }}; const Scenario stopRequest{"A stop request belongs to its own recording", [] { - CaptureDirectory directory{"restart"}; - CaptureStore store{directory.path, fakeImage, 3}; - store.startRecording("one", 30); - store.requestStop(); - std::optional frames; - requireEventually([&] { return (frames = store.pollRecording()).has_value(); }); - store.startRecording("two", 30); // must not inherit, nor lose, the earlier stop request - requireEventually([&] { - return fileExists(directory.path / "two" / "0003.png"); - }); - require(store.stopRecording() == 3); // reached its own image limit: it was not stopped early by the first request -}}; + CaptureDirectory directory{"restart"}; + CaptureStore store{directory.path, fakeImage, 3}; + store.startRecording("one", 30); + store.requestStop(); + std::optional frames; + requireEventually([&] { + return (frames = store.pollRecording()).has_value(); + }); + store.startRecording("two", 30); // must not inherit, nor lose, the earlier stop request + requireEventually([&] { + return fileExists(directory.path / "two" / "0003.png"); + }); + require(store.stopRecording() == 3); // reached its own image limit: it was not stopped early by the first request + }}; namespace { /// State shared with a source that a detached worker may still run after the test ended: never a reference to a local. @@ -427,198 +509,228 @@ CaptureStore::Source blockedUntilReleased(std::shared_ptr gate) { } // namespace const Scenario destroyingStore{"Destroying a store does not wait for a window that never answers", [] { - CaptureDirectory directory{"closing"}; - const auto gate = std::make_shared(); - const auto started = std::chrono::steady_clock::now(); - { - CaptureStore store{directory.path, blockedUntilReleased(gate)}; - store.beginScreenshot("stuck"); - requireEventually([&] { - return gate->entered.load(); - }); - } - const auto elapsed = std::chrono::steady_clock::now() - started; - gate->release = true; // the detached worker ends alone, only touching state it owns - requireEventually([&] { - return gate->left.load(); - }); - require(elapsed < std::chrono::seconds{5}); -}}; + CaptureDirectory directory{"closing"}; + const auto gate = std::make_shared(); + const auto started = std::chrono::steady_clock::now(); + { + CaptureStore store{directory.path, blockedUntilReleased(gate)}; + store.beginScreenshot("stuck"); + requireEventually([&] { + return gate->entered.load(); + }); + } + const auto elapsed = std::chrono::steady_clock::now() - started; + gate->release = true; // the detached worker ends alone, only touching state it owns + requireEventually([&] { + return gate->left.load(); + }); + require(elapsed < std::chrono::seconds{5}); + }}; const Scenario captureCallbacks{"Capture callbacks of a Jasmine session obey the same page authority", [] { - CaptureDirectory directory{"session"}; - ReportFile report{"capture"}; - auto store = std::make_shared(directory.path, fakeImage); - JasmineSession session{{"x"}, report.path, store}; - require(session.attach(1)); - then("the instrumented page captures and another page cannot", [&] { - session.screenshotStart(1, "ok"); - require(pollUntilDone([&] { - return session.screenshotPoll(1); - }) - == 4); - requireThrows([&] { session.screenshotStart(2, "no"); }); - requireThrows([&] { (void)session.screenshotPoll(2); }); - requireThrows([&] { session.recordStart(2, "no", 10); }); - requireThrows([&] { session.recordStop(2); }); - requireThrows([&] { (void)session.recordPoll(2); }); - }); - then("a recording is stopped and collected through the session", [&] { - session.recordStart(1, "clip", 30); - requireEventually([&] { - return fileExists(directory.path / "clip" / "0002.png"); - }); - session.recordStop(1); - require(pollUntilDone([&] { - return session.recordPoll(1); - }) - >= 2); - }); - then("a page that replaces the instrumented one finds the recording slot free", [&] { - session.recordStart(1, "abandoned", 30); - require(session.attach(2)); // a reload: page 1 can no longer collect its recording - // The slot is free as soon as attach returns, with no polling for the old recording to end. - requireNothrow([&] { session.recordStart(2, "again", 30); }); - session.recordStop(2); - }); - then("a session without a directory refuses to capture", [&] { - JasmineSession bare{{"x"}, report.path}; - require(bare.attach(1)); - requireThrows([&] { bare.screenshotStart(1, "ok"); }); - }); -}}; + CaptureDirectory directory{"session"}; + ReportFile report{"capture"}; + auto store = std::make_shared(directory.path, fakeImage); + JasmineSession session{{"x"}, report.path, store}; + require(session.attach(1)); + then("the instrumented page captures and another page cannot", [&] { + session.screenshotStart(1, "ok"); + require(pollUntilDone([&] { + return session.screenshotPoll(1); + }) + == 4); + requireThrows([&] { + session.screenshotStart(2, "no"); + }); + requireThrows([&] { + (void)session.screenshotPoll(2); + }); + requireThrows([&] { + session.recordStart(2, "no", 10); + }); + requireThrows([&] { + session.recordStop(2); + }); + requireThrows([&] { + (void)session.recordPoll(2); + }); + }); + then("a recording is stopped and collected through the session", [&] { + session.recordStart(1, "clip", 30); + requireEventually([&] { + return fileExists(directory.path / "clip" / "0002.png"); + }); + session.recordStop(1); + require(pollUntilDone([&] { + return session.recordPoll(1); + }) + >= 2); + }); + then("a page that replaces the instrumented one finds the recording slot free", [&] { + session.recordStart(1, "abandoned", 30); + require(session.attach(2)); // a reload: page 1 can no longer collect its recording + // The slot is free as soon as attach returns, with no polling for the old recording to end. + requireNothrow([&] { + session.recordStart(2, "again", 30); + }); + session.recordStop(2); + }); + then("a session without a directory refuses to capture", [&] { + JasmineSession bare{{"x"}, report.path}; + require(bare.attach(1)); + requireThrows([&] { + bare.screenshotStart(1, "ok"); + }); + }); + }}; const Scenario windowRegistration{"A window registration is replaced by a later one and never removes its successor", [] { - using webfront::frontend::capturePng; - using webfront::frontend::CaptureRegistration; - const auto answer = [](std::uint8_t byte) { - return [byte](std::chrono::milliseconds) -> CaptureResult { - return std::vector{byte}; - }; - }; - require(!capturePng().has_value()); // nothing registered - { - CaptureRegistration first{answer(1)}; - require(capturePng().value() == std::vector{1}); - { - CaptureRegistration second{answer(2)}; - require(capturePng().value() == std::vector{2}); - first = CaptureRegistration{}; // the stale one goes away - require(capturePng().value() == std::vector{2}); - CaptureRegistration moved{std::move(second)}; - require(capturePng().value() == std::vector{2}); - } - require(!capturePng().has_value()); // the last owner closed the window - } -}}; + using webfront::frontend::capturePng; + using webfront::frontend::CaptureRegistration; + const auto answer = [](std::uint8_t byte) { + return [byte](std::chrono::milliseconds) -> CaptureResult { + return std::vector{byte}; + }; + }; + require(!capturePng().has_value()); // nothing registered + { + CaptureRegistration first{answer(1)}; + require(capturePng().value() == std::vector{1}); + { + CaptureRegistration second{answer(2)}; + require(capturePng().value() == std::vector{2}); + first = CaptureRegistration{}; // the stale one goes away + require(capturePng().value() == std::vector{2}); + CaptureRegistration moved{std::move(second)}; + require(capturePng().value() == std::vector{2}); + } + require(!capturePng().has_value()); // the last owner closed the window + } + }}; const Scenario jasmineConfigurationAccepts{"The Jasmine configuration accepts an optional capture directory", [] { - using webfront::testing::detail::jasmineConfiguration; - require(jasmineConfiguration(R"({"files":["j","s"],"report":"r","captures":"c"})").captures == "c"); - require(jasmineConfiguration(R"({"files":["j","s"],"report":"r"})").captures.empty()); - requireThrows([&] { jasmineConfiguration(R"({"files":["j","s"],"report":"r","captures":"a","captures":"b"})"); }); -}}; + using webfront::testing::detail::jasmineConfiguration; + require(jasmineConfiguration(R"({"files":["j","s"],"report":"r","captures":"c"})").captures == "c"); + require(jasmineConfiguration(R"({"files":["j","s"],"report":"r"})").captures.empty()); + requireThrows([&] { + jasmineConfiguration(R"({"files":["j","s"],"report":"r","captures":"a","captures":"b"})"); + }); + }}; const Scenario abandoningRecording{"Abandoning a recording frees its slot before it returns, unless the window blocks the worker", [] { - CaptureDirectory directory{"abandon"}; - given("a window that answers", [&] { - CaptureStore store{directory.path, fakeImage}; - store.startRecording("first", 30); - store.abandon(); - then("a new recording starts at once", [&] { - requireNothrow([&] { store.startRecording("second", 30); }); - requireNothrow([&] { store.stopRecording(); }); - }); - then("abandoning with nothing running is not an error", [&] { - store.abandon(); - requireNothrow([&] { store.abandon(); }); - }); - }); - given("a window that does not answer", [&] { - const auto gate = std::make_shared(); - { - CaptureStore store{directory.path, blockedUntilReleased(gate)}; - store.startRecording("blocked", 30); - requireEventually([&] { - return gate->entered.load(); - }); // The worker is inside the window's capture, not yet started. - const auto begin = std::chrono::steady_clock::now(); - store.abandon(); - then("it waits only the grace period, and the slot stays taken", [&] { - require(std::chrono::steady_clock::now() - begin < std::chrono::seconds{3}); - requireThrows([&] { store.startRecording("next", 30); }); - }); - gate->release = true; - } - requireEventually([&] { - return gate->left.load(); - }); - }); -}}; + CaptureDirectory directory{"abandon"}; + given("a window that answers", [&] { + CaptureStore store{directory.path, fakeImage}; + store.startRecording("first", 30); + store.abandon(); + then("a new recording starts at once", [&] { + requireNothrow([&] { + store.startRecording("second", 30); + }); + requireNothrow([&] { + store.stopRecording(); + }); + }); + then("abandoning with nothing running is not an error", [&] { + store.abandon(); + requireNothrow([&] { + store.abandon(); + }); + }); + }); + given("a window that does not answer", [&] { + const auto gate = std::make_shared(); + { + CaptureStore store{directory.path, blockedUntilReleased(gate)}; + store.startRecording("blocked", 30); + requireEventually([&] { + return gate->entered.load(); + }); // The worker is inside the window's capture, not yet started. + const auto begin = std::chrono::steady_clock::now(); + store.abandon(); + then("it waits only the grace period, and the slot stays taken", [&] { + require(std::chrono::steady_clock::now() - begin < std::chrono::seconds{3}); + requireThrows([&] { + store.startRecording("next", 30); + }); + }); + gate->release = true; + } + requireEventually([&] { + return gate->left.load(); + }); + }); + }}; const Scenario twoRecording{"Two recording names that differ only by case are one recording, as on a case-insensitive file system", [] { - CaptureDirectory directory{"case"}; - CaptureStore store{directory.path, fakeImage}; - store.startRecording("run", 30); - requireEventually([&] { - return fileExists(directory.path / "run" / "0002.png"); - }); - const auto frames = store.stopRecording(); - then("the second name is refused before anything is erased", [&] { - requireThrows([&] { store.startRecording("Run", 30); }); - requireThrows([&] { store.startRecording("RUN", 30); }); - require(fileExists(directory.path / "run" / "0001.png")); - require(fileExists(directory.path / "run" / "0002.png")); - require(frames >= 2); - }); - then("a different name is still accepted", [&] { - requireNothrow([&] { store.startRecording("run2", 30); }); - store.stopRecording(); - }); -}}; + CaptureDirectory directory{"case"}; + CaptureStore store{directory.path, fakeImage}; + store.startRecording("run", 30); + requireEventually([&] { + return fileExists(directory.path / "run" / "0002.png"); + }); + const auto frames = store.stopRecording(); + then("the second name is refused before anything is erased", [&] { + requireThrows([&] { + store.startRecording("Run", 30); + }); + requireThrows([&] { + store.startRecording("RUN", 30); + }); + require(fileExists(directory.path / "run" / "0001.png")); + require(fileExists(directory.path / "run" / "0002.png")); + require(frames >= 2); + }); + then("a different name is still accepted", [&] { + requireNothrow([&] { + store.startRecording("run2", 30); + }); + store.stopRecording(); + }); + }}; namespace { -struct FakeCapture { }; +struct FakeCapture {}; } // namespace const Scenario windowCloses{"A window that closes answers the captures it never got to run", [] { - using Pending = webfront::frontend::PendingCaptures; - given("a request queued for a window whose event loop will never serve it", [&] { - Pending pending; - const auto request = std::make_shared(); - pending.open(); - require(pending.track(request)); - when("the window closes", [&] { - const auto unanswered = pending.close(); - then("the request is handed back to be answered at once, not left to the capture timeout", [&] { - require(unanswered.size() == 1); - require(unanswered.front() == request); - }); - then("a request made after the closing is refused instead of queued", [&] { - require(!pending.track(std::make_shared())); - require(pending.close().empty()); - }); - }); - when("the request is answered or gives up before the window closes", [&] { - pending.untrack(request); - then("closing has nothing left to answer", [&] { - require(pending.close().empty()); - }); - }); - }); - given("a window that has not opened yet", [&] { - Pending pending; - then("no request is accepted", [&] { - require(!pending.track(std::make_shared())); - }); - }); - given("a window that is closed and then opened again", [&] { - Pending pending; - pending.open(); - static_cast(pending.close()); - pending.open(); - then("requests are accepted again", [&] { - require(pending.track(std::make_shared())); - }); - }); -}}; + using Pending = webfront::frontend::PendingCaptures; + given("a request queued for a window whose event loop will never serve it", [&] { + Pending pending; + const auto request = std::make_shared(); + pending.open(); + require(pending.track(request)); + when("the window closes", [&] { + const auto unanswered = pending.close(); + then("the request is handed back to be answered at once, not left to the capture timeout", [&] { + require(unanswered.size() == 1); + require(unanswered.front() == request); + }); + then("a request made after the closing is refused instead of queued", [&] { + require(!pending.track(std::make_shared())); + require(pending.close().empty()); + }); + }); + when("the request is answered or gives up before the window closes", [&] { + pending.untrack(request); + then("closing has nothing left to answer", [&] { + require(pending.close().empty()); + }); + }); + }); + given("a window that has not opened yet", [&] { + Pending pending; + then("no request is accepted", [&] { + require(!pending.track(std::make_shared())); + }); + }); + given("a window that is closed and then opened again", [&] { + Pending pending; + pending.open(); + static_cast(pending.close()); + pending.open(); + then("requests are accepted again", [&] { + require(pending.track(std::make_shared())); + }); + }); + }}; diff --git a/test/unit/JsFunctionSenderTests.cpp b/test/unit/JsFunctionSenderTests.cpp index 2bfa31a0..a4dfb3eb 100644 --- a/test/unit/JsFunctionSenderTests.cpp +++ b/test/unit/JsFunctionSenderTests.cpp @@ -37,7 +37,7 @@ struct SenderObserved { }; struct Receiver { using receiver_concept = ex::receiver_tag; - SenderObserved& observed; + SenderObserved& observed; ex::inplace_stop_token token; auto get_env() const noexcept { return ex::prop{ex::get_stop_token, token}; @@ -79,180 +79,183 @@ void stringReply(msg::CallId id, std::string value) { } // namespace const Scenario typedBrowser{"Typed browser senders are lazy and own their arguments", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) { }, scope}; - SenderApp app{link}; - BasicUI ui{app, 1, 1}; - ex::inplace_stop_source stop; - SenderObserved observed; - given("a sender encoded from a temporary string view", [&] { - auto sender = ui.jsFunctionSender("echo")(std::string_view(std::string("owned-argument"))); - require(!InjectableSocket::hasWrittenData()); - auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); - static_assert(!std::is_copy_constructible_v); - static_assert(!std::is_move_constructible_v); - require(!InjectableSocket::hasWrittenData()); - when("the operation starts", [&] { - ex::start(operation); - require(InjectableSocket::wrote("owned-argument")); - require(observed.completions == 0); - stringReply(1, "result"); - then("the receiver gets the decoded result once", [&] { - check(observed.value == "result"); - check(observed.completions == 1); - stop.request_stop(); - check(!observed.stopped); - }); - }); - }); - given("a void sender", [&] { - auto operation = ex::connect(ui.jsFunctionSender("finish")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - reply(1, [](auto&, auto&) { }); - then("an empty return completes successfully", [&] { - check(observed.completions == 1); - check(observed.error.empty()); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) {}, scope}; + SenderApp app{link}; + BasicUI ui{app, 1, 1}; + ex::inplace_stop_source stop; + SenderObserved observed; + given("a sender encoded from a temporary string view", [&] { + auto sender = ui.jsFunctionSender("echo")(std::string_view(std::string("owned-argument"))); + require(!InjectableSocket::hasWrittenData()); + auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); + static_assert(!std::is_copy_constructible_v); + static_assert(!std::is_move_constructible_v); + require(!InjectableSocket::hasWrittenData()); + when("the operation starts", [&] { + ex::start(operation); + require(InjectableSocket::wrote("owned-argument")); + require(observed.completions == 0); + stringReply(1, "result"); + then("the receiver gets the decoded result once", [&] { + check(observed.value == "result"); + check(observed.completions == 1); + stop.request_stop(); + check(!observed.stopped); + }); + }); + }); + given("a void sender", [&] { + auto operation = ex::connect(ui.jsFunctionSender("finish")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + reply(1, [](auto&, auto&) {}); + then("an empty return completes successfully", [&] { + check(observed.completions == 1); + check(observed.error.empty()); + }); + }); + }}; -const Scenario typedBrowserSenders{"Typed browser senders report errors without escaping the receive loop", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - auto link = std::make_unique>(InjectableSocket{}, WebLinkId{1}, [](WebLinkEvent) { }, scope); - SenderApp app{*link}; - BasicUI ui{app, 1, 1}; - SenderObserved observed; - ex::inplace_stop_source stop; - auto sender = ui.jsFunctionSender("result")(); - given("a call started before the browser responds", [&] { - auto operation = ex::connect(sender, Receiver{observed, stop.get_token()}); - ex::start(operation); - when("JavaScript throws", [&] { - reply(1, [](auto& message, auto& frame) { - const std::runtime_error error("JS failed"); - message.encodeParameter(error, frame); - frame.freeze(); +const Scenario typedBrowserSenders{ + "Typed browser senders report errors without escaping the receive loop", + [] { + InjectableSocket::reset(); + InlineTaskScope scope; + auto link = std::make_unique>(InjectableSocket{}, WebLinkId{1}, [](WebLinkEvent) {}, scope); + SenderApp app{*link}; + BasicUI ui{app, 1, 1}; + SenderObserved observed; + ex::inplace_stop_source stop; + auto sender = ui.jsFunctionSender("result")(); + given("a call started before the browser responds", [&] { + auto operation = ex::connect(sender, Receiver{observed, stop.get_token()}); + ex::start(operation); + when("JavaScript throws", [&] { + reply(1, [](auto& message, auto& frame) { + const std::runtime_error error("JS failed"); + message.encodeParameter(error, frame); + frame.freeze(); + }); + then("set_error carries its exception", [&] { + check(observed.error == "JS failed"); + }); }); - then("set_error carries its exception", [&] { - check(observed.error == "JS failed"); + when("the result is malformed", [&] { + reply(1, [](auto& message, auto&) { + message.setParametersCount(1); + }); + then("set_error carries the decoding error", [&] { + check(!observed.error.empty()); + }); }); - }); - when("the result is malformed", [&] { - reply(1, [](auto& message, auto&) { - message.setParametersCount(1); + when("the connection closes", [&] { + InjectableSocket::fail(std::make_error_code(std::errc::connection_reset)); + then("set_error reports disconnection", [&] { + check(observed.error.starts_with("Browser connection closed")); + }); }); - then("set_error carries the decoding error", [&] { - check(!observed.error.empty()); - }); - }); - when("the connection closes", [&] { - InjectableSocket::fail(std::make_error_code(std::errc::connection_reset)); - then("set_error reports disconnection", [&] { - check(observed.error.starts_with("Browser connection closed")); + when("the link is destroyed", [&] { + link.reset(); + then("the receiver is completed before destruction returns", [&] { + check(observed.error == "Browser connection closed"); + }); }); + check(observed.completions == 1); }); - when("the link is destroyed", [&] { + given("a sender whose link has already been destroyed", [&] { link.reset(); - then("the receiver is completed before destruction returns", [&] { + auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); + ex::start(operation); + then("starting it safely reports disconnection", [&] { check(observed.error == "Browser connection closed"); + check(observed.completions == 1); }); }); - check(observed.completions == 1); - }); - given("a sender whose link has already been destroyed", [&] { - link.reset(); - auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); - ex::start(operation); - then("starting it safely reports disconnection", [&] { - check(observed.error == "Browser connection closed"); - check(observed.completions == 1); - }); - }); -}}; + }}; const Scenario typedBrowserCalls{"Typed browser calls propagate receiver cancellation", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) { }, scope}; - SenderApp app{link}; - BasicUI ui{app, 1, 1}; - ex::inplace_stop_source stop; - SenderObserved observed; - given("a receiver already stopped at start", [&] { - stop.request_stop(); - auto operation = ex::connect(ui.jsFunctionSender("slow")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - then("it completes stopped without dispatching", [&] { - check(observed.stopped); - check(observed.completions == 1); - check(!InjectableSocket::hasWrittenData()); - }); - }); - given("a call awaiting its browser result", [&] { - auto operation = ex::connect(ui.jsFunctionSender("slow")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - stop.request_stop(); - then("the receiver completes stopped exactly once", [&] { - require(observed.stopped); - require(observed.completions == 1); - }); - when("the browser returns late and a different call is pending", [&] { - auto [id, future] = link.expectResult(); - require(id != 1); - stringReply(1, "late"); - check(future.wait_for(std::chrono::seconds(0)) == std::future_status::timeout); - stringReply(id, "next"); - then("only the matching call completes", [&] { - check(future.get() == "next"); - check(observed.completions == 1); - }); - }); - }); - given("an operation destroyed by its own completion", [&] { - auto sender = ui.jsFunctionSender("slow")(); - using Operation = ex::connect_result_t; - auto operation = std::unique_ptr(new Operation(ex::connect(std::move(sender), Receiver{observed, stop.get_token()}))); - observed.onComplete = [&] { - operation.reset(); - }; - ex::start(*operation); - stop.request_stop(); - then("cancellation safely releases the operation inline", [&] { - check(!operation); - check(observed.stopped); - check(observed.completions == 1); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) {}, scope}; + SenderApp app{link}; + BasicUI ui{app, 1, 1}; + ex::inplace_stop_source stop; + SenderObserved observed; + given("a receiver already stopped at start", [&] { + stop.request_stop(); + auto operation = ex::connect(ui.jsFunctionSender("slow")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + then("it completes stopped without dispatching", [&] { + check(observed.stopped); + check(observed.completions == 1); + check(!InjectableSocket::hasWrittenData()); + }); + }); + given("a call awaiting its browser result", [&] { + auto operation = ex::connect(ui.jsFunctionSender("slow")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + stop.request_stop(); + then("the receiver completes stopped exactly once", [&] { + require(observed.stopped); + require(observed.completions == 1); + }); + when("the browser returns late and a different call is pending", [&] { + auto [id, future] = link.expectResult(); + require(id != 1); + stringReply(1, "late"); + check(future.wait_for(std::chrono::seconds(0)) == std::future_status::timeout); + stringReply(id, "next"); + then("only the matching call completes", [&] { + check(future.get() == "next"); + check(observed.completions == 1); + }); + }); + }); + given("an operation destroyed by its own completion", [&] { + auto sender = ui.jsFunctionSender("slow")(); + using Operation = ex::connect_result_t; + auto operation = std::unique_ptr( + new Operation(ex::connect(std::move(sender), Receiver{observed, stop.get_token()}))); + observed.onComplete = [&] { + operation.reset(); + }; + ex::start(*operation); + stop.request_stop(); + then("cancellation safely releases the operation inline", [&] { + check(!operation); + check(observed.stopped); + check(observed.completions == 1); + }); + }); + }}; const Scenario browserResult{"Browser result and cancellation can race", [] { - given("a dispatched call with a stoppable receiver", [&] { - when("stop and a result arrive on different threads", [&] { - then("exactly one terminal completion wins on repeated attempts", [&] { - for (int iteration = 0; iteration != 40; ++iteration) { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) { }, scope}; - SenderApp app{link}; - BasicUI ui{app, 1, 1}; - ex::inplace_stop_source stop; - SenderObserved observed; - auto operation = ex::connect(ui.jsFunctionSender("race")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - std::thread stopping([&] { - stop.request_stop(); - }); - stringReply(1, "returned"); - stopping.join(); - check(observed.completions == 1); - check((observed.stopped || observed.value == "returned")); - } - }); - }); - }); -}}; + given("a dispatched call with a stoppable receiver", [&] { + when("stop and a result arrive on different threads", [&] { + then("exactly one terminal completion wins on repeated attempts", [&] { + for (int iteration = 0; iteration != 40; ++iteration) { + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) {}, scope}; + SenderApp app{link}; + BasicUI ui{app, 1, 1}; + ex::inplace_stop_source stop; + SenderObserved observed; + auto operation = ex::connect(ui.jsFunctionSender("race")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + std::thread stopping([&] { + stop.request_stop(); + }); + stringReply(1, "returned"); + stopping.join(); + check(observed.completions == 1); + check((observed.stopped || observed.value == "returned")); + } + }); + }); + }); + }}; namespace { networking::Task awaitBrowser(BasicUI ui, SenderObserved& observed, std::shared_ptr lifetime) { @@ -262,219 +265,227 @@ networking::Task awaitBrowser(BasicUI ui, SenderObserved& observed, s } } // namespace const Scenario typedBrowserSendersCan{"Typed browser senders can be awaited in a tracked task", [] { - InjectableSocket::reset(); - InlineTaskScope transport; - WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) { }, transport}; - SenderApp app{link}; - SenderObserved observed; - InlineTaskScope calls; - given("a coroutine awaiting a browser sender in its own scope", [&] { - auto lifetime = std::make_shared(42); - std::weak_ptr frame = lifetime; - networking::Spawn(calls, ex::inline_scheduler{}, awaitBrowser(BasicUI{app, 1, 1}, observed, std::move(lifetime))); - require(!frame.expired()); - when("the browser replies", [&] { - stringReply(1, "awaited result"); - then("co_await resumes with its typed value", [&] { - check(observed.value == "awaited result"); - check(observed.completions == 1); - check(frame.expired()); - }); - }); - when("the enclosing scope requests stop while the transport remains active", [&] { - calls.requestStop(); - then("the pending coroutine unwinds before a late reply arrives", [&] { - check(frame.expired()); - stringReply(1, "late"); - check(observed.completions == 0); - check(observed.value.empty()); - }); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope transport; + WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) {}, transport}; + SenderApp app{link}; + SenderObserved observed; + InlineTaskScope calls; + given("a coroutine awaiting a browser sender in its own scope", [&] { + auto lifetime = std::make_shared(42); + std::weak_ptr frame = lifetime; + networking::Spawn(calls, + ex::inline_scheduler{}, + awaitBrowser(BasicUI{app, 1, 1}, observed, std::move(lifetime))); + require(!frame.expired()); + when("the browser replies", [&] { + stringReply(1, "awaited result"); + then("co_await resumes with its typed value", [&] { + check(observed.value == "awaited result"); + check(observed.completions == 1); + check(frame.expired()); + }); + }); + when("the enclosing scope requests stop while the transport remains active", [&] { + calls.requestStop(); + then("the pending coroutine unwinds before a late reply arrives", [&] { + check(frame.expired()); + stringReply(1, "late"); + check(observed.completions == 0); + check(observed.value.empty()); + }); + }); + }); + }}; const Scenario cancelledCorrelation{"Cancelled correlation IDs cannot be reused before a late reply", [] { - given("a registry with one cancelled call", [&] { - webfront::detail::PendingCalls calls; - auto retained = std::make_shared(42); - std::weak_ptr released = retained; - const auto cancelled = calls.add({[retained](const auto&) { }, [retained](auto) { }}); - retained.reset(); - calls.cancel(cancelled); - check(released.expired()); - when("the correlation counter wraps", [&] { - for (std::size_t i = 1; i < std::numeric_limits::max(); ++i) { - const auto id = calls.add({[](const auto&) { }, [](auto) { }}); - require(id != cancelled); - msg::FunctionReturn result; - result.setCallId(id); - require(calls.complete(result)); - } - const auto next = calls.add({[](const auto&) { }, [](auto) { }}); - then("the reserved ID is skipped until its response is consumed", [&] { - check(next != cancelled); - msg::FunctionReturn late; - late.setCallId(cancelled); - check(calls.complete(late)); - }); - }); - }); -}}; + given("a registry with one cancelled call", [&] { + webfront::detail::PendingCalls calls; + auto retained = std::make_shared(42); + std::weak_ptr released = retained; + const auto cancelled = calls.add({[retained](const auto&) {}, [retained](auto) {}}); + retained.reset(); + calls.cancel(cancelled); + check(released.expired()); + when("the correlation counter wraps", [&] { + for (std::size_t i = 1; i < std::numeric_limits::max(); ++i) { + const auto id = calls.add({[](const auto&) {}, [](auto) {}}); + require(id != cancelled); + msg::FunctionReturn result; + result.setCallId(id); + require(calls.complete(result)); + } + const auto next = calls.add({[](const auto&) {}, [](auto) {}}); + then("the reserved ID is skipped until its response is consumed", [&] { + check(next != cancelled); + msg::FunctionReturn late; + late.setCallId(cancelled); + check(calls.complete(late)); + }); + }); + }); + }}; const Scenario serverScope{"A server scope can release the final owner of a WebSocket during cancellation", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - given("a WebSocket owned only by its pending read and write tasks", [&] { - auto socket = websocket::WebSocket::create(InjectableSocket{}, scope); - std::weak_ptr> lifetime = socket; - socket->start(); - InjectableSocket::deferWrites(); - socket->write(std::string_view("pending")); - socket.reset(); - require(!lifetime.expired()); - when("the parent scope requests stop inline", [&] { - scope.requestStop(); - then("both tasks release the socket before the stop callback returns", [&] { - check(lifetime.expired()); - check(InjectableSocket::completeDeferredWrites() == 1); - }); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + given("a WebSocket owned only by its pending read and write tasks", [&] { + auto socket = websocket::WebSocket::create(InjectableSocket{}, scope); + std::weak_ptr> lifetime = socket; + socket->start(); + InjectableSocket::deferWrites(); + socket->write(std::string_view("pending")); + socket.reset(); + require(!lifetime.expired()); + when("the parent scope requests stop inline", [&] { + scope.requestStop(); + then("both tasks release the socket before the stop callback returns", [&] { + check(lifetime.expired()); + check(InjectableSocket::completeDeferredWrites() == 1); + }); + }); + }); + }}; const Scenario browserSenders{"Browser senders reject inconsistent return envelopes", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) { }, scope}; - SenderApp app{link}; - BasicUI ui{app, 1, 1}; - ex::inplace_stop_source stop; - SenderObserved observed; - given("a pending string call", [&] { - auto operation = ex::connect(ui.jsFunctionSender("result")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - when("a return contains no result", [&] { - reply(1, [](auto&, auto&) { }); - then("its arity error reaches the receiver", [&] { - check(observed.error == "Malformed function return message"); - }); - }); - when("a return contains trailing value data", [&] { - reply(1, [](auto& message, auto& frame) { - message.encodeParameter("first", frame); - message.encodeParameter("extra", frame); - message.setParametersCount(1); - frame.freeze(); - }); - then("the extra bytes are rejected", [&] { - check(observed.error == "Function return contains trailing data"); - }); - }); - when("an encoded exception contains trailing data", [&] { - reply(1, [](auto& message, auto& frame) { - const std::runtime_error error("failure"); - message.encodeParameter(error, frame); - message.encodeParameter("extra", frame); - message.setParametersCount(1); - frame.freeze(); - }); - then("the malformed exception is rejected", [&] { - check(observed.error == "Malformed exception return payload"); - }); - }); - check(observed.completions == 1); - }); - given("a pending void call", [&] { - auto operation = ex::connect(ui.jsFunctionSender("finish")(), Receiver{observed, stop.get_token()}); - ex::start(operation); - reply(1, [](auto& message, auto& frame) { - message.encodeParameter("unexpected", frame); - frame.freeze(); - }); - then("a nonempty result is rejected", [&] { - check(observed.error == "Malformed void return message"); - check(observed.completions == 1); - }); - }); - given("a browser reply whose correlation ID was never registered", [&] { - stringReply(99, "unknown"); - then("the receive loop still accepts the next valid call", [&] { - auto [id, future] = link.expectResult(); - stringReply(id, "valid"); - check(future.get() == "valid"); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 1, [](WebLinkEvent) {}, scope}; + SenderApp app{link}; + BasicUI ui{app, 1, 1}; + ex::inplace_stop_source stop; + SenderObserved observed; + given("a pending string call", [&] { + auto operation = ex::connect(ui.jsFunctionSender("result")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + when("a return contains no result", [&] { + reply(1, [](auto&, auto&) {}); + then("its arity error reaches the receiver", [&] { + check(observed.error == "Malformed function return message"); + }); + }); + when("a return contains trailing value data", [&] { + reply(1, [](auto& message, auto& frame) { + message.encodeParameter("first", frame); + message.encodeParameter("extra", frame); + message.setParametersCount(1); + frame.freeze(); + }); + then("the extra bytes are rejected", [&] { + check(observed.error == "Function return contains trailing data"); + }); + }); + when("an encoded exception contains trailing data", [&] { + reply(1, [](auto& message, auto& frame) { + const std::runtime_error error("failure"); + message.encodeParameter(error, frame); + message.encodeParameter("extra", frame); + message.setParametersCount(1); + frame.freeze(); + }); + then("the malformed exception is rejected", [&] { + check(observed.error == "Malformed exception return payload"); + }); + }); + check(observed.completions == 1); + }); + given("a pending void call", [&] { + auto operation = ex::connect(ui.jsFunctionSender("finish")(), Receiver{observed, stop.get_token()}); + ex::start(operation); + reply(1, [](auto& message, auto& frame) { + message.encodeParameter("unexpected", frame); + frame.freeze(); + }); + then("a nonempty result is rejected", [&] { + check(observed.error == "Malformed void return message"); + check(observed.completions == 1); + }); + }); + given("a browser reply whose correlation ID was never registered", [&] { + stringReply(99, "unknown"); + then("the receive loop still accepts the next valid call", [&] { + auto [id, future] = link.expectResult(); + stringReply(id, "valid"); + check(future.get() == "valid"); + }); + }); + }}; const Scenario correlationExhaustion{"Correlation exhaustion fails until an outstanding reply releases an ID", [] { - given("a registry with every ID reserved by an unanswered cancelled call", [&] { - webfront::detail::PendingCalls calls; - for (std::size_t i = 0; i < std::numeric_limits::max(); ++i) { - const auto id = calls.add({}); - calls.cancel(id); - } - when("another call is registered", [&] { - then("registration fails instead of reusing an unanswered ID", [&] { - checkThrows([&] { calls.add({}); }, equals("Too many outstanding WebFront calls")); - }); - }); - when("the browser returns one of the cancelled calls", [&] { - msg::FunctionReturn result; - result.setCallId(7); - require(calls.complete(result)); - then("its ID is available again", [&] { - check(calls.add({}) == 7); - }); - }); - }); -}}; + given("a registry with every ID reserved by an unanswered cancelled call", [&] { + webfront::detail::PendingCalls calls; + for (std::size_t i = 0; i < std::numeric_limits::max(); ++i) { + const auto id = calls.add({}); + calls.cancel(id); + } + when("another call is registered", [&] { + then("registration fails instead of reusing an unanswered ID", [&] { + checkThrows( + [&] { + calls.add({}); + }, + equals("Too many outstanding WebFront calls")); + }); + }); + when("the browser returns one of the cancelled calls", [&] { + msg::FunctionReturn result; + result.setCallId(7); + require(calls.complete(result)); + then("its ID is available again", [&] { + check(calls.add({}) == 7); + }); + }); + }); + }}; -const Scenario senderReports{"A sender reports a socket expiring independently of its correlation registry", [] { - given("an expired socket and a still-owned registry", [&] { - auto calls = std::make_shared>(); - std::vector payload(sizeof(msg::FunctionCallHeader)); - webfront::detail::BrowserCallSender sender{calls, {}, std::move(payload)}; - SenderObserved observed; - ex::inplace_stop_source stop; - auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); - when("the operation starts", [&] { - ex::start(operation); - then("the receiver gets a connection error without accessing the socket", [&] { - check(observed.error == "Browser connection closed"); - check(observed.completions == 1); +const Scenario senderReports{ + "A sender reports a socket expiring independently of its correlation registry", + [] { + given("an expired socket and a still-owned registry", [&] { + auto calls = std::make_shared>(); + std::vector payload(sizeof(msg::FunctionCallHeader)); + webfront::detail::BrowserCallSender sender{calls, {}, std::move(payload)}; + SenderObserved observed; + ex::inplace_stop_source stop; + auto operation = ex::connect(std::move(sender), Receiver{observed, stop.get_token()}); + when("the operation starts", [&] { + ex::start(operation); + then("the receiver gets a connection error without accessing the socket", [&] { + check(observed.error == "Browser connection closed"); + check(observed.completions == 1); + }); }); }); - }); -}}; + }}; const Scenario obsoleteRegistration{"An obsolete registration cannot cancel a replacement with the same wire ID", [] { - given("a completed call whose operation is still delivering an error", [&] { - webfront::detail::PendingCalls calls; - int originalOwner{}; - int replacementOwner{}; - const auto old = calls.add({.complete = [](const auto&) { }, .reject = {}, .owner = &originalOwner}); - msg::FunctionReturn result; - result.setCallId(old); - require(calls.complete(result)); - for (std::size_t i = 1; i < std::numeric_limits::max(); ++i) { - result.setCallId(calls.add({})); - require(calls.complete(result)); - } - bool completed = false; - const auto replacement = calls.add({.complete = - [&](const auto&) { - completed = true; - }, - .reject = {}, - .owner = &replacementOwner}); - require(replacement == old); - when("the obsolete operation tries to discard its registration", [&] { - calls.cancel(old, &originalOwner); - result.setCallId(replacement); - require(calls.complete(result)); - then("the replacement still receives its own reply", [&] { - check(completed); - }); - }); - }); -}}; + given("a completed call whose operation is still delivering an error", [&] { + webfront::detail::PendingCalls calls; + int originalOwner{}; + int replacementOwner{}; + const auto old = calls.add({.complete = [](const auto&) {}, .reject = {}, .owner = &originalOwner}); + msg::FunctionReturn result; + result.setCallId(old); + require(calls.complete(result)); + for (std::size_t i = 1; i < std::numeric_limits::max(); ++i) { + result.setCallId(calls.add({})); + require(calls.complete(result)); + } + bool completed = false; + const auto replacement = calls.add({.complete = + [&](const auto&) { + completed = true; + }, + .reject = {}, + .owner = &replacementOwner}); + require(replacement == old); + when("the obsolete operation tries to discard its registration", [&] { + calls.cancel(old, &originalOwner); + result.setCallId(replacement); + require(calls.complete(result)); + then("the replacement still receives its own reply", [&] { + check(completed); + }); + }); + }); + }}; diff --git a/test/unit/LifeTests.cpp b/test/unit/LifeTests.cpp index 5eacc821..28007826 100644 --- a/test/unit/LifeTests.cpp +++ b/test/unit/LifeTests.cpp @@ -11,118 +11,122 @@ using webfront::demo::LifeGrid; using webfront::demo::nextLife; const Scenario lifeGenerations{"Life generations follow B3/S23 synchronously", [] { - given("an empty grid and a stable block", [&] { - require(nextLife({}).none()); - LifeGrid block; - for (const auto i : {330, 331, 362, 363}) - block.set(static_cast(i)); - require(nextLife(block) == block); - }); - given("a horizontal blinker", [&] { - LifeGrid horizontal, vertical; - for (const auto i : {330, 331, 332}) - horizontal.set(static_cast(i)); - for (const auto i : {299, 331, 363}) - vertical.set(static_cast(i)); - when("two generations are computed", [&] { - require(nextLife(horizontal) == vertical); - require(nextLife(vertical) == horizontal); - require(horizontal.count() == 3); - }); - }); - given("a glider", [&] { - LifeGrid grid, translated; - for (const auto i : {1, 34, 64, 65, 66}) - grid.set(static_cast(i)); - for (const auto i : {34, 67, 97, 98, 99}) - translated.set(static_cast(i)); - for (int i = 0; i < 4; ++i) - grid = nextLife(grid); - require(grid == translated); - }); -}}; + given("an empty grid and a stable block", [&] { + require(nextLife({}).none()); + LifeGrid block; + for (const auto i : {330, 331, 362, 363}) + block.set(static_cast(i)); + require(nextLife(block) == block); + }); + given("a horizontal blinker", [&] { + LifeGrid horizontal, vertical; + for (const auto i : {330, 331, 332}) + horizontal.set(static_cast(i)); + for (const auto i : {299, 331, 363}) + vertical.set(static_cast(i)); + when("two generations are computed", [&] { + require(nextLife(horizontal) == vertical); + require(nextLife(vertical) == horizontal); + require(horizontal.count() == 3); + }); + }); + given("a glider", [&] { + LifeGrid grid, translated; + for (const auto i : {1, 34, 64, 65, 66}) + grid.set(static_cast(i)); + for (const auto i : {34, 67, 97, 98, 99}) + translated.set(static_cast(i)); + for (int i = 0; i < 4; ++i) + grid = nextLife(grid); + require(grid == translated); + }); + }}; const Scenario lifeWraps{"Life wraps both axes without treating adjacent rows as neighbors", [] { - LifeGrid horizontal, vertical; - for (const auto i : {31, 0, 1}) - horizontal.set(static_cast(i)); - for (const auto i : {992, 0, 32}) - vertical.set(static_cast(i)); - require(nextLife(horizontal) == vertical); - require(nextLife(vertical) == horizontal); - LifeGrid isolated; - for (const auto i : {30, 31, 34}) - isolated.set(static_cast(i)); - require(nextLife(isolated).none()); -}}; + LifeGrid horizontal, vertical; + for (const auto i : {31, 0, 1}) + horizontal.set(static_cast(i)); + for (const auto i : {992, 0, 32}) + vertical.set(static_cast(i)); + require(nextLife(horizontal) == vertical); + require(nextLife(vertical) == horizontal); + LifeGrid isolated; + for (const auto i : {30, 31, 34}) + isolated.set(static_cast(i)); + require(nextLife(isolated).none()); + }}; using webfront::demo::parseLifeDeveloperOptions; using webfront::demo::prepareLifeProject; -const Scenario webFrontLifeDeveloperStarts{"WebFrontLifeDeveloper starts without arguments", [] { - given("an empty command line", [&] { - const char* argv[] = {"WebFrontLifeDeveloper"}; - const auto options = parseLifeDeveloperOptions(1, argv); - then("the project is life-project and the pinned environment is used", [&] { - require(options); - require(options->project == "life-project"); - require(!options->environment); - require(!options->integrity); +const Scenario webFrontLifeDeveloperStarts{ + "WebFrontLifeDeveloper starts without arguments", + [] { + given("an empty command line", [&] { + const char* argv[] = {"WebFrontLifeDeveloper"}; + const auto options = parseLifeDeveloperOptions(1, argv); + then("the project is life-project and the pinned environment is used", [&] { + require(options); + require(options->project == "life-project"); + require(!options->environment); + require(!options->integrity); + }); }); - }); - given("an explicit project", [&] { - const char* argv[] = {"WebFrontLifeDeveloper", "other"}; - const auto options = parseLifeDeveloperOptions(2, argv); - then("it replaces the default and keeps the pinned environment", [&] { - require(options); - require(options->project == "other"); - require(!options->environment); + given("an explicit project", [&] { + const char* argv[] = {"WebFrontLifeDeveloper", "other"}; + const auto options = parseLifeDeveloperOptions(2, argv); + then("it replaces the default and keeps the pinned environment", [&] { + require(options); + require(options->project == "other"); + require(!options->environment); + }); }); - }); - given("a project with an environment archive and its integrity", [&] { - const char* argv[] = {"WebFrontLifeDeveloper", "other", "https://example.test/environment.tgz", "sha512-abc"}; - const auto options = parseLifeDeveloperOptions(4, argv); - then("both are passed on", [&] { - require(options); - require(options->environment == "https://example.test/environment.tgz"); - require(options->integrity == "sha512-abc"); + given("a project with an environment archive and its integrity", [&] { + const char* argv[] = {"WebFrontLifeDeveloper", "other", "https://example.test/environment.tgz", "sha512-abc"}; + const auto options = parseLifeDeveloperOptions(4, argv); + then("both are passed on", [&] { + require(options); + require(options->environment == "https://example.test/environment.tgz"); + require(options->integrity == "sha512-abc"); + }); }); - }); - given("an incomplete or empty command line", [&] { - const char* three[] = {"WebFrontLifeDeveloper", "other", "https://example.test/environment.tgz"}; - const char* empty[] = {"WebFrontLifeDeveloper", ""}; - const char* many[] = {"WebFrontLifeDeveloper", "a", "b", "c", "d"}; - then("it is rejected", [&] { - require(!parseLifeDeveloperOptions(3, three)); - require(!parseLifeDeveloperOptions(2, empty)); - require(!parseLifeDeveloperOptions(5, many)); + given("an incomplete or empty command line", [&] { + const char* three[] = {"WebFrontLifeDeveloper", "other", "https://example.test/environment.tgz"}; + const char* empty[] = {"WebFrontLifeDeveloper", ""}; + const char* many[] = {"WebFrontLifeDeveloper", "a", "b", "c", "d"}; + then("it is rejected", [&] { + require(!parseLifeDeveloperOptions(3, three)); + require(!parseLifeDeveloperOptions(2, empty)); + require(!parseLifeDeveloperOptions(5, many)); + }); }); - }); -}}; + }}; const Scenario defaultLife{"The default Life project is created once and then reused", [] { - webfront::test::TemporaryDirectory work; - const auto project = work.path() / "life-project"; - given("a missing project directory", [&] { - prepareLifeProject(project); - then("it exists", [&] { - require(std::filesystem::is_directory(project)); - }); - when("the user has edited a file and the example starts again", [&] { - std::ofstream{project / "webfront.project.json"} << "edited"; - prepareLifeProject(project); - then("the content is unchanged", [&] { - std::ifstream in{project / "webfront.project.json"}; - std::string content; - std::getline(in, content); - require(content == "edited"); - }); - }); - }); - given("a path occupied by a regular file", [&] { - std::ofstream{work.path() / "occupied"} << "x"; - then("preparation fails so that the example exits with an error", [&] { - requireThrows([&] { prepareLifeProject(work.path() / "occupied"); }); - }); - }); -}}; + webfront::test::TemporaryDirectory work; + const auto project = work.path() / "life-project"; + given("a missing project directory", [&] { + prepareLifeProject(project); + then("it exists", [&] { + require(std::filesystem::is_directory(project)); + }); + when("the user has edited a file and the example starts again", [&] { + std::ofstream{project / "webfront.project.json"} << "edited"; + prepareLifeProject(project); + then("the content is unchanged", [&] { + std::ifstream in{project / "webfront.project.json"}; + std::string content; + std::getline(in, content); + require(content == "edited"); + }); + }); + }); + given("a path occupied by a regular file", [&] { + std::ofstream{work.path() / "occupied"} << "x"; + then("preparation fails so that the example exits with an error", [&] { + requireThrows([&] { + prepareLifeProject(work.path() / "occupied"); + }); + }); + }); + }}; diff --git a/test/unit/LoggerTests.cpp b/test/unit/LoggerTests.cpp index 23fb63e4..f3d97cbb 100644 --- a/test/unit/LoggerTests.cpp +++ b/test/unit/LoggerTests.cpp @@ -1,14 +1,13 @@ #include "../driver/RequestLog.hpp" -#include - #include +#include #include +#include #include +#include #include #include -#include -#include #include #include @@ -18,174 +17,176 @@ using namespace webfront; using namespace std; const Scenario loggerScenario{"Logger", [] { - std::list logs; - auto testSink = [&logs](std::string_view text) { logs.emplace_back(text); }; + std::list logs; + auto testSink = [&logs](std::string_view text) { + logs.emplace_back(text); + }; - given("A Logger with a debug level config", [&] { - log::setLogLevel(log::Debug); - auto sinkId = log::addSinks(testSink); + given("A Logger with a debug level config", [&] { + log::setLogLevel(log::Debug); + auto sinkId = log::addSinks(testSink); - when("An info and debug lines are logged", [&] { - log::debug("Debug log"); - log::info("Info log"); - then("Two logs should have been correctly issued", [&] { - auto& infoLog = logs.back(); - require(infoLog.starts_with("[I]")); - require(infoLog.ends_with("Info log")); + when("An info and debug lines are logged", [&] { + log::debug("Debug log"); + log::info("Info log"); + then("Two logs should have been correctly issued", [&] { + auto& infoLog = logs.back(); + require(infoLog.starts_with("[I]")); + require(infoLog.ends_with("Info log")); - logs.pop_back(); - auto& debugLog = logs.back(); - require(debugLog.starts_with("[D]")); - require(debugLog.ends_with("Debug log")); -#ifndef __llvm__ // No support for source_location filename for now - require(debugLog.find("LoggerTests.cpp") != debugLog.npos); + logs.pop_back(); + auto& debugLog = logs.back(); + require(debugLog.starts_with("[D]")); + require(debugLog.ends_with("Debug log")); +#ifndef __llvm__ // No support for source_location filename for now + require(debugLog.find("LoggerTests.cpp") != debugLog.npos); #endif - }); - }); + }); + }); + + when("Selected log levels are disabled", [&] { + size_t logCounter = 0; + log::set(log::Warn, false); + log::set(log::Error, false); + log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); + log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); + log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); + log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); + log::set(log::Warn, true); + log::set(log::Info, false); + log::set(log::Debug, false); + log::set(log::Error, true); + log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); + log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); + log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); + log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); + log::setLogLevel(log::Info); + log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); + log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); + log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); + log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); - when("Selected log levels are disabled", [&] { - size_t logCounter = 0; - log::set(log::Warn, false); - log::set(log::Error, false); - log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); - log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); - log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); - log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); - log::set(log::Warn, true); - log::set(log::Info, false); - log::set(log::Debug, false); - log::set(log::Error, true); - log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); - log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); - log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); - log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); - log::setLogLevel(log::Info); - log::warn("Warn log:{} enabled [{}]", logCounter++, log::is(log::Warn) ? 'x' : ' '); - log::info("Info log:{} enabled [{}]", logCounter++, log::is(log::Info) ? 'x' : ' '); - log::debug("Debug log:{} enabled [{}]", logCounter++, log::is(log::Debug) ? 'x' : ' '); - log::error("Error log:{} enabled [{}]", logCounter++, log::is(log::Error) ? 'x' : ' '); - - then("Only enabled level should have produced a log", [&] { - for (auto& logLine : logs) { - std::clog << " logline : " << logLine << "\n"; - require(logLine.ends_with("enabled [x]")); - } + then("Only enabled level should have produced a log", [&] { + for (auto& logLine : logs) { + std::clog << " logline : " << logLine << "\n"; + require(logLine.ends_with("enabled [x]")); + } - for (auto level : {'I', 'D', 'W', 'E', 'W', 'I', 'E'}) { - require(logs.front().at(1) == level); - logs.pop_front(); - } - }); - }); + for (auto level : {'I', 'D', 'W', 'E', 'W', 'I', 'E'}) { + require(logs.front().at(1) == level); + logs.pop_front(); + } + }); + }); - log::removeSinks(sinkId); - }); -}}; + log::removeSinks(sinkId); + }); + }}; #if !defined(WEBFRONT_USE_MDDLOG) || !WEBFRONT_USE_MDDLOG const Scenario fallbackLogger{"Fallback logger removal waits for active delivery", [] { - using namespace std::chrono_literals; - log::setLogLevel(log::Info); - std::promise entered, release; - auto ready = entered.get_future(); - const auto gate = release.get_future().share(); - const auto sink = log::addSinks([&](std::string_view) { - entered.set_value(); - gate.wait(); - }); - std::thread producer([] { - log::info("blocked delivery"); - }); - const bool running = waitReady(ready); - check(running); - std::promise removed; - auto done = removed.get_future(); - std::thread remover([&] { - log::removeSinks(sink); - removed.set_value(); - }); - // A negative observation of a deliberately blocked call, not a readiness deadline. - if (running) - check(done.wait_for(50ms) == std::future_status::timeout); - release.set_value(); - producer.join(); - remover.join(); - check(done.wait_for(0ms) == std::future_status::ready); - log::setLogLevel(log::Error); -}}; + using namespace std::chrono_literals; + log::setLogLevel(log::Info); + std::promise entered, release; + auto ready = entered.get_future(); + const auto gate = release.get_future().share(); + const auto sink = log::addSinks([&](std::string_view) { + entered.set_value(); + gate.wait(); + }); + std::thread producer([] { + log::info("blocked delivery"); + }); + const bool running = waitReady(ready); + check(running); + std::promise removed; + auto done = removed.get_future(); + std::thread remover([&] { + log::removeSinks(sink); + removed.set_value(); + }); + // A negative observation of a deliberately blocked call, not a readiness deadline. + if (running) + check(done.wait_for(50ms) == std::future_status::timeout); + release.set_value(); + producer.join(); + remover.join(); + check(done.wait_for(0ms) == std::future_status::ready); + log::setLogLevel(log::Error); + }}; const Scenario secondRemoval{"A second removal of the same fallback sink also waits for the active delivery (#542)", [] { - using namespace std::chrono_literals; - log::setLogLevel(log::Info); - std::promise entered, release; - auto ready = entered.get_future(); - const auto gate = release.get_future().share(); - const auto sink = log::addSinks([&](std::string_view) { - entered.set_value(); - gate.wait(); - }); - std::thread producer([] { - log::info("blocked delivery"); - }); - const bool running = checkReady(ready); - check(running); - std::promise firstRemoved, secondRemoved; - auto firstDone = firstRemoved.get_future(); - auto secondDone = secondRemoved.get_future(); - std::thread first([&] { - log::removeSinks(sink); - firstRemoved.set_value(); - }); - // The slot is emptied at once, while the first removal keeps waiting for the delivery. - if (running) - check(firstDone.wait_for(50ms) == std::future_status::timeout); - std::thread second([&] { - log::removeSinks(sink); - secondRemoved.set_value(); - }); - // A negative observation of a deliberately blocked call, not a readiness deadline. - if (running) - check(secondDone.wait_for(50ms) == std::future_status::timeout); - release.set_value(); - producer.join(); - first.join(); - second.join(); - check(firstDone.wait_for(0ms) == std::future_status::ready); - check(secondDone.wait_for(0ms) == std::future_status::ready); - // Once nothing runs the callback, a further removal returns at once. - log::removeSinks(sink); - log::setLogLevel(log::Error); -}}; + using namespace std::chrono_literals; + log::setLogLevel(log::Info); + std::promise entered, release; + auto ready = entered.get_future(); + const auto gate = release.get_future().share(); + const auto sink = log::addSinks([&](std::string_view) { + entered.set_value(); + gate.wait(); + }); + std::thread producer([] { + log::info("blocked delivery"); + }); + const bool running = checkReady(ready); + check(running); + std::promise firstRemoved, secondRemoved; + auto firstDone = firstRemoved.get_future(); + auto secondDone = secondRemoved.get_future(); + std::thread first([&] { + log::removeSinks(sink); + firstRemoved.set_value(); + }); + // The slot is emptied at once, while the first removal keeps waiting for the delivery. + if (running) + check(firstDone.wait_for(50ms) == std::future_status::timeout); + std::thread second([&] { + log::removeSinks(sink); + secondRemoved.set_value(); + }); + // A negative observation of a deliberately blocked call, not a readiness deadline. + if (running) + check(secondDone.wait_for(50ms) == std::future_status::timeout); + release.set_value(); + producer.join(); + first.join(); + second.join(); + check(firstDone.wait_for(0ms) == std::future_status::ready); + check(secondDone.wait_for(0ms) == std::future_status::ready); + // Once nothing runs the callback, a further removal returns at once. + log::removeSinks(sink); + log::setLogLevel(log::Error); + }}; const Scenario fallbackLoggerRegistration{"Fallback logger registration and delivery may run on different threads", [] { - log::setLogLevel(log::Info); - std::atomic seen{0}; - const auto sink = log::addSinks([&](std::string_view line) { - if (line.find("stable record") != std::string_view::npos) - ++seen; - }); - static constexpr unsigned each = 2000; - auto emit = [] { - for (unsigned i = 0; i < each; ++i) { - log::info("stable record"); - log::warn("level changed concurrently"); - } - }; - std::thread first(emit), second(emit); - std::thread registrations([] { - for (unsigned i = 0; i < each; ++i) { - const auto temporary = log::addSinks([](std::string_view) { }); - log::set(log::Warn, (i & 1) != 0); - log::removeSinks(temporary); - } - }); - first.join(); - second.join(); - registrations.join(); - log::removeSinks(sink); - log::setLogLevel(log::Error); - require(seen == 2 * each); -}}; + log::setLogLevel(log::Info); + std::atomic seen{0}; + const auto sink = log::addSinks([&](std::string_view line) { + if (line.find("stable record") != std::string_view::npos) + ++seen; + }); + static constexpr unsigned each = 2000; + auto emit = [] { + for (unsigned i = 0; i < each; ++i) { + log::info("stable record"); + log::warn("level changed concurrently"); + } + }; + std::thread first(emit), second(emit); + std::thread registrations([] { + for (unsigned i = 0; i < each; ++i) { + const auto temporary = log::addSinks([](std::string_view) {}); + log::set(log::Warn, (i & 1) != 0); + log::removeSinks(temporary); + } + }); + first.join(); + second.join(); + registrations.join(); + log::removeSinks(sink); + log::setLogLevel(log::Error); + require(seen == 2 * each); + }}; namespace { // Restores the level that the other scenarios expect, on every path. @@ -196,174 +197,194 @@ struct LevelRestore { }; // Opens a gate once, however the scenario ends, so that the threads blocked on it can be joined. struct Gate { - std::promise promise; + std::promise promise; std::shared_future future{promise.get_future().share()}; - bool opened = false; - void open() { + bool opened = false; + void open() { if (!std::exchange(opened, true)) promise.set_value(); } - ~Gate() { open(); } + ~Gate() { + open(); + } }; } // namespace const Scenario sinkSlots{"Fallback sinks reuse their slots and a stale id cannot remove another sink", [] { - const LevelRestore restore; - log::setLogLevel(log::Info); - given("a sink that was removed and a new one that took its slot", [&] { - std::atomic first{0}, second{0}; - const auto stale = log::addSinks([&](std::string_view) { ++first; }); - log::removeSinks(stale); - const auto live = log::addSinks([&](std::string_view) { ++second; }); - then("the slot is reused with another generation", [&] { - check(live.index == stale.index); - check(live.generation != stale.generation); - }); - when("the stale id is removed again", [&] { - log::removeSinks(stale); - log::info("still delivered"); - then("the new sink keeps receiving lines", [&] { - check(second == 1); - check(first == 0); - }); - }); - log::removeSinks(live); - }); - given("a hundred thousand transient sinks", [&] { - const auto before = log::addSinks([](std::string_view) {}); - std::size_t highest = 0; - for (int i = 0; i < 100000; ++i) { - const auto id = log::addSinks([](std::string_view) {}); - highest = std::max(highest, id.index); - log::removeSinks(id); - } - then("the table stays as small as the sinks alive", [&] { - // Sinks of other scenarios may still be registered; the bound is far below the number added. - check(highest < 64); - }); - log::removeSinks(before); - }); - given("two callbacks registered at once", [&] { - std::atomic a{0}, b{0}; - const auto ids = log::addSinks([&](std::string_view) { ++a; }, [&](std::string_view) { ++b; }); - then("both can be removed one by one", [&] { - log::removeSinks(ids[0]); - log::info("one left"); - check(a == 0); - check(b == 1); - log::removeSinks(ids[1]); - log::info("none left"); - check(b == 1); - }); - }); -}}; + const LevelRestore restore; + log::setLogLevel(log::Info); + given("a sink that was removed and a new one that took its slot", [&] { + std::atomic first{0}, second{0}; + const auto stale = log::addSinks([&](std::string_view) { + ++first; + }); + log::removeSinks(stale); + const auto live = log::addSinks([&](std::string_view) { + ++second; + }); + then("the slot is reused with another generation", [&] { + check(live.index == stale.index); + check(live.generation != stale.generation); + }); + when("the stale id is removed again", [&] { + log::removeSinks(stale); + log::info("still delivered"); + then("the new sink keeps receiving lines", [&] { + check(second == 1); + check(first == 0); + }); + }); + log::removeSinks(live); + }); + given("a hundred thousand transient sinks", [&] { + const auto before = log::addSinks([](std::string_view) {}); + std::size_t highest = 0; + for (int i = 0; i < 100000; ++i) { + const auto id = log::addSinks([](std::string_view) {}); + highest = std::max(highest, id.index); + log::removeSinks(id); + } + then("the table stays as small as the sinks alive", [&] { + // Sinks of other scenarios may still be registered; the bound is far below the number added. + check(highest < 64); + }); + log::removeSinks(before); + }); + given("two callbacks registered at once", [&] { + std::atomic a{0}, b{0}; + const auto ids = log::addSinks( + [&](std::string_view) { + ++a; + }, + [&](std::string_view) { + ++b; + }); + then("both can be removed one by one", [&] { + log::removeSinks(ids[0]); + log::info("one left"); + check(a == 0); + check(b == 1); + log::removeSinks(ids[1]); + log::info("none left"); + check(b == 1); + }); + }); + }}; const Scenario removalFromCallback{"A sink removed from another sink's callback waits for that sink's delivery on another thread", [] { - using namespace std::chrono_literals; - const LevelRestore restore; - log::setLogLevel(log::Info); - std::promise entered, removed; - auto ready = entered.get_future(); - std::atomic finished{false}, victimGone{false}; - Gate gate; - const auto victim = log::addSinks([&](std::string_view line) { - if (line.find("victim") == std::string_view::npos) - return; - entered.set_value(); - gate.future.wait(); - std::this_thread::sleep_for(20ms); - finished = true; - }); - const auto remover = log::addSinks([&](std::string_view line) { - if (line.find("remove") == std::string_view::npos) - return; - log::removeSinks(victim); - victimGone = finished.load(); // the other thread's delivery is over when the removal returns - removed.set_value(); - }); - auto removedDone = removed.get_future(); - std::jthread slow([] { log::info("victim"); }); - std::jthread removing; - const bool running = waitReady(ready); - check(running); - if (running) { - removing = std::jthread([] { log::info("remove"); }); - // A negative observation of a deliberately blocked call, not a readiness deadline. - check(removedDone.wait_for(50ms) == std::future_status::timeout); - } - gate.open(); - slow.join(); - if (removing.joinable()) - removing.join(); - check(victimGone.load()); - log::removeSinks(remover); -}}; + using namespace std::chrono_literals; + const LevelRestore restore; + log::setLogLevel(log::Info); + std::promise entered, removed; + auto ready = entered.get_future(); + std::atomic finished{false}, victimGone{false}; + Gate gate; + const auto victim = log::addSinks([&](std::string_view line) { + if (line.find("victim") == std::string_view::npos) + return; + entered.set_value(); + gate.future.wait(); + std::this_thread::sleep_for(20ms); + finished = true; + }); + const auto remover = log::addSinks([&](std::string_view line) { + if (line.find("remove") == std::string_view::npos) + return; + log::removeSinks(victim); + victimGone = finished.load(); // the other thread's delivery is over when the removal returns + removed.set_value(); + }); + auto removedDone = removed.get_future(); + std::jthread slow([] { + log::info("victim"); + }); + std::jthread removing; + const bool running = waitReady(ready); + check(running); + if (running) { + removing = std::jthread([] { + log::info("remove"); + }); + // A negative observation of a deliberately blocked call, not a readiness deadline. + check(removedDone.wait_for(50ms) == std::future_status::timeout); + } + gate.open(); + slow.join(); + if (removing.joinable()) + removing.join(); + check(victimGone.load()); + log::removeSinks(remover); + }}; const Scenario mutualRemoval{"Two sinks that remove each other from their callbacks do not deadlock", [] { - const LevelRestore restore; - log::setLogLevel(log::Info); - std::promise aIn, bIn; - auto aReady = aIn.get_future(); - auto bReady = bIn.get_future(); - Gate start; - log::SinkId a, b; - std::atomic returned{0}; - std::atomic inA{false}, inB{false}; - a = log::addSinks([&](std::string_view line) { - if (line.find("both") == std::string_view::npos || inA.exchange(true)) - return; - aIn.set_value(); - start.future.wait(); - log::removeSinks(b); - ++returned; - }); - b = log::addSinks([&](std::string_view line) { - if (line.find("both") == std::string_view::npos || inB.exchange(true)) - return; - bIn.set_value(); - start.future.wait(); - log::removeSinks(a); - ++returned; - }); - std::jthread one([] { log::info("both"); }); - std::jthread two([] { log::info("both"); }); - const bool running = waitReady(aReady) && waitReady(bReady); - check(running); - start.open(); - one.join(); - two.join(); - check(returned == 2); - log::removeSinks(a, b); -}}; + const LevelRestore restore; + log::setLogLevel(log::Info); + std::promise aIn, bIn; + auto aReady = aIn.get_future(); + auto bReady = bIn.get_future(); + Gate start; + log::SinkId a, b; + std::atomic returned{0}; + std::atomic inA{false}, inB{false}; + a = log::addSinks([&](std::string_view line) { + if (line.find("both") == std::string_view::npos || inA.exchange(true)) + return; + aIn.set_value(); + start.future.wait(); + log::removeSinks(b); + ++returned; + }); + b = log::addSinks([&](std::string_view line) { + if (line.find("both") == std::string_view::npos || inB.exchange(true)) + return; + bIn.set_value(); + start.future.wait(); + log::removeSinks(a); + ++returned; + }); + std::jthread one([] { + log::info("both"); + }); + std::jthread two([] { + log::info("both"); + }); + const bool running = waitReady(aReady) && waitReady(bReady); + check(running); + start.open(); + one.join(); + two.join(); + check(returned == 2); + log::removeSinks(a, b); + }}; #endif const Scenario requestLog{"The request log keeps what the HTTP layer says about a request (#542)", [] { - using webfront::testdriver::isRequestLine; - // The wording of HTTPServer.hpp: a renamed message must fail here instead of emptying the transcript of a failed case. - given("the lines of an answered request", [&] { - then("they are kept", [&] { - check(isRequestLine("[I] Received request GET on /WebFront.js")); - check(isRequestLine("[I] responding http 200")); - check(isRequestLine("[W] HTTP asset request failed: boom")); - check(isRequestLine("[W] Route /api failed: boom")); - check(isRequestLine("[W] connection ended its response early: boom")); - }); - }); - given("bridge traffic logged at the information level", [&] { - then("it is left out", [&] { - check(!isRequestLine("[I] Call 12 to cppFunction x")); - check(!isRequestLine("[I] Call 12 to cppFunction [W]")); - }); - }); - given("a warning whose message spans several lines", [&] { - then("it is kept whole, as the sink receives it in one call", [&] { - check(isRequestLine("[W] 12:00:00 | Route /api failed: first line\nsecond line\nthird line")); - }); - }); - given("the rows of a hex dump, which carry no level tag", [&] { - then("they are left out", [&] { - check(!isRequestLine("00000010 5b 57 5d 20 20 20 20 20 20 20 20 20 20 20 20 20 |[W] |")); - check(!isRequestLine("00000000 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a |GET / HTTP/1.1..|")); - }); - }); -}}; + using webfront::testdriver::isRequestLine; + // The wording of HTTPServer.hpp: a renamed message must fail here instead of emptying the transcript of a failed case. + given("the lines of an answered request", [&] { + then("they are kept", [&] { + check(isRequestLine("[I] Received request GET on /WebFront.js")); + check(isRequestLine("[I] responding http 200")); + check(isRequestLine("[W] HTTP asset request failed: boom")); + check(isRequestLine("[W] Route /api failed: boom")); + check(isRequestLine("[W] connection ended its response early: boom")); + }); + }); + given("bridge traffic logged at the information level", [&] { + then("it is left out", [&] { + check(!isRequestLine("[I] Call 12 to cppFunction x")); + check(!isRequestLine("[I] Call 12 to cppFunction [W]")); + }); + }); + given("a warning whose message spans several lines", [&] { + then("it is kept whole, as the sink receives it in one call", [&] { + check(isRequestLine("[W] 12:00:00 | Route /api failed: first line\nsecond line\nthird line")); + }); + }); + given("the rows of a hex dump, which carry no level tag", [&] { + then("they are left out", [&] { + check(!isRequestLine("00000010 5b 57 5d 20 20 20 20 20 20 20 20 20 20 20 20 20 |[W] |")); + check(!isRequestLine("00000000 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a |GET / HTTP/1.1..|")); + }); + }); + }}; diff --git a/test/unit/MddlogLoggerTests.cpp b/test/unit/MddlogLoggerTests.cpp index 6c454452..62cab6c3 100644 --- a/test/unit/MddlogLoggerTests.cpp +++ b/test/unit/MddlogLoggerTests.cpp @@ -1,6 +1,6 @@ /** @brief Module-free consumer regressions for WebFront's optional diagnostic facade. */ -#include #include +#include #include #include @@ -31,172 +31,187 @@ struct LoggingScope { }; } // namespace -const Scenario mddlogFacade{"mddlog facade masks, caller location and independent registrations", {"mddlog", "logger"}, [] { - namespace log = webfront::log; - std::vector lines; - std::size_t otherWrites = 0; - LoggingScope scope; - for (const auto level : {log::Error, log::Warn, log::Info, log::Debug}) - require(!log::is(level)); - const auto handles = log::addSinks( - [&](std::string_view text) { - lines.emplace_back(text); - }, - [&](std::string_view) { - ++otherWrites; - }); - scope.handles.assign(handles.begin(), handles.end()); - log::set(log::Error, true); - log::set(log::Warn, false); - log::error("error {}", 42); - log::warn("invalid {"); - require(lines.size() == 1); - require(lines[0].starts_with("[E]")); - require(lines[0].ends_with(" | error 42")); - log::setLogLevel(log::Debug); - const auto callerLine = std::source_location::current().line() + 1; - log::debug("answer {}", 42); - require(lines.back().find(std::format("{:16}:{:4} |", "MddlogLoggerTests.cpp", callerLine)) != std::string::npos); - log::info("info {}", 42); - require(lines.back().starts_with("[I]")); - require(!lines.back().contains("MddlogLoggerTests.cpp")); - log::removeSinks(handles[0]); - log::warn("remaining"); - require(lines.size() == 3); - require(otherWrites == 4); - log::removeSinks(handles[0]); - log::set(log::Disabled, true); - require(!log::is(log::Error)); - require(!log::is(log::Debug)); - log::info("invalid {"); - require(otherWrites == 4); -}}; +const Scenario mddlogFacade{ + "mddlog facade masks, caller location and independent registrations", + {"mddlog", "logger"}, + [] { + namespace log = webfront::log; + std::vector lines; + std::size_t otherWrites = 0; + LoggingScope scope; + for (const auto level : {log::Error, log::Warn, log::Info, log::Debug}) + require(!log::is(level)); + const auto handles = log::addSinks( + [&](std::string_view text) { + lines.emplace_back(text); + }, + [&](std::string_view) { + ++otherWrites; + }); + scope.handles.assign(handles.begin(), handles.end()); + log::set(log::Error, true); + log::set(log::Warn, false); + log::error("error {}", 42); + log::warn("invalid {"); + require(lines.size() == 1); + require(lines[0].starts_with("[E]")); + require(lines[0].ends_with(" | error 42")); + log::setLogLevel(log::Debug); + const auto callerLine = std::source_location::current().line() + 1; + log::debug("answer {}", 42); + require(lines.back().find(std::format("{:16}:{:4} |", "MddlogLoggerTests.cpp", callerLine)) != std::string::npos); + log::info("info {}", 42); + require(lines.back().starts_with("[I]")); + require(!lines.back().contains("MddlogLoggerTests.cpp")); + log::removeSinks(handles[0]); + log::warn("remaining"); + require(lines.size() == 3); + require(otherWrites == 4); + log::removeSinks(handles[0]); + log::set(log::Disabled, true); + require(!log::is(log::Error)); + require(!log::is(log::Debug)); + log::info("invalid {"); + require(otherWrites == 4); + } +}; -const Scenario mddlogFacadeRenders{"mddlog facade renders every byte independently of char signedness", {"mddlog", "logger"}, [] { - namespace log = webfront::log; - std::vector lines; - LoggingScope scope; - scope.handles.push_back(log::addSinks([&](std::string_view text) { - lines.emplace_back(text); - })); - log::setLogLevel(log::Info); - std::array bytes{}; - for (std::size_t index = 0; index < bytes.size(); ++index) - bytes[index] = static_cast(index); - log::infoHex("all bytes {literal}", bytes); - require(lines.size() == 2); - require(lines[0].ends_with(" | all bytes {literal}")); - require(lines[1].size() == (16 * 75) + 15); - for (std::size_t index = 0; index < bytes.size(); ++index) { - const auto expected = index >= 0x20 && index <= 0x7E ? static_cast(index) : '.'; - require(lines[1][((index / 16) * 76) + 59 + (index % 16)] == expected); - } - log::set(log::Info, false); - log::infoHex("disabled", bytes); - require(lines.size() == 2); -}}; +const Scenario mddlogFacadeRenders{ + "mddlog facade renders every byte independently of char signedness", + {"mddlog", "logger"}, + [] { + namespace log = webfront::log; + std::vector lines; + LoggingScope scope; + scope.handles.push_back(log::addSinks([&](std::string_view text) { + lines.emplace_back(text); + })); + log::setLogLevel(log::Info); + std::array bytes{}; + for (std::size_t index = 0; index < bytes.size(); ++index) + bytes[index] = static_cast(index); + log::infoHex("all bytes {literal}", bytes); + require(lines.size() == 2); + require(lines[0].ends_with(" | all bytes {literal}")); + require(lines[1].size() == (16 * 75) + 15); + for (std::size_t index = 0; index < bytes.size(); ++index) { + const auto expected = index >= 0x20 && index <= 0x7E ? static_cast(index) : '.'; + require(lines[1][((index / 16) * 76) + 59 + (index % 16)] == expected); + } + log::set(log::Info, false); + log::infoHex("disabled", bytes); + require(lines.size() == 2); + } +}; -const Scenario mddlogFacadePreserves{"mddlog facade preserves structured context and independent text delivery", {"mddlog", "logger"}, [] { - namespace log = webfront::log; - std::vector lines; - std::vector operations; - LoggingScope scope; - scope.handles.push_back(log::addSinks([&](std::string_view text) { - lines.emplace_back(text); - })); - log::setLogLevel(log::Info); - bool admit = true; - log::setRecordWriter([&](const log::DiagnosticRecord& record) { - require(record.component == "jsFunction"); - require(record.correlationId == "2"); - operations.emplace_back(record.operationId); - return admit; - }); - { - const log::ContextScope context({.component = "jsFunction", .webLinkId = "2", .direction = log::CallDirection::CppToJs, .callId = "1"}); - require(log::tryWrite(log::Info, "request").status == log::WriteStatus::Written); +const Scenario mddlogFacadePreserves{ + "mddlog facade preserves structured context and independent text delivery", + {"mddlog", "logger"}, + [] { + namespace log = webfront::log; + std::vector lines; + std::vector operations; + LoggingScope scope; + scope.handles.push_back(log::addSinks([&](std::string_view text) { + lines.emplace_back(text); + })); + log::setLogLevel(log::Info); + bool admit = true; + log::setRecordWriter([&](const log::DiagnosticRecord& record) { + require(record.component == "jsFunction"); + require(record.correlationId == "2"); + operations.emplace_back(record.operationId); + return admit; + }); { - const log::ContextScope nested({.component = "jsFunction", .webLinkId = "2", .direction = log::CallDirection::JsToCpp, .callId = "3"}); - log::info("reply"); + const log::ContextScope context({.component = "jsFunction", .webLinkId = "2", .direction = log::CallDirection::CppToJs, .callId = "1"}); + require(log::tryWrite(log::Info, "request").status == log::WriteStatus::Written); + { + const log::ContextScope nested({.component = "jsFunction", .webLinkId = "2", .direction = log::CallDirection::JsToCpp, .callId = "3"}); + log::info("reply"); + } + admit = false; + const auto result = log::infoHex("bytes", std::array{0, 65}); + require(result.message.status == log::WriteStatus::RingFull); + require(result.dump.status == log::WriteStatus::RingFull); + require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); } - admit = false; - const auto result = log::infoHex("bytes", std::array{0, 65}); - require(result.message.status == log::WriteStatus::RingFull); - require(result.dump.status == log::WriteStatus::RingFull); - require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); - } - require(operations == std::vector{"cpp-js:1", "js-cpp:3", "cpp-js:1", "cpp-js:1"}); - require(lines.size() == 4); - require(lines.back() == "00000000 00 41 .A"); - const std::string oversized(33, 'x'); - { - const log::ContextScope context({.component = oversized, .webLinkId = "2", .direction = log::CallDirection::None, .callId = ""}); - const auto result = log::tryWrite(log::Info, "refused context"); - require(result.status == log::WriteStatus::IdentifierTooLong); - require(result.field == log::ContextField::Component); - } - require(operations.size() == 4); - require(lines.size() == 5); -}}; + require(operations == std::vector{"cpp-js:1", "js-cpp:3", "cpp-js:1", "cpp-js:1"}); + require(lines.size() == 4); + require(lines.back() == "00000000 00 41 .A"); + const std::string oversized(33, 'x'); + { + const log::ContextScope context({.component = oversized, .webLinkId = "2", .direction = log::CallDirection::None, .callId = ""}); + const auto result = log::tryWrite(log::Info, "refused context"); + require(result.status == log::WriteStatus::IdentifierTooLong); + require(result.field == log::ContextField::Component); + } + require(operations.size() == 4); + require(lines.size() == 5); } +}; -const Scenario mddlogHex{"mddlog hex summary retains truncation from admitted records only", {"mddlog", "logger"}, [] { - namespace log = webfront::log; - const LoggingScope scope; - log::setLogLevel(log::Info); - const std::array largeDump{}; - const std::array smallDump{}; - const std::string largeMessage(161, 'm'); - unsigned int writes = 0; - log::HexWriteOutcome result; +const Scenario mddlogHex{ + "mddlog hex summary retains truncation from admitted records only", + {"mddlog", "logger"}, + [] { + namespace log = webfront::log; + const LoggingScope scope; + log::setLogLevel(log::Info); + const std::array largeDump{}; + const std::array smallDump{}; + const std::string largeMessage(161, 'm'); + unsigned int writes = 0; + log::HexWriteOutcome result; - section("a refused message remains unmarked while an admitted dump is truncated", [&] { - log::setRecordWriter([&](const log::DiagnosticRecord&) { - return ++writes != 1; + section("a refused message remains unmarked while an admitted dump is truncated", [&] { + log::setRecordWriter([&](const log::DiagnosticRecord&) { + return ++writes != 1; + }); + result = log::infoHex("refused message", largeDump); + require(result.message.status == log::WriteStatus::RingFull); + require(!result.message.messageTruncated); + require(result.dump.status == log::WriteStatus::Written); + require(result.dump.messageTruncated); + require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); + require(log::lastWriteOutcome().messageTruncated); }); - result = log::infoHex("refused message", largeDump); - require(result.message.status == log::WriteStatus::RingFull); - require(!result.message.messageTruncated); - require(result.dump.status == log::WriteStatus::Written); - require(result.dump.messageTruncated); - require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); - require(log::lastWriteOutcome().messageTruncated); - }); - section("a refused dump cannot erase an admitted message's truncation", [&] { - log::setRecordWriter([&](const log::DiagnosticRecord&) { - return ++writes == 1; + section("a refused dump cannot erase an admitted message's truncation", [&] { + log::setRecordWriter([&](const log::DiagnosticRecord&) { + return ++writes == 1; + }); + result = log::infoHex(largeMessage, smallDump); + require(result.message.status == log::WriteStatus::Written); + require(result.message.messageTruncated); + require(result.dump.status == log::WriteStatus::RingFull); + require(!result.dump.messageTruncated); + require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); + require(log::lastWriteOutcome().messageTruncated); }); - result = log::infoHex(largeMessage, smallDump); - require(result.message.status == log::WriteStatus::Written); - require(result.message.messageTruncated); - require(result.dump.status == log::WriteStatus::RingFull); - require(!result.dump.messageTruncated); - require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); - require(log::lastWriteOutcome().messageTruncated); - }); - section("an admitted short dump cannot erase an admitted message's truncation", [&] { - log::setRecordWriter([&](const log::DiagnosticRecord&) { - ++writes; - return true; + section("an admitted short dump cannot erase an admitted message's truncation", [&] { + log::setRecordWriter([&](const log::DiagnosticRecord&) { + ++writes; + return true; + }); + result = log::infoHex(largeMessage, smallDump); + require(result.message.messageTruncated); + require(result.dump.status == log::WriteStatus::Written); + require(!result.dump.messageTruncated); + require(log::lastWriteOutcome().status == log::WriteStatus::Written); + require(log::lastWriteOutcome().messageTruncated); }); - result = log::infoHex(largeMessage, smallDump); - require(result.message.messageTruncated); - require(result.dump.status == log::WriteStatus::Written); - require(!result.dump.messageTruncated); - require(log::lastWriteOutcome().status == log::WriteStatus::Written); - require(log::lastWriteOutcome().messageTruncated); - }); - section("refusing both oversized records reports no admitted truncation", [&] { - log::setRecordWriter([&](const log::DiagnosticRecord&) { - ++writes; - return false; + section("refusing both oversized records reports no admitted truncation", [&] { + log::setRecordWriter([&](const log::DiagnosticRecord&) { + ++writes; + return false; + }); + result = log::infoHex(largeMessage, largeDump); + require(result.message.status == log::WriteStatus::RingFull); + require(result.dump.status == log::WriteStatus::RingFull); + require(!result.message.messageTruncated); + require(!result.dump.messageTruncated); + require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); + require(!log::lastWriteOutcome().messageTruncated); }); - result = log::infoHex(largeMessage, largeDump); - require(result.message.status == log::WriteStatus::RingFull); - require(result.dump.status == log::WriteStatus::RingFull); - require(!result.message.messageTruncated); - require(!result.dump.messageTruncated); - require(log::lastWriteOutcome().status == log::WriteStatus::RingFull); - require(!log::lastWriteOutcome().messageTruncated); - }); - require(writes == 2); -}}; + require(writes == 2); + } +}; diff --git a/test/unit/MddlogTransportTests.cpp b/test/unit/MddlogTransportTests.cpp index 02513309..abf5f6c0 100644 --- a/test/unit/MddlogTransportTests.cpp +++ b/test/unit/MddlogTransportTests.cpp @@ -199,7 +199,7 @@ class LinkedBrowser { LinkedBrowser() { InjectableSocket::reset(); log::setLogLevel(log::Info); - link = make_unique>(InjectableSocket{}, WebLinkId{21}, [](WebLinkEvent) { }, scope); + link = make_unique>(InjectableSocket{}, WebLinkId{21}, [](WebLinkEvent) {}, scope); handshake(); log::info("delivered to the browser"); require(log::flushTransports()); @@ -240,298 +240,343 @@ void checkTruncation(const Delivered& record) { } // namespace -const Scenario browserTransports{"Browser transports receive the context captured at emission", {"mddlog", "transport"}, [] { - struct Event { - string_view component; - string_view link; - log::CallDirection direction; - string_view call; - }; - // ADR-003 Decision 6: two links, CallId 1 in both directions, then call 2 and disconnection. - static constexpr array events{ - {{"jsFunction", "1", log::CallDirection::CppToJs, "1"}, - {"jsFunction", "2", log::CallDirection::CppToJs, "1"}, - {"jsFunction", "2", log::CallDirection::CppToJs, "1"}, - {"jsFunction", "1", log::CallDirection::CppToJs, "1"}, - {"cppFunction", "1", log::CallDirection::JsToCpp, "1"}, - {"jsFunction", "2", log::CallDirection::CppToJs, "2"}, - {"weblink", "2", log::CallDirection::CppToJs, "2"}} - }; - Collector first; - Collector second; - TransportScope scope; - scope.add(ref(first)); - scope.add(ref(second)); - - vector expected; - for (const auto& event : events) { - // The connection's strings die before the drain; transports must not need them. - string component(event.component); - string link(event.link); - string call(event.call); - log::ContextScope context({.component = component, .webLinkId = link, .direction = event.direction, .callId = call}); - require(log::tryWrite(log::Info, "identical text with misleading ids 999").status == log::WriteStatus::Written); - const auto prefix = event.direction == log::CallDirection::CppToJs ? "cpp-js:" : "js-cpp:"; - expected.push_back({component, prefix + call, link}); - } - require(log::flushTransports()); - - const auto delivered = first.snapshot(); - check(identities(delivered) == expected); - check(identities(second.snapshot()) == expected); - check(ranges::all_of(delivered, [](const Delivered& record) { - return record.level == log::Info && record.text.starts_with("[I] ") && record.text.ends_with(" | identical text with misleading ids 999"); - })); -}}; - -const Scenario browserTransportsKeep{"Browser transports keep the legacy rendering and the governed truncation flag", {"mddlog", "transport"}, [] { - Collector collector; - TransportScope scope; - scope.add(ref(collector)); - log::setLogLevel(log::Debug); - - const auto callerLine = source_location::current().line() + 1; - log::debug("located {}", 1); - log::infoHex("frame:", array{0x41, 0x7f}); - require(log::tryWrite(log::Warn, string(200, 'x')).status == log::WriteStatus::Written); - require(log::lastWriteOutcome().messageTruncated); - log::error("outside any call"); - require(log::flushTransports()); - - const auto records = collector.snapshot(); - require(records.size() == 5); - checkDebugRendering(records[0], callerLine); - check(records[1].text.ends_with(" | frame:")); - check(records[2].message.ends_with(" A.")); - checkTruncation(records[3]); - check(records[4].text.starts_with("[E] ")); - check(identities({records[4]}) == vector{{}}); -}}; - -const Scenario blockedTransport{"A blocked transport never blocks producers; saturation is refused observably", {"mddlog", "transport"}, [] { - const auto gate = make_shared(); - atomic calls{0}; - TransportScope scope; - OpenOnExit opener(gate); - scope.add([&calls, gate](const log::TransportRecord&) { - if (calls.fetch_add(1) == 0) - gate->block(); - }); - const auto before = log::transportHealth(); - - log::info("blocks the consumer"); - require(gate->waitEntered()); - static constexpr size_t overflow = 20; - size_t written = 0; - size_t refused = 0; - for (size_t index = 0; index < log::transportRingCapacity + overflow; ++index) { - const auto status = log::tryWrite(log::Info, "while blocked").status; - written += status == log::WriteStatus::Written ? 1 : 0; - refused += status == log::WriteStatus::RingFull ? 1 : 0; - } - check(pair(written, refused) == pair(log::transportRingCapacity, overflow)); - check(log::lastWriteOutcome().status == log::WriteStatus::RingFull); - check(since(before).ringRefusals == overflow); - - gate->open(); - require(log::flushTransports()); - check(calls.load() == 1 + log::transportRingCapacity); - check(since(before).delivered == 1 + log::transportRingCapacity); -}}; - -const Scenario transportThrowing{"A transport throwing synchronously is detached before its next record", {"mddlog", "transport"}, [] { - atomic calls{0}; - Collector healthy; - TransportScope scope; - scope.add([&](const log::TransportRecord&) { - ++calls; - throw runtime_error("socket gone"); - }); - scope.add(ref(healthy)); - const auto before = log::transportHealth(); - - log::info("first"); - log::info("second"); - require(log::flushTransports()); - log::info("third"); - require(log::flushTransports()); - - const auto health = since(before); - check(calls.load() == 1); - check(failures(health) == Failures{.delivered = 3, .writeFailures = 1, .reportedFailures = 0, .detachments = 1}); - check(health.activeTransports == before.activeTransports - 1); -}}; - -const Scenario loggingSynchronously{"Logging synchronously from a transport is not amplified", {"mddlog", "transport"}, [] { - atomic echoes{0}; - Collector observer; - TransportScope scope; - scope.add([&](const log::TransportRecord& record) { - ++echoes; - log::error("echo of {}", record.message); - }); - scope.add(ref(observer)); - const auto before = log::transportHealth(); - - log::info("origin"); - flushThrice(); - - check(echoes.load() == 1); - check(deliveredMessages(observer.snapshot()) == vector{"origin"}); - check(since(before).reentrantRecords == 1); -}}; - -const Scenario asynchronousWrite{"An asynchronous write failure detaches the transport before its diagnostic", {"mddlog", "transport"}, [] { - mutex queuedMutex; - vector queued; - Collector observer; - TransportScope scope; - const auto failing = scope.add([&](const log::TransportRecord& record) { - lock_guard lock(queuedMutex); - queued.emplace_back(record.message); - }); - scope.add(ref(observer)); - const auto before = log::transportHealth(); - - log::info("queued write"); - require(log::flushTransports()); - // The write completes later, on another thread, which reports the failure first. - thread([&] { - log::reportTransportFailure(failing); - log::error("browser write failed"); - }).join(); - flushThrice(); - - check(queued == vector{"queued write"}); - check(observer.snapshot().size() == 2); - check(failures(since(before)) == Failures{.delivered = 3, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); -}}; - -const Scenario removalDuring{"Removal during emission is quiescent, so captures can be destroyed at once", {"mddlog", "transport"}, [] { - log::setLogLevel(log::Info); - for (int round = 0; round < 10; ++round) { - auto state = make_unique>(); - atomic removed{false}; - atomic late{0}; - auto handle = log::addTransport([&removed, &late, raw = state.get()](const log::TransportRecord&) { - if (removed.load()) - ++late; - raw->push_back(1); +const Scenario browserTransports{ + "Browser transports receive the context captured at emission", + {"mddlog", "transport"}, + [] { + struct Event { + string_view component; + string_view link; + log::CallDirection direction; + string_view call; + }; + // ADR-003 Decision 6: two links, CallId 1 in both directions, then call 2 and disconnection. + static constexpr array events{ + {{"jsFunction", "1", log::CallDirection::CppToJs, "1"}, + {"jsFunction", "2", log::CallDirection::CppToJs, "1"}, + {"jsFunction", "2", log::CallDirection::CppToJs, "1"}, + {"jsFunction", "1", log::CallDirection::CppToJs, "1"}, + {"cppFunction", "1", log::CallDirection::JsToCpp, "1"}, + {"jsFunction", "2", log::CallDirection::CppToJs, "2"}, + {"weblink", "2", log::CallDirection::CppToJs, "2"}}}; + Collector first; + Collector second; + TransportScope scope; + scope.add(ref(first)); + scope.add(ref(second)); + + vector expected; + for (const auto& event : events) { + // The connection's strings die before the drain; transports must not need them. + string component(event.component); + string link(event.link); + string call(event.call); + log::ContextScope context({.component = component, .webLinkId = link, .direction = event.direction, .callId = call}); + require(log::tryWrite(log::Info, "identical text with misleading ids 999").status == log::WriteStatus::Written); + const auto prefix = event.direction == log::CallDirection::CppToJs ? "cpp-js:" : "js-cpp:"; + expected.push_back({component, prefix + call, link}); + } + require(log::flushTransports()); + + const auto delivered = first.snapshot(); + check(identities(delivered) == expected); + check(identities(second.snapshot()) == expected); + check(ranges::all_of(delivered, [](const Delivered& record) { + return record.level == log::Info && record.text.starts_with("[I] ") && record.text.ends_with(" | identical text with misleading ids 999"); + })); + } +}; + +const Scenario browserTransportsKeep{ + "Browser transports keep the legacy rendering and the governed truncation flag", + {"mddlog", "transport"}, + [] { + Collector collector; + TransportScope scope; + scope.add(ref(collector)); + log::setLogLevel(log::Debug); + + const auto callerLine = source_location::current().line() + 1; + log::debug("located {}", 1); + log::infoHex("frame:", array{0x41, 0x7f}); + require(log::tryWrite(log::Warn, string(200, 'x')).status == log::WriteStatus::Written); + require(log::lastWriteOutcome().messageTruncated); + log::error("outside any call"); + require(log::flushTransports()); + + const auto records = collector.snapshot(); + require(records.size() == 5); + checkDebugRendering(records[0], callerLine); + check(records[1].text.ends_with(" | frame:")); + check(records[2].message.ends_with(" A.")); + checkTruncation(records[3]); + check(records[4].text.starts_with("[E] ")); + check(identities({records[4]}) == vector{{}}); + } +}; + +const Scenario blockedTransport{ + "A blocked transport never blocks producers; saturation is refused observably", + {"mddlog", "transport"}, + [] { + const auto gate = make_shared(); + atomic calls{0}; + TransportScope scope; + OpenOnExit opener(gate); + scope.add([&calls, gate](const log::TransportRecord&) { + if (calls.fetch_add(1) == 0) + gate->block(); + }); + const auto before = log::transportHealth(); + + log::info("blocks the consumer"); + require(gate->waitEntered()); + static constexpr size_t overflow = 20; + size_t written = 0; + size_t refused = 0; + for (size_t index = 0; index < log::transportRingCapacity + overflow; ++index) { + const auto status = log::tryWrite(log::Info, "while blocked").status; + written += status == log::WriteStatus::Written ? 1 : 0; + refused += status == log::WriteStatus::RingFull ? 1 : 0; + } + check(pair(written, refused) == pair(log::transportRingCapacity, overflow)); + check(log::lastWriteOutcome().status == log::WriteStatus::RingFull); + check(since(before).ringRefusals == overflow); + + gate->open(); + require(log::flushTransports()); + check(calls.load() == 1 + log::transportRingCapacity); + check(since(before).delivered == 1 + log::transportRingCapacity); + } +}; + +const Scenario transportThrowing{ + "A transport throwing synchronously is detached before its next record", + {"mddlog", "transport"}, + [] { + atomic calls{0}; + Collector healthy; + TransportScope scope; + scope.add([&](const log::TransportRecord&) { + ++calls; + throw runtime_error("socket gone"); + }); + scope.add(ref(healthy)); + const auto before = log::transportHealth(); + + log::info("first"); + log::info("second"); + require(log::flushTransports()); + log::info("third"); + require(log::flushTransports()); + + const auto health = since(before); + check(calls.load() == 1); + check(failures(health) == Failures{.delivered = 3, .writeFailures = 1, .reportedFailures = 0, .detachments = 1}); + check(health.activeTransports == before.activeTransports - 1); + } +}; + +const Scenario loggingSynchronously{ + "Logging synchronously from a transport is not amplified", + {"mddlog", "transport"}, + [] { + atomic echoes{0}; + Collector observer; + TransportScope scope; + scope.add([&](const log::TransportRecord& record) { + ++echoes; + log::error("echo of {}", record.message); + }); + scope.add(ref(observer)); + const auto before = log::transportHealth(); + + log::info("origin"); + flushThrice(); + + check(echoes.load() == 1); + check(deliveredMessages(observer.snapshot()) == vector{"origin"}); + check(since(before).reentrantRecords == 1); + } +}; + +const Scenario asynchronousWrite{ + "An asynchronous write failure detaches the transport before its diagnostic", + {"mddlog", "transport"}, + [] { + mutex queuedMutex; + vector queued; + Collector observer; + TransportScope scope; + const auto failing = scope.add([&](const log::TransportRecord& record) { + lock_guard lock(queuedMutex); + queued.emplace_back(record.message); }); - atomic stop{false}; - vector producers; - for (int producer = 0; producer < 3; ++producer) - producers.emplace_back([&stop] { - while (!stop.load()) - log::info("load"); + scope.add(ref(observer)); + const auto before = log::transportHealth(); + + log::info("queued write"); + require(log::flushTransports()); + // The write completes later, on another thread, which reports the failure first. + thread([&] { + log::reportTransportFailure(failing); + log::error("browser write failed"); + }).join(); + flushThrice(); + + check(queued == vector{"queued write"}); + check(observer.snapshot().size() == 2); + check(failures(since(before)) == Failures{.delivered = 3, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); + } +}; + +const Scenario removalDuring{ + "Removal during emission is quiescent, so captures can be destroyed at once", + {"mddlog", "transport"}, + [] { + log::setLogLevel(log::Info); + for (int round = 0; round < 10; ++round) { + auto state = make_unique>(); + atomic removed{false}; + atomic late{0}; + auto handle = log::addTransport([&removed, &late, raw = state.get()](const log::TransportRecord&) { + if (removed.load()) + ++late; + raw->push_back(1); }); + atomic stop{false}; + vector producers; + for (int producer = 0; producer < 3; ++producer) + producers.emplace_back([&stop] { + while (!stop.load()) + log::info("load"); + }); + require(log::flushTransports()); + log::removeTransport(handle); + removed.store(true); + state.reset(); + require(log::flushTransports()); + stop.store(true); + for (auto& producer : producers) + producer.join(); + check(late.load() == 0); + } + log::setLogLevel(log::Disabled); + } +}; + +const Scenario webLinkRemoves{ + "WebLink removes its browser transport on normal disconnection", + {"mddlog", "transport", "weblink"}, + [] { + LinkedBrowser browser; + InjectableSocket::fail(make_error_code(errc::connection_reset)); + log::info("after disconnection"); require(log::flushTransports()); - log::removeTransport(handle); - removed.store(true); - state.reset(); + + const auto health = since(browser.before); + check(health.activeTransports == browser.before.activeTransports - 1); + check(health.detachments == 0); + check(!InjectableSocket::wrote("after disconnection")); + } +}; + +const Scenario webLinkCaptures{ + "WebLink captures the link and call context of a C++ function call", + {"mddlog", "transport", "weblink"}, + [] { + LinkedBrowser browser; + Collector observer; + TransportScope scope; + scope.add(ref(observer)); + msg::FunctionCall<> call; + call.setCallId(37); + websocket::Frame frame{span(reinterpret_cast(call.header().data()), call.header().size())}; + const string functionName{"registered"}; // The frame borrows it until freeze() copies it. + call.encodeParameter(functionName, frame); + const string payload{"never-log-this-payload"}; + call.encodeParameter(payload, frame); + frame.freeze(); + InjectableSocket::receive(clientFrame(messagePayload(frame))); require(log::flushTransports()); - stop.store(true); - for (auto& producer : producers) - producer.join(); - check(late.load() == 0); - } - log::setLogLevel(log::Disabled); -}}; - -const Scenario webLinkRemoves{"WebLink removes its browser transport on normal disconnection", {"mddlog", "transport", "weblink"}, [] { - LinkedBrowser browser; - InjectableSocket::fail(make_error_code(errc::connection_reset)); - log::info("after disconnection"); - require(log::flushTransports()); - - const auto health = since(browser.before); - check(health.activeTransports == browser.before.activeTransports - 1); - check(health.detachments == 0); - check(!InjectableSocket::wrote("after disconnection")); -}}; - -const Scenario webLinkCaptures{"WebLink captures the link and call context of a C++ function call", {"mddlog", "transport", "weblink"}, [] { - LinkedBrowser browser; - Collector observer; - TransportScope scope; - scope.add(ref(observer)); - msg::FunctionCall<> call; - call.setCallId(37); - websocket::Frame frame{span(reinterpret_cast(call.header().data()), call.header().size())}; - const string functionName{"registered"}; // The frame borrows it until freeze() copies it. - call.encodeParameter(functionName, frame); - const string payload{"never-log-this-payload"}; - call.encodeParameter(payload, frame); - frame.freeze(); - InjectableSocket::receive(clientFrame(messagePayload(frame))); - require(log::flushTransports()); - - // Only the message summary and the call: binary payloads must not become diagnostic records. - const auto records = observer.snapshot(); - require(records.size() == 2); - check(identities(records) - == vector{ - { "weblink", "", "21"}, - {"cppFunction", "js-cpp:37", "21"} - }); - check(records.front().message.starts_with("onMessage(binary) : ")); - for (const auto& record : records) { - check(record.message.find(payload) == string::npos); - check(record.text.find(payload) == string::npos); - } - check(deliveredMessages(records).back() == "Function called !"); - check(InjectableSocket::wrote("Function called !")); -}}; - -const Scenario webLinkReports{"WebLink reports a write failing inside its transport before the diagnostic", {"mddlog", "transport", "weblink"}, [] { - LinkedBrowser browser; - Collector observer; - TransportScope scope; - scope.add(ref(observer)); - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - log::info("cannot be sent"); - flushThrice(); - - const auto health = since(browser.before); - check(failures(health) == Failures{.delivered = 2, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); - // The write-error diagnostic is logged during dispatch: suppressed for every transport. - check(health.reentrantRecords >= 1); - check(deliveredMessages(observer.snapshot()) == vector{"cannot be sent"}); -}}; - -const Scenario webLinkReportsWrite{"WebLink reports a write failing on asynchronous completion", {"mddlog", "transport", "weblink"}, [] { - LinkedBrowser browser; - InjectableSocket::deferWrites(); - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - log::info("completes later"); - require(log::flushTransports()); - require(InjectableSocket::completeDeferredWrites() == 1); - flushThrice(); - - // Neither the failure diagnostic nor anything later reaches the failed transport. - const auto health = since(browser.before); - check(failures(health) == Failures{.delivered = 1, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); - check(health.activeTransports == browser.before.activeTransports - 1); -}}; - -const Scenario webLinkDestroyed{"A WebLink destroyed before the drain receives nothing more", {"mddlog", "transport", "weblink"}, [] { - LinkedBrowser browser; - const auto gate = make_shared(); - atomic blocked{0}; - TransportScope scope; - OpenOnExit opener(gate); - scope.add([&blocked, gate](const log::TransportRecord&) { - if (blocked.fetch_add(1) == 0) - gate->block(); - }); - log::info("holds the consumer"); - require(gate->waitEntered()); - log::info("queued before destruction"); - browser.link.reset(); - gate->open(); - require(log::flushTransports()); - - check(!InjectableSocket::wrote("queued before destruction")); - // The link's transport left; the blocker is still registered. - check(since(browser.before).activeTransports == browser.before.activeTransports); -}}; + + // Only the message summary and the call: binary payloads must not become diagnostic records. + const auto records = observer.snapshot(); + require(records.size() == 2); + check(identities(records) + == vector{ + { "weblink", "", "21"}, + { "cppFunction", "js-cpp:37", "21"}}); + check(records.front().message.starts_with("onMessage(binary) : ")); + for (const auto& record : records) { + check(record.message.find(payload) == string::npos); + check(record.text.find(payload) == string::npos); + } + check(deliveredMessages(records).back() == "Function called !"); + check(InjectableSocket::wrote("Function called !")); } +}; + +const Scenario webLinkReports{ + "WebLink reports a write failing inside its transport before the diagnostic", + {"mddlog", "transport", "weblink"}, + [] { + LinkedBrowser browser; + Collector observer; + TransportScope scope; + scope.add(ref(observer)); + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + log::info("cannot be sent"); + flushThrice(); + + const auto health = since(browser.before); + check(failures(health) == Failures{.delivered = 2, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); + // The write-error diagnostic is logged during dispatch: suppressed for every transport. + check(health.reentrantRecords >= 1); + check(deliveredMessages(observer.snapshot()) == vector{"cannot be sent"}); + } +}; + +const Scenario webLinkReportsWrite{ + "WebLink reports a write failing on asynchronous completion", + {"mddlog", "transport", "weblink"}, + [] { + LinkedBrowser browser; + InjectableSocket::deferWrites(); + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + log::info("completes later"); + require(log::flushTransports()); + require(InjectableSocket::completeDeferredWrites() == 1); + flushThrice(); + + // Neither the failure diagnostic nor anything later reaches the failed transport. + const auto health = since(browser.before); + check(failures(health) == Failures{.delivered = 1, .writeFailures = 0, .reportedFailures = 1, .detachments = 1}); + check(health.activeTransports == browser.before.activeTransports - 1); + } +}; + +const Scenario webLinkDestroyed{ + "A WebLink destroyed before the drain receives nothing more", + {"mddlog", "transport", "weblink"}, + [] { + LinkedBrowser browser; + const auto gate = make_shared(); + atomic blocked{0}; + TransportScope scope; + OpenOnExit opener(gate); + scope.add([&blocked, gate](const log::TransportRecord&) { + if (blocked.fetch_add(1) == 0) + gate->block(); + }); + log::info("holds the consumer"); + require(gate->waitEntered()); + log::info("queued before destruction"); + browser.link.reset(); + gate->open(); + require(log::flushTransports()); + + check(!InjectableSocket::wrote("queued before destruction")); + // The link's transport left; the blocker is still registered. + check(since(browser.before).activeTransports == browser.before.activeTransports); + } +}; diff --git a/test/unit/MessagesTests.cpp b/test/unit/MessagesTests.cpp index c1ab52f6..c2093f75 100644 --- a/test/unit/MessagesTests.cpp +++ b/test/unit/MessagesTests.cpp @@ -1,7 +1,7 @@ #include "InlineTaskScope.hpp" -#include #include #include +#include #include #include @@ -20,152 +20,158 @@ using namespace std; using namespace webfront; const Scenario handshakeAck{"Handshake and Ack messages have a two-byte header", [] { - require(sizeof(msg::Ack) == 2); - std::vector raw{std::byte{0x00}, std::byte{0x00}}; - then("a bare handshake is little-endian", [&] { - auto handshake = msg::Handshake::castFromRawData(std::span(raw)); - require(sizeof(*handshake) == 2); - require(handshake->getEndian() == msg::JSEndian::little); - }); - then("the proof of an embedded view follows the unchanged header", [&] { - // ADR-003: bytes after the two header bytes are the launch secret of ADR-020. - raw.resize(2 + 64, static_cast('a')); - auto handshake = msg::Handshake::castFromRawData(std::span(raw)); - require(handshake->getEndian() == msg::JSEndian::little); - require(handshake->getPayloadSize() == 0); - require(raw.size() - sizeof(*handshake) == 64); - }); -}}; - -const Scenario functionCallScenario{"FunctionCall", [] { - given("Raw data of a call to 'print' function with a small string as parameter", [&] { - std::array raw{0x03, 0x02, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x04, 0x05, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x04, 0x13, 0x48, - 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x20, 0x32, 0x30, 0x32, 0x32}; - - auto functionCall = msg::FunctionCall<>::castFromRawData(std::span(reinterpret_cast(raw.data()), raw.size())); - require(functionCall->getParametersCount() == 2); - require(functionCall->getPayloadSize() == 28); - auto [name, undecodedData] = functionCall->getFunctionName(); - require(name == "print"); - std::string text; - functionCall->decodeParameter(text, undecodedData); - require(text == "Hello World of 2022"); - require(undecodedData.size() == 0); - }); - given("Raw data of a call to 'cppTest' function with a small string, a string and a number as parameters", [&] { - std::vector raw{ - 0x03, 0x04, 0x00, 0x00, 0xb1, 0x01, 0x00, 0x00, 0x04, 0x07, 0x63, 0x70, 0x70, 0x54, 0x65, 0x73, 0x74, 0x04, 0x35, 0x54, 0x65, 0x78, 0x74, 0x65, - 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, - 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, - 0x05, 0x65, 0x01, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, - 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, - 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, - 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, - 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, - 0x2d, 0x20, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, - 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, - 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, - 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, - 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x2d, - 0x20, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, - 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, - 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, - 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, - 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x2d, 0x20, - 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x76, 0x40}; - - auto functionCall = msg::FunctionCall<>::castFromRawData(std::span(reinterpret_cast(raw.data()), raw.size())); - require(functionCall->getParametersCount() == 4); - require(functionCall->getPayloadSize() == 433); - auto [name, undecodedData] = functionCall->getFunctionName(); - require(name == "cppTest"); - std::string text; - functionCall->decodeParameter(text, undecodedData); - require(text == "Texte de test suffisament long pour changer de format"); - - functionCall->decodeParameter(text, undecodedData); - require(text.starts_with("bigText : Texte de test suffisament long pour changer de format")); - require(text.size() == 357); - require(text.ends_with("suffisament long pour changer de format - ")); - - size_t value{}; - functionCall->decodeParameter(value, undecodedData); - require(value == text.size()); - require(undecodedData.empty()); - }); -}}; - -const Scenario functionReturnScenario{"FunctionReturn", [] { - using Net = networking::NetworkingMock; - - given("A FunctionReturn message", [&] { - msg::FunctionReturn<> message; - websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; - networking::SocketMock socket; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(socket, scope); - - then("Header command byte is functionReturn", [&] { - require(static_cast(message.header()[0]) == msg::Command::functionReturn); + require(sizeof(msg::Ack) == 2); + std::vector raw{std::byte{0x00}, std::byte{0x00}}; + then("a bare handshake is little-endian", [&] { + auto handshake = msg::Handshake::castFromRawData(std::span(raw)); + require(sizeof(*handshake) == 2); + require(handshake->getEndian() == msg::JSEndian::little); + }); + then("the proof of an embedded view follows the unchanged header", [&] { + // ADR-003: bytes after the two header bytes are the launch secret of ADR-020. + raw.resize(2 + 64, static_cast('a')); + auto handshake = msg::Handshake::castFromRawData(std::span(raw)); + require(handshake->getEndian() == msg::JSEndian::little); + require(handshake->getPayloadSize() == 0); + require(raw.size() - sizeof(*handshake) == 64); + }); + }}; + +const Scenario functionCallScenario{ + "FunctionCall", + [] { + given("Raw data of a call to 'print' function with a small string as parameter", [&] { + std::array raw{0x03, 0x02, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x04, 0x05, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x04, 0x13, 0x48, + 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x20, 0x32, 0x30, 0x32, 0x32}; + + auto functionCall = msg::FunctionCall<>::castFromRawData(std::span(reinterpret_cast(raw.data()), raw.size())); + require(functionCall->getParametersCount() == 2); + require(functionCall->getPayloadSize() == 28); + auto [name, undecodedData] = functionCall->getFunctionName(); + require(name == "print"); + std::string text; + functionCall->decodeParameter(text, undecodedData); + require(text == "Hello World of 2022"); + require(undecodedData.size() == 0); }); - - when("An exception is encoded", [&] { - std::string exceptionText = "Parameter error"; - auto exception = std::runtime_error(exceptionText); - message.encodeParameter(exception, frame); - ws->write(std::move(frame)); - - then("Encoded frame should be", [&] { - auto encodedFrame = span(socket.debugBuffer.data(), socket.bufferIndex); - require(encodedFrame.size() == 2 + message.header().size() + 4 + bridge_code::generic.size() + exceptionText.size()); + given("Raw data of a call to 'cppTest' function with a small string, a string and a number as parameters", [&] { + std::vector raw{ + 0x03, 0x04, 0x00, 0x00, 0xb1, 0x01, 0x00, 0x00, 0x04, 0x07, 0x63, 0x70, 0x70, 0x54, 0x65, 0x73, 0x74, 0x04, 0x35, 0x54, 0x65, 0x78, 0x74, 0x65, + 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, + 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x05, 0x65, 0x01, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, + 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, + 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, + 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, + 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, + 0x2d, 0x20, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, + 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, + 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, + 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, + 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x2d, + 0x20, 0x62, 0x69, 0x67, 0x54, 0x65, 0x78, 0x74, 0x20, 0x3a, 0x20, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, 0x20, 0x74, 0x65, 0x73, 0x74, + 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x6f, 0x75, 0x72, 0x20, 0x63, + 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x54, 0x65, 0x78, 0x74, 0x65, 0x20, 0x64, 0x65, + 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x73, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x70, + 0x6f, 0x75, 0x72, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x64, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x2d, 0x20, + 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x76, 0x40}; + + auto functionCall = msg::FunctionCall<>::castFromRawData(std::span(reinterpret_cast(raw.data()), raw.size())); + require(functionCall->getParametersCount() == 4); + require(functionCall->getPayloadSize() == 433); + auto [name, undecodedData] = functionCall->getFunctionName(); + require(name == "cppTest"); + std::string text; + functionCall->decodeParameter(text, undecodedData); + require(text == "Texte de test suffisament long pour changer de format"); + + functionCall->decodeParameter(text, undecodedData); + require(text.starts_with("bigText : Texte de test suffisament long pour changer de format")); + require(text.size() == 357); + require(text.ends_with("suffisament long pour changer de format - ")); + + size_t value{}; + functionCall->decodeParameter(value, undecodedData); + require(value == text.size()); + require(undecodedData.empty()); + }); + }}; + +const Scenario functionReturnScenario{ + "FunctionReturn", + [] { + using Net = networking::NetworkingMock; + + given("A FunctionReturn message", [&] { + msg::FunctionReturn<> message; + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + networking::SocketMock socket; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(socket, scope); + + then("Header command byte is functionReturn", [&] { + require(static_cast(message.header()[0]) == msg::Command::functionReturn); }); - then("A Frame decoded should retrieve the encoded parameters", [&] { - websocket::FrameDecoder decoder; - require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); - - auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); - require(funcRet->getParametersCount() == 1); - require(funcRet->getPayloadSize() == 4 + bridge_code::generic.size() + exceptionText.size()); - - std::string text; - auto undecodedData = funcRet->payload(); - funcRet->decodeParameter(text, undecodedData); - require(text == exceptionText); - require(undecodedData.empty()); + when("An exception is encoded", [&] { + std::string exceptionText = "Parameter error"; + auto exception = std::runtime_error(exceptionText); + message.encodeParameter(exception, frame); + ws->write(std::move(frame)); + + then("Encoded frame should be", [&] { + auto encodedFrame = span(socket.debugBuffer.data(), socket.bufferIndex); + require(encodedFrame.size() == 2 + message.header().size() + 4 + bridge_code::generic.size() + exceptionText.size()); + }); + + then("A Frame decoded should retrieve the encoded parameters", [&] { + websocket::FrameDecoder decoder; + require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); + + auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); + require(funcRet->getParametersCount() == 1); + require(funcRet->getPayloadSize() == 4 + bridge_code::generic.size() + exceptionText.size()); + + std::string text; + auto undecodedData = funcRet->payload(); + funcRet->decodeParameter(text, undecodedData); + require(text == exceptionText); + require(undecodedData.empty()); + }); }); - }); - when("A tuple is encoded", [&] { - std::tuple value{42, "Hello World"}; - message.encodeParameter(value, frame); - ws->write(std::move(frame)); - - then("An erroneous tuple should trigger an exception", [&] { - websocket::FrameDecoder decoder; - require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); - auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); - std::tuple tupleValue; - auto undecodedData = funcRet->payload(); - requireThrows([&] { funcRet->decodeParameter(tupleValue, undecodedData); }); - }); - then("A Frame decoded should retrieve the encoded parameters", [&] { - websocket::FrameDecoder decoder; - require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); - auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); - require(funcRet->getParametersCount() == 1); - require(funcRet->getPayloadSize() == 24); - - std::tuple tupleValue; - auto undecodedData = funcRet->payload(); - funcRet->decodeParameter(tupleValue, undecodedData); - require(std::get<0>(tupleValue) == 42); - require(std::get<1>(tupleValue) == "Hello World"); - require(undecodedData.empty()); + when("A tuple is encoded", [&] { + std::tuple value{42, "Hello World"}; + message.encodeParameter(value, frame); + ws->write(std::move(frame)); + + then("An erroneous tuple should trigger an exception", [&] { + websocket::FrameDecoder decoder; + require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); + auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); + std::tuple tupleValue; + auto undecodedData = funcRet->payload(); + requireThrows([&] { + funcRet->decodeParameter(tupleValue, undecodedData); + }); + }); + then("A Frame decoded should retrieve the encoded parameters", [&] { + websocket::FrameDecoder decoder; + require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); + auto funcRet = msg::FunctionReturn<>::castFromRawData(decoder.payload()); + require(funcRet->getParametersCount() == 1); + require(funcRet->getPayloadSize() == 24); + + std::tuple tupleValue; + auto undecodedData = funcRet->payload(); + funcRet->decodeParameter(tupleValue, undecodedData); + require(std::get<0>(tupleValue) == 42); + require(std::get<1>(tupleValue) == "Hello World"); + require(undecodedData.empty()); + }); }); }); - }); -}}; + }}; namespace { @@ -210,98 +216,111 @@ msg::CodedType firstCodeOf(const T& value) { } // namespace const Scenario strings65536{"Strings of 65536 bytes or more use a 32-bit length", [] { - given("strings on both sides of the 16-bit boundary", [&] { - then("255 bytes is a smallString, 256 to 65535 a string and 65536 a longString", [&] { - require(firstCodeOf(string(255, 'x')) == msg::CodedType::smallString); - require(firstCodeOf(string(256, 'x')) == msg::CodedType::string); - require(firstCodeOf(string(65535, 'x')) == msg::CodedType::string); - require(firstCodeOf(string(65536, 'x')) == msg::CodedType::longString); - }); - then("each crosses the wire whole", [&] { - for (const auto size : {255uz, 256uz, 65535uz, 65536uz, 65537uz, 1000000uz}) { - const string text(size, 'x'); - require(roundTrip(text) == text); - } - }); - }); - given("a UTF-8 character that straddles the 65535-byte boundary", [&] { - const string text = string(65534, 'x') + "\xc3\xa9" + string(10, 'y'); // 'é' occupies bytes 65534 and 65535 - then("it is not cut: the whole string is a longString", [&] { - require(text.size() == 65546); - require(firstCodeOf(text) == msg::CodedType::longString); - require(roundTrip(text) == text); - }); - }); - given("a string whose multi-byte characters take it past 65535 bytes", [&] { - string text; - for (int i = 0; i < 40000; ++i) - text += "\xe2\x82\xac"; // the euro sign, 3 bytes - then("the size counts bytes, not characters", [&] { - require(roundTrip(text) == text); - }); - }); - given("a longString header whose payload is truncated or inconsistent", [&] { - auto decode = [](span bytes) { - string target; - span payload{bytes}; - msg::FunctionCall<>::decodeParameter(target, payload); - }; - const auto long5 = [](uint32_t size, size_t present) { - vector bytes{byte{static_cast(msg::CodedType::longString)}}; - for (int i = 0; i < 4; ++i) - bytes.push_back(byte{static_cast(size >> (8 * i))}); - bytes.insert(bytes.end(), present, byte{'a'}); - return bytes; - }; - then("a header shorter than five bytes is refused", [&] { - const vector header{byte{static_cast(msg::CodedType::longString)}, byte{1}, byte{0}}; - requireThrows([&] { decode(header); }); - }); - then("a length that exceeds the bytes present is refused", [&] { - requireThrows([&] { decode(long5(70000, 69999)); }); - requireThrows([&] { decode(long5(0xffffffffu, 10)); }); - }); - then("the exact length decodes and leaves the cursor after it", [&] { - auto bytes = long5(70000, 70000); - string target; - span payload{bytes}; - msg::FunctionCall<>::decodeParameter(target, payload); - require(target.size() == 70000); - require(payload.empty()); - }); - then("a destination that is not a string is refused", [&] { - auto bytes = long5(5, 5); - int number{}; - span payload{bytes}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(number, payload); }); - }); - }); - given("a policy whose messages cannot exceed 1 MiB", [&] { - using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024 * 1024>; - msg::FunctionReturn message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - then("a string that fits is encoded", [&] { - message.encodeParameter(string(1024 * 1024 - 8 - 5, 'x'), frame); - require(message.getPayloadSize() == 1024 * 1024 - 8); - }); - then("a string one byte too large throws length_error and leaves the message untouched", [&] { - requireThrows([&] { message.encodeParameter(string(1024 * 1024 - 8 - 4, 'x'), frame); }); - require(message.getPayloadSize() == 0); - require(message.getParametersCount() == 0); - require(frame.size() == message.header().size()); - }); - then("the bound counts what the message already carries", [&] { - message.encodeParameter(string(600 * 1024, 'x'), frame); - requireThrows([&] { message.encodeParameter(string(600 * 1024, 'y'), frame); }); - }); - }); - given("an exception message longer than 65535 bytes, with a two-byte character across the limit", [&] { - const runtime_error error{string(65534, 'x') + "\xc3\xa9" + string(10, 'y')}; - then("the message is cut before the first character that does not fit whole", [&] { - require(roundTrip(error) == string(65534, 'x')); - }); - }); -}}; + given("strings on both sides of the 16-bit boundary", [&] { + then("255 bytes is a smallString, 256 to 65535 a string and 65536 a longString", [&] { + require(firstCodeOf(string(255, 'x')) == msg::CodedType::smallString); + require(firstCodeOf(string(256, 'x')) == msg::CodedType::string); + require(firstCodeOf(string(65535, 'x')) == msg::CodedType::string); + require(firstCodeOf(string(65536, 'x')) == msg::CodedType::longString); + }); + then("each crosses the wire whole", [&] { + for (const auto size : {255uz, 256uz, 65535uz, 65536uz, 65537uz, 1000000uz}) { + const string text(size, 'x'); + require(roundTrip(text) == text); + } + }); + }); + given("a UTF-8 character that straddles the 65535-byte boundary", [&] { + const string text = string(65534, 'x') + "\xc3\xa9" + string(10, 'y'); // 'é' occupies bytes 65534 and 65535 + then("it is not cut: the whole string is a longString", [&] { + require(text.size() == 65546); + require(firstCodeOf(text) == msg::CodedType::longString); + require(roundTrip(text) == text); + }); + }); + given("a string whose multi-byte characters take it past 65535 bytes", [&] { + string text; + for (int i = 0; i < 40000; ++i) + text += "\xe2\x82\xac"; // the euro sign, 3 bytes + then("the size counts bytes, not characters", [&] { + require(roundTrip(text) == text); + }); + }); + given("a longString header whose payload is truncated or inconsistent", [&] { + auto decode = [](span bytes) { + string target; + span payload{bytes}; + msg::FunctionCall<>::decodeParameter(target, payload); + }; + const auto long5 = [](uint32_t size, size_t present) { + vector bytes{byte{static_cast(msg::CodedType::longString)}}; + for (int i = 0; i < 4; ++i) + bytes.push_back(byte{static_cast(size >> (8 * i))}); + bytes.insert(bytes.end(), present, byte{'a'}); + return bytes; + }; + then("a header shorter than five bytes is refused", [&] { + const vector header{byte{static_cast(msg::CodedType::longString)}, byte{1}, byte{0}}; + requireThrows([&] { + decode(header); + }); + }); + then("a length that exceeds the bytes present is refused", [&] { + requireThrows([&] { + decode(long5(70000, 69999)); + }); + requireThrows([&] { + decode(long5(0xffffffffu, 10)); + }); + }); + then("the exact length decodes and leaves the cursor after it", [&] { + auto bytes = long5(70000, 70000); + string target; + span payload{bytes}; + msg::FunctionCall<>::decodeParameter(target, payload); + require(target.size() == 70000); + require(payload.empty()); + }); + then("a destination that is not a string is refused", [&] { + auto bytes = long5(5, 5); + int number{}; + span payload{bytes}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(number, payload); + }); + }); + }); + given("a policy whose messages cannot exceed 1 MiB", [&] { + using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024 * 1024>; + msg::FunctionReturn message; + websocket::Frame frame{ + span(reinterpret_cast(message.header().data()), message.header().size())}; + then("a string that fits is encoded", [&] { + message.encodeParameter(string(1024 * 1024 - 8 - 5, 'x'), frame); + require(message.getPayloadSize() == 1024 * 1024 - 8); + }); + then("a string one byte too large throws length_error and leaves the message untouched", [&] { + requireThrows([&] { + message.encodeParameter(string(1024 * 1024 - 8 - 4, 'x'), frame); + }); + require(message.getPayloadSize() == 0); + require(message.getParametersCount() == 0); + require(frame.size() == message.header().size()); + }); + then("the bound counts what the message already carries", [&] { + message.encodeParameter(string(600 * 1024, 'x'), frame); + requireThrows([&] { + message.encodeParameter(string(600 * 1024, 'y'), frame); + }); + }); + }); + given("an exception message longer than 65535 bytes, with a two-byte character across the limit", [&] { + const runtime_error error{string(65534, 'x') + "\xc3\xa9" + string(10, 'y')}; + then("the message is cut before the first character that does not fit whole", [&] { + require(roundTrip(error) == string(65534, 'x')); + }); + }); + }}; namespace { @@ -363,317 +382,396 @@ static_assert(msg::contains_list_v>>); } // namespace -const Scenario listsStrings{"Lists of strings, tuples and arrays are encoded as one list value", [] { - given("an empty list of strings", [&] { - const vector empty; - then("it is the list code and a zero count", [&] { - require(encodedParameter(empty) == listBytes(0, {})); - require(listRoundTrip(empty).empty()); - }); - }); - given("a list with one element, then several of different lengths", [&] { - const vector one{"alpha"}; - const vector several{"", "beta", string(300, 'g'), string(70000, 'd')}; - then("elements keep their order and their own string header", [&] { - require(encodedParameter(one) == listBytes(1, {wireString("alpha")})); - require(listRoundTrip(one) == one); - require(listRoundTrip(several) == several); - }); - then("the list is one parameter, not one per element", [&] { - msg::FunctionReturn<> message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - message.encodeParameter(several, frame); - require(message.getParametersCount() == 1); - }); - }); - given("a list of records mixing strings, numbers, booleans and a Uint8Array", [&] { - using Record = tuple>; - const vector entries{{"a.txt", 12.5, true, {1, 2, 3}}, {"b", 0, false, {}}, {"c", -1, true, vector(300, 7)}}; - then("every field of every record crosses the wire", [&] { - require(listRoundTrip(entries) == entries); - }); - }); - given("a list of typed arrays and a list of bitsets", [&] { - const vector> chunks{{1}, vector(500, 9), {}}; - const vector> bits{bitset<9>{0x181}, bitset<9>{}}; - then("each is an element of its list", [&] { - require(listRoundTrip(chunks) == chunks); - require(listRoundTrip(bits) == bits); - }); - }); - given("a tuple that holds a list, as a page of results with its cursor does", [&] { - const tuple, string> page{{"x", "y"}, "next"}; - then("the list is nested in the tuple, not in a list", [&] { - require(listRoundTrip(page) == page); - }); - }); - given("a list sent by JavaScript as a plain array, hence a tuple", [&] { - vector tupleBytes{byte{static_cast(msg::CodedType::tuple)}, byte{2}}; - for (const auto& element : {wireString("one"), wireString("two")}) - tupleBytes.insert(tupleBytes.end(), element.begin(), element.end()); - then("it decodes into a vector of the same elements", [&] { - require(decodedParameter>(tupleBytes) == vector{"one", "two"}); - }); - then("a tuple of other elements is still refused", [&] { - requireThrows([&] { decodedParameter>(vector{byte{static_cast(msg::CodedType::tuple)}, byte{1}, wireNumber(1)[0], wireNumber(1)[1]}); }); - }); - }); - given("lists that are heterogeneous, truncated or inconsistent", [&] { - then("an element of another type than the first is refused", [&] { - requireThrows([&] { decodedParameter>(listBytes(2, {wireString("a"), wireNumber(1)})); }); - requireThrows([&] { (decodedParameter>>(listBytes(2, {encodedParameter(tuple{"a", 1}), wireString("b")}))); }); - }); - then("a tuple of another arity than the first is refused", [&] { - requireThrows([&] { (decodedParameter>>( - listBytes(2, {encodedParameter(tuple{"a", 1}), encodedParameter(tuple{"b"})}))); }); - }); - then("a list or an exception inside a list is refused", [&] { - requireThrows([&] { decodedParameter>(listBytes(1, {listBytes(0, {})})); }); - const vector exception{byte{static_cast(msg::CodedType::exception)}, byte{1}, byte{0}, byte{'x'}}; - requireThrows([&] { decodedParameter>(listBytes(1, {exception})); }); - }); - then("a count larger than the bytes that follow is refused without allocating for it", [&] { - requireThrows([&] { decodedParameter>(listBytes(0xffffffffu, {wireString("a")})); }); - requireThrows([&] { decodedParameter>(listBytes(3, {wireString("a"), wireString("b")})); }); - }); - then("a header shorter than five bytes, or an element cut short, is refused", [&] { - requireThrows([&] { decodedParameter>(vector{byte{static_cast(msg::CodedType::list)}, byte{1}}); }); - auto cut = listBytes(1, {wireString("abcdef")}); - cut.pop_back(); - requireThrows([&] { decodedParameter>(cut); }); +const Scenario listsStrings{ + "Lists of strings, tuples and arrays are encoded as one list value", + [] { + given("an empty list of strings", [&] { + const vector empty; + then("it is the list code and a zero count", [&] { + require(encodedParameter(empty) == listBytes(0, {})); + require(listRoundTrip(empty).empty()); + }); }); - then("a list decoded into another kind of destination is refused", [&] { - requireThrows([&] { decodedParameter(listBytes(0, {})); }); - requireThrows([&] { decodedParameter>(listBytes(0, {})); }); - requireThrows([&] { decodedParameter>(encodedParameter(vector{1})); }); + given("a list with one element, then several of different lengths", [&] { + const vector one{"alpha"}; + const vector several{"", "beta", string(300, 'g'), string(70000, 'd')}; + then("elements keep their order and their own string header", [&] { + require(encodedParameter(one) == listBytes(1, {wireString("alpha")})); + require(listRoundTrip(one) == one); + require(listRoundTrip(several) == several); + }); + then("the list is one parameter, not one per element", [&] { + msg::FunctionReturn<> message; + websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(several, frame); + require(message.getParametersCount() == 1); + }); }); - }); - given("elements whose values decode into the destination but whose wire shapes differ", [&] { - const auto boolTuple = encodedParameter(tuple{true}); - const auto numberTuple = encodedParameter(tuple{1}); - then("a list of [true] and [1] is refused although a number decodes as a bool", [&] { - requireThrows([&] { decodedParameter>>(listBytes(2, {boolTuple, numberTuple})); }); + given("a list of records mixing strings, numbers, booleans and a Uint8Array", [&] { + using Record = tuple>; + const vector entries{ + {"a.txt", 12.5, true, {1, 2, 3}}, + {"b", 0, false, {}}, + {"c", -1, true, vector(300, 7)} + }; + then("every field of every record crosses the wire", [&] { + require(listRoundTrip(entries) == entries); + }); }); - then("the same holds for a plain JavaScript array, which arrives as a tuple", [&] { - vector asTuple{byte{static_cast(msg::CodedType::tuple)}, byte{2}}; - for (const auto* element : {&boolTuple, &numberTuple}) - asTuple.insert(asTuple.end(), element->begin(), element->end()); - requireThrows([&] { decodedParameter>>(asTuple); }); + given("a list of typed arrays and a list of bitsets", [&] { + const vector> chunks{{1}, vector(500, 9), {}}; + const vector> bits{bitset<9>{0x181}, bitset<9>{}}; + then("each is an element of its list", [&] { + require(listRoundTrip(chunks) == chunks); + require(listRoundTrip(bits) == bits); + }); }); - then("true and false are one shape", [&] { - require(decodedParameter>>(listBytes(2, {boolTuple, encodedParameter(tuple{false})})).size() == 2); + given("a tuple that holds a list, as a page of results with its cursor does", [&] { + const tuple, string> page{ + {"x", "y"}, + "next" + }; + then("the list is nested in the tuple, not in a list", [&] { + require(listRoundTrip(page) == page); + }); }); - then("different fields at the same position are refused, equal shapes with different string headers are accepted", [&] { - requireThrows([&] { (decodedParameter>>( - listBytes(2, {encodedParameter(tuple{"a", 1}), encodedParameter(tuple{2, "b"})}))); }); - const vector> mixed{{"a", 1}, {string(300, 'b'), 2}, {string(70000, 'c'), 3}}; - require(listRoundTrip(mixed) == mixed); + given("a list sent by JavaScript as a plain array, hence a tuple", [&] { + vector tupleBytes{byte{static_cast(msg::CodedType::tuple)}, byte{2}}; + for (const auto& element : {wireString("one"), wireString("two")}) + tupleBytes.insert(tupleBytes.end(), element.begin(), element.end()); + then("it decodes into a vector of the same elements", [&] { + require(decodedParameter>(tupleBytes) == vector{"one", "two"}); + }); + then("a tuple of other elements is still refused", [&] { + requireThrows([&] { + decodedParameter>( + vector{byte{static_cast(msg::CodedType::tuple)}, byte{1}, wireNumber(1)[0], wireNumber(1)[1]}); + }); + }); }); - then("the short and the regular Uint8Array are one shape, other element types are not", [&] { - const vector> bytes{vector(3, 1), vector(300, 2)}; - require(listRoundTrip(bytes) == bytes); - requireThrows([&] { decodedParameter>>(listBytes(2, {encodedParameter(vector{1}), encodedParameter(vector{1})})); }); + given("lists that are heterogeneous, truncated or inconsistent", [&] { + then("an element of another type than the first is refused", [&] { + requireThrows([&] { + decodedParameter>(listBytes(2, {wireString("a"), wireNumber(1)})); + }); + requireThrows([&] { + (decodedParameter>>(listBytes(2, {encodedParameter(tuple{"a", 1}), wireString("b")}))); + }); + }); + then("a tuple of another arity than the first is refused", [&] { + requireThrows([&] { + (decodedParameter>>( + listBytes(2, {encodedParameter(tuple{"a", 1}), encodedParameter(tuple{"b"})}))); + }); + }); + then("a list or an exception inside a list is refused", [&] { + requireThrows([&] { + decodedParameter>(listBytes(1, {listBytes(0, {})})); + }); + const vector exception{byte{static_cast(msg::CodedType::exception)}, byte{1}, byte{0}, byte{'x'}}; + requireThrows([&] { + decodedParameter>(listBytes(1, {exception})); + }); + }); + then("a count larger than the bytes that follow is refused without allocating for it", [&] { + requireThrows([&] { + decodedParameter>(listBytes(0xffffffffu, {wireString("a")})); + }); + requireThrows([&] { + decodedParameter>(listBytes(3, {wireString("a"), wireString("b")})); + }); + }); + then("a header shorter than five bytes, or an element cut short, is refused", [&] { + requireThrows([&] { + decodedParameter>(vector{byte{static_cast(msg::CodedType::list)}, byte{1}}); + }); + auto cut = listBytes(1, {wireString("abcdef")}); + cut.pop_back(); + requireThrows([&] { + decodedParameter>(cut); + }); + }); + then("a list decoded into another kind of destination is refused", [&] { + requireThrows([&] { + decodedParameter(listBytes(0, {})); + }); + requireThrows([&] { + decodedParameter>(listBytes(0, {})); + }); + requireThrows([&] { + decodedParameter>(encodedParameter(vector{1})); + }); + }); }); - }); - given("tuples nested far deeper than any application type", [&] { - // A list whose first element is 100000 tuples of one field each: 2 bytes of header per level. - vector bytes{byte{static_cast(msg::CodedType::list)}, byte{1}, byte{0}, byte{0}, byte{0}}; - for (int level = 0; level < 100000; ++level) { - bytes.push_back(byte{static_cast(msg::CodedType::tuple)}); - bytes.push_back(byte{1}); - } - bytes.push_back(byte{static_cast(msg::CodedType::booleanTrue)}); - then("the shape check refuses them before the stack is at risk", [&] { - requireThrows([&] { decodedParameter>>(bytes); }); + given("elements whose values decode into the destination but whose wire shapes differ", [&] { + const auto boolTuple = encodedParameter(tuple{true}); + const auto numberTuple = encodedParameter(tuple{1}); + then("a list of [true] and [1] is refused although a number decodes as a bool", [&] { + requireThrows([&] { + decodedParameter>>(listBytes(2, {boolTuple, numberTuple})); + }); + }); + then("the same holds for a plain JavaScript array, which arrives as a tuple", [&] { + vector asTuple{byte{static_cast(msg::CodedType::tuple)}, byte{2}}; + for (const auto* element : {&boolTuple, &numberTuple}) + asTuple.insert(asTuple.end(), element->begin(), element->end()); + requireThrows([&] { + decodedParameter>>(asTuple); + }); + }); + then("true and false are one shape", [&] { + require(decodedParameter>>(listBytes(2, {boolTuple, encodedParameter(tuple{false})})).size() == 2); + }); + then("different fields at the same position are refused, equal shapes with different string headers are accepted", [&] { + requireThrows([&] { + (decodedParameter>>( + listBytes(2, {encodedParameter(tuple{"a", 1}), encodedParameter(tuple{2, "b"})}))); + }); + const vector> mixed{ + {"a", 1}, + {string(300, 'b'), 2}, + {string(70000, 'c'), 3} + }; + require(listRoundTrip(mixed) == mixed); + }); + then("the short and the regular Uint8Array are one shape, other element types are not", [&] { + const vector> bytes{vector(3, 1), vector(300, 2)}; + require(listRoundTrip(bytes) == bytes); + requireThrows([&] { + decodedParameter>>(listBytes(2, {encodedParameter(vector{1}), encodedParameter(vector{1})})); + }); + }); }); - }); - given("tuples nested exactly at and just past the shared limit of 32 levels", [&] { - const auto nested = [](int levels) { + given("tuples nested far deeper than any application type", [&] { + // A list whose first element is 100000 tuples of one field each: 2 bytes of header per level. vector bytes{byte{static_cast(msg::CodedType::list)}, byte{1}, byte{0}, byte{0}, byte{0}}; - for (int level = 0; level < levels; ++level) { + for (int level = 0; level < 100000; ++level) { bytes.push_back(byte{static_cast(msg::CodedType::tuple)}); bytes.push_back(byte{1}); } bytes.push_back(byte{static_cast(msg::CodedType::booleanTrue)}); - return bytes; - }; - // The destination only has to be as deep as the wire value for decoding to reach the check: a 33-level destination - // type is refused at compile time by the encoder, so the wire is built by hand. - then("32 levels pass the shape check and 33 are refused", [&] { - using Level32 = tuple>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>; - static_assert(msg::tuple_depth_v == 32); - requireNothrow([&] { decodedParameter>(nested(32)); }); - requireThrows([&] { decodedParameter>(nested(33)); }); + then("the shape check refuses them before the stack is at risk", [&] { + requireThrows([&] { + decodedParameter>>(bytes); + }); + }); + }); + given("tuples nested exactly at and just past the shared limit of 32 levels", [&] { + const auto nested = [](int levels) { + vector bytes{byte{static_cast(msg::CodedType::list)}, byte{1}, byte{0}, byte{0}, byte{0}}; + for (int level = 0; level < levels; ++level) { + bytes.push_back(byte{static_cast(msg::CodedType::tuple)}); + bytes.push_back(byte{1}); + } + bytes.push_back(byte{static_cast(msg::CodedType::booleanTrue)}); + return bytes; + }; + // The destination only has to be as deep as the wire value for decoding to reach the check: a 33-level destination + // type is refused at compile time by the encoder, so the wire is built by hand. + then("32 levels pass the shape check and 33 are refused", [&] { + using Level32 = tuple>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>; + static_assert(msg::tuple_depth_v == 32); + requireNothrow([&] { + decodedParameter>(nested(32)); + }); + requireThrows([&] { + decodedParameter>(nested(33)); + }); + }); }); - }); -}}; + }}; // A scenario of its own: each message and frame holds its policy's buffers, and one function with all of them exceeds // the 64 KiB of stack that the MSVC analysis allows (C6262, #512). -const Scenario listsRespect{"Lists respect the bounds of the buffers policy", [] { - given("a policy whose messages cannot exceed 1 KiB", [&] { - using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024>; - msg::FunctionReturn message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - then("a list that does not fit throws length_error", [&] { - requireThrows([&] { message.encodeParameter(vector(200, string(10, 'x')), frame); }); +const Scenario listsRespect{ + "Lists respect the bounds of the buffers policy", + [] { + given("a policy whose messages cannot exceed 1 KiB", [&] { + using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024>; + msg::FunctionReturn message; + websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; + then("a list that does not fit throws length_error", [&] { + requireThrows([&] { + message.encodeParameter(vector(200, string(10, 'x')), frame); + }); + }); }); - }); - given("a policy whose header buffer is small", [&] { - using TinyPolicy = http::CustomBuffersPolicy<8192, 8192, 64>; - msg::FunctionReturn message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - then("a list with more element headers than the buffer holds overflows explicitly", [&] { - requireThrows([&] { message.encodeParameter(vector(100, "x"), frame); }); + given("a policy whose header buffer is small", [&] { + using TinyPolicy = http::CustomBuffersPolicy<8192, 8192, 64>; + msg::FunctionReturn message; + websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; + then("a list with more element headers than the buffer holds overflows explicitly", [&] { + requireThrows([&] { + message.encodeParameter(vector(100, "x"), frame); + }); + }); }); - }); -}}; + }}; const Scenario typedArray{"A typed array that exactly fills the message size is encoded", [] { - using ExactPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 32>; - msg::FunctionReturn message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - then("its header is counted once", [&] { - const vector bytes(22, 1); // 8 header bytes + 2 + 22 = 32 - requireNothrow([&] { message.encodeParameter(bytes, frame); }); - require(message.getPayloadSize() == 24); - }); - then("one more byte is refused", [&] { - requireThrows([&] { message.encodeParameter(vector(23, 1), frame); }); - }); -}}; + using ExactPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 32>; + msg::FunctionReturn message; + websocket::Frame frame{ + span(reinterpret_cast(message.header().data()), message.header().size())}; + then("its header is counted once", [&] { + const vector bytes(22, 1); // 8 header bytes + 2 + 22 = 32 + requireNothrow([&] { + message.encodeParameter(bytes, frame); + }); + require(message.getPayloadSize() == 24); + }); + then("one more byte is refused", [&] { + requireThrows([&] { + message.encodeParameter(vector(23, 1), frame); + }); + }); + }}; const Scenario exceptionsCarry{"Exceptions carry a code and a message", [] { - auto decodeBoth = [](const vector& bytes) { - string code, message; - span payload{bytes}; - msg::FunctionReturn<>::decodeException(code, message, payload); - require(payload.empty()); - return pair{code, message}; - }; - given("an application error", [&] { - const BridgeError error{"quota:exceeded", "no space left"}; - then("the wire carries the code, then the message", [&] { - const auto bytes = encodedParameter(error); - require(bytes.size() == 2 + 14 + 2 + 13); - require(bytes[0] == byte{static_cast(msg::CodedType::exception)}); - require(bytes[1] == byte{14}); - require(decodeBoth(bytes) == pair{"quota:exceeded", "no space left"}); - }); - then("decoded as a string, the exception is its message", [&] { - require(roundTrip(error) == "no space left"); - }); - }); - given("an ordinary exception", [&] { - then("it is sent with the generic code", [&] { - require(decodeBoth(encodedParameter(runtime_error{"boom"})) == pair{string(bridge_code::generic), "boom"}); - require(decodeBoth(encodedParameter(out_of_range{"gone"})).first == bridge_code::generic); - }); - }); - given("an error of the bridge", [&] { - then("its reserved code crosses the wire", [&] { - require(decodeBoth(encodedParameter(detail::makeBridgeError(bridge_code::cancelled, "stopped"))).first == bridge_code::cancelled); - }); - }); - given("an exception message longer than 65535 bytes", [&] { - then("the code is kept and the message is cut before a character that does not fit", [&] { - const BridgeError error{"big", string(65534, 'x') + "\xc3\xa9" + string(10, 'y')}; - require(decodeBoth(encodedParameter(error)) == pair{"big", string(65534, 'x')}); - }); - }); - given("a truncated exception", [&] { - auto bytes = encodedParameter(BridgeError{"code", "message"}); - then("every cut is refused", [&] { - for (size_t keep = 0; keep < bytes.size(); ++keep) { - const vector cut(bytes.begin(), bytes.begin() + static_cast(keep)); - string code, message; - span payload{cut}; - requireThrows([&] { msg::FunctionReturn<>::decodeException(code, message, payload); }); - } - }); - }); - given("a code that is ill-formed or reserved", [&] { - then("an application cannot build the error", [&] { - requireThrows([&] { BridgeError("", "m"); }); - requireThrows([&] { BridgeError(string(65, 'a'), "m"); }); - requireThrows([&] { BridgeError("with space", "m"); }); - requireThrows([&] { BridgeError("webfront.cancelled", "m"); }); - requireNothrow([&] { BridgeError(string(64, 'a'), "m"); }); - }); - then("a peer's ill-formed code becomes the generic one", [&] { - require(detail::makeBridgeError("bad code", "m").code() == bridge_code::generic); - }); - }); -}}; + auto decodeBoth = [](const vector& bytes) { + string code, message; + span payload{bytes}; + msg::FunctionReturn<>::decodeException(code, message, payload); + require(payload.empty()); + return pair{code, message}; + }; + given("an application error", [&] { + const BridgeError error{"quota:exceeded", "no space left"}; + then("the wire carries the code, then the message", [&] { + const auto bytes = encodedParameter(error); + require(bytes.size() == 2 + 14 + 2 + 13); + require(bytes[0] == byte{static_cast(msg::CodedType::exception)}); + require(bytes[1] == byte{14}); + require(decodeBoth(bytes) == pair{"quota:exceeded", "no space left"}); + }); + then("decoded as a string, the exception is its message", [&] { + require(roundTrip(error) == "no space left"); + }); + }); + given("an ordinary exception", [&] { + then("it is sent with the generic code", [&] { + require(decodeBoth(encodedParameter(runtime_error{"boom"})) + == pair{string(bridge_code::generic), "boom"}); + require(decodeBoth(encodedParameter(out_of_range{"gone"})).first == bridge_code::generic); + }); + }); + given("an error of the bridge", [&] { + then("its reserved code crosses the wire", [&] { + require(decodeBoth(encodedParameter(detail::makeBridgeError(bridge_code::cancelled, "stopped"))).first + == bridge_code::cancelled); + }); + }); + given("an exception message longer than 65535 bytes", [&] { + then("the code is kept and the message is cut before a character that does not fit", [&] { + const BridgeError error{"big", string(65534, 'x') + "\xc3\xa9" + string(10, 'y')}; + require(decodeBoth(encodedParameter(error)) == pair{"big", string(65534, 'x')}); + }); + }); + given("a truncated exception", [&] { + auto bytes = encodedParameter(BridgeError{"code", "message"}); + then("every cut is refused", [&] { + for (size_t keep = 0; keep < bytes.size(); ++keep) { + const vector cut(bytes.begin(), bytes.begin() + static_cast(keep)); + string code, message; + span payload{cut}; + requireThrows([&] { + msg::FunctionReturn<>::decodeException(code, message, payload); + }); + } + }); + }); + given("a code that is ill-formed or reserved", [&] { + then("an application cannot build the error", [&] { + requireThrows([&] { + BridgeError("", "m"); + }); + requireThrows([&] { + BridgeError(string(65, 'a'), "m"); + }); + requireThrows([&] { + BridgeError("with space", "m"); + }); + requireThrows([&] { + BridgeError("webfront.cancelled", "m"); + }); + requireNothrow([&] { + BridgeError(string(64, 'a'), "m"); + }); + }); + then("a peer's ill-formed code becomes the generic one", [&] { + require(detail::makeBridgeError("bad code", "m").code() == bridge_code::generic); + }); + }); + }}; const Scenario functionCallCorrelation{"Function call correlation identifiers", [] { - msg::FunctionCall<> message; - message.setCallId(42); - require(message.getCallId() == 42); - message.reset(); - require(message.getCallId() == 0); -}}; + msg::FunctionCall<> message; + message.setCallId(42); + require(message.getCallId() == 42); + message.reset(); + require(message.getCallId() == 0); + }}; const Scenario numericArrays{"Numeric arrays are encoded and decoded as owning values", [] { - using Net = networking::NetworkingMock; - - auto roundTrip = [](const vector& input) { - msg::FunctionReturn<> message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - networking::SocketMock socket; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(socket, scope); - - message.encodeParameter(input, frame); - ws->write(std::move(frame)); - - websocket::FrameDecoder decoder; - require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); - const auto* decodedMessage = msg::FunctionReturn<>::castFromRawData(decoder.payload()); - auto payload = decodedMessage->payload(); - vector output; - decodedMessage->decodeParameter(output, payload); - require(output == input); - require(payload.empty()); - }; - - roundTrip(vector{}); - roundTrip(vector{0, 1, 127, 255}); - roundTrip(vector{-128, -1, 0, 127}); - roundTrip(vector{0, 1, 65535}); - roundTrip(vector{-32768, -1, 32767}); - roundTrip(vector{0, 1, 0xffffffffu}); - roundTrip(vector{numeric_limits::min(), -1, numeric_limits::max()}); - roundTrip(vector{0, 1, numeric_limits::max()}); - roundTrip(vector{numeric_limits::min(), -1, numeric_limits::max()}); - roundTrip(vector{-1.5F, 0.0F, 42.25F}); - roundTrip(vector{-1.5, 0.0, 42.25}); - -}}; + using Net = networking::NetworkingMock; + + auto roundTrip = [](const vector& input) { + msg::FunctionReturn<> message; + websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; + networking::SocketMock socket; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(socket, scope); + + message.encodeParameter(input, frame); + ws->write(std::move(frame)); + + websocket::FrameDecoder decoder; + require(decoder.parse(span(socket.debugBuffer.data(), socket.bufferIndex))); + const auto* decodedMessage = msg::FunctionReturn<>::castFromRawData(decoder.payload()); + auto payload = decodedMessage->payload(); + vector output; + decodedMessage->decodeParameter(output, payload); + require(output == input); + require(payload.empty()); + }; + + roundTrip(vector{}); + roundTrip(vector{0, 1, 127, 255}); + roundTrip(vector{-128, -1, 0, 127}); + roundTrip(vector{0, 1, 65535}); + roundTrip(vector{-32768, -1, 32767}); + roundTrip(vector{0, 1, 0xffffffffu}); + roundTrip(vector{numeric_limits::min(), -1, numeric_limits::max()}); + roundTrip(vector{0, 1, numeric_limits::max()}); + roundTrip(vector{numeric_limits::min(), -1, numeric_limits::max()}); + roundTrip(vector{-1.5F, 0.0F, 42.25F}); + roundTrip(vector{-1.5, 0.0, 42.25}); + }}; const Scenario uint8Arrays{"Uint8 arrays switch encoding at the compact-length boundary", [] { - using Net = networking::NetworkingMock; - - auto encodedType = [](const Array& input) { - msg::FunctionReturn<> message; - websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; - message.encodeParameter(input, frame); - const auto buffers = frame.toBuffers(); - require(buffers.size() == 4); - const auto type = *reinterpret_cast(buffers[2].data()); - return static_cast(to_integer(type)); - }; - - vector compact(255, 7); - vector regular(256, 9); - array fixedCompact{}; - array fixedRegular{}; - - require(encodedType(compact) == msg::CodedType::smallArrayU8); - require(encodedType(regular) == msg::CodedType::arrayU8); - require(encodedType(fixedCompact) == msg::CodedType::smallArrayU8); - require(encodedType(fixedRegular) == msg::CodedType::arrayU8); -}}; + using Net = networking::NetworkingMock; + + auto encodedType = [](const Array& input) { + msg::FunctionReturn<> message; + websocket::Frame frame{span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(input, frame); + const auto buffers = frame.toBuffers(); + require(buffers.size() == 4); + const auto type = *reinterpret_cast(buffers[2].data()); + return static_cast(to_integer(type)); + }; + + vector compact(255, 7); + vector regular(256, 9); + array fixedCompact{}; + array fixedRegular{}; + + require(encodedType(compact) == msg::CodedType::smallArrayU8); + require(encodedType(regular) == msg::CodedType::arrayU8); + require(encodedType(fixedCompact) == msg::CodedType::smallArrayU8); + require(encodedType(fixedRegular) == msg::CodedType::arrayU8); + }}; namespace { /// Three uint16 elements (1, 2, 3) in an arrayU16 payload, little-endian. @@ -691,197 +789,253 @@ constexpr array threeUint16s{byte{static_cast(msg::CodedType: } // namespace const Scenario numericArraysDecode{"Numeric arrays decode into fixed-size destinations", [] { - array output{}; - span payload{threeUint16s}; - msg::FunctionCall<>::decodeParameter(output, payload); - require(output == array{1, 2, 3}); - require(payload.empty()); -}}; + array output{}; + span payload{threeUint16s}; + msg::FunctionCall<>::decodeParameter(output, payload); + require(output == array{1, 2, 3}); + require(payload.empty()); + }}; const Scenario malformedNumeric{"Malformed numeric array payloads are rejected", [] { - given("A payload shorter than its declared element count", [&] { - vector output; - array truncated{byte{static_cast(msg::CodedType::smallArrayU8)}, byte{2}, byte{1}}; - span payload{truncated}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(output, payload); }); - }); - - given("A fixed-size destination whose length disagrees with the payload", [&] { - array fixed{}; - span payload{threeUint16s}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(fixed, payload); }); - }); - - given("A wire type that does not match the destination element type", [&] { - vector output; - span payload{threeUint16s}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(output, payload); }); - }); - - given("An array header truncated before its length field", [&] { - vector output; - array shortHeader{byte{static_cast(msg::CodedType::arrayU16)}, byte{1}}; - span payload{shortHeader}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(output, payload); }); - }); -}}; + given("A payload shorter than its declared element count", [&] { + vector output; + array truncated{byte{static_cast(msg::CodedType::smallArrayU8)}, byte{2}, byte{1}}; + span payload{truncated}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(output, payload); + }); + }); + + given("A fixed-size destination whose length disagrees with the payload", [&] { + array fixed{}; + span payload{threeUint16s}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(fixed, payload); + }); + }); + + given("A wire type that does not match the destination element type", [&] { + vector output; + span payload{threeUint16s}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(output, payload); + }); + }); + + given("An array header truncated before its length field", [&] { + vector output; + array shortHeader{byte{static_cast(msg::CodedType::arrayU16)}, byte{1}}; + span payload{shortHeader}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(output, payload); + }); + }); + }}; const Scenario decodeParameterRejects{"decodeParameter rejects malformed and mistyped payloads", [] { - auto decodeInto = [](T& target, span bytes) { - span payload{bytes}; - msg::FunctionCall<>::decodeParameter(target, payload); - }; - auto coded = [](msg::CodedType type) { return byte{static_cast(type)}; }; - - given("An empty payload", [&] { - string target; - span payload{}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(target, payload); }); - }); - - given("An unknown coded type", [&] { - string target; - array unknown{byte{0xfe}}; - requireThrows([&] { decodeInto(target, unknown); }); - }); - - given("A value decoded into the wrong destination type", [&] { - // Every mismatch must throw: silently leaving the bytes unconsumed would desynchronise - // the parameters that follow it in the same message. - array boolean{coded(msg::CodedType::booleanTrue)}; - array smallString{coded(msg::CodedType::smallString), byte{0}}; - array number{coded(msg::CodedType::number)}; - array tuple{coded(msg::CodedType::tuple), byte{1}}; - array array8{coded(msg::CodedType::smallArrayU8), byte{0}}; - - string asString; - bool asBool{}; - int asInt{}; - vector asVector; - - requireThrows([&] { decodeInto(asString, boolean); }); - requireThrows([&] { decodeInto(asBool, smallString); }); - requireThrows([&] { decodeInto(asString, number); }); - requireThrows([&] { decodeInto(asInt, tuple); }); - requireThrows([&] { decodeInto(asInt, array8); }); - requireThrows([&] { decodeInto(asVector, boolean); }); - }); - - given("String payloads truncated after their type byte", [&] { - string target; - array smallHeader{coded(msg::CodedType::smallString)}; - array longHeader{coded(msg::CodedType::string), byte{4}}; - array smallBody{coded(msg::CodedType::smallString), byte{8}, byte{'a'}}; - array longBody{coded(msg::CodedType::string), byte{8}, byte{0}, byte{'a'}}; - - requireThrows([&] { decodeInto(target, smallHeader); }); - requireThrows([&] { decodeInto(target, longHeader); }); - requireThrows([&] { decodeInto(target, smallBody); }); - requireThrows([&] { decodeInto(target, longBody); }); - }); - - given("A number payload shorter than a double", [&] { - double target{}; - array shortNumber{coded(msg::CodedType::number), byte{0}, byte{0}, byte{0}}; - requireThrows([&] { decodeInto(target, shortNumber); }); - }); - - given("A tuple whose declared arity differs from the destination", [&] { - tuple target; - array wrongArity{coded(msg::CodedType::tuple), byte{3}}; - array truncatedHeader{coded(msg::CodedType::tuple)}; - requireThrows([&] { decodeInto(target, wrongArity); }); - requireThrows([&] { decodeInto(target, truncatedHeader); }); - }); -}}; + auto decodeInto = [](T& target, span bytes) { + span payload{bytes}; + msg::FunctionCall<>::decodeParameter(target, payload); + }; + auto coded = [](msg::CodedType type) { + return byte{static_cast(type)}; + }; + + given("An empty payload", [&] { + string target; + span payload{}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(target, payload); + }); + }); + + given("An unknown coded type", [&] { + string target; + array unknown{byte{0xfe}}; + requireThrows([&] { + decodeInto(target, unknown); + }); + }); + + given("A value decoded into the wrong destination type", [&] { + // Every mismatch must throw: silently leaving the bytes unconsumed would desynchronise + // the parameters that follow it in the same message. + array boolean{coded(msg::CodedType::booleanTrue)}; + array smallString{coded(msg::CodedType::smallString), byte{0}}; + array number{coded(msg::CodedType::number)}; + array tuple{coded(msg::CodedType::tuple), byte{1}}; + array array8{coded(msg::CodedType::smallArrayU8), byte{0}}; + + string asString; + bool asBool{}; + int asInt{}; + vector asVector; + + requireThrows([&] { + decodeInto(asString, boolean); + }); + requireThrows([&] { + decodeInto(asBool, smallString); + }); + requireThrows([&] { + decodeInto(asString, number); + }); + requireThrows([&] { + decodeInto(asInt, tuple); + }); + requireThrows([&] { + decodeInto(asInt, array8); + }); + requireThrows([&] { + decodeInto(asVector, boolean); + }); + }); + + given("String payloads truncated after their type byte", [&] { + string target; + array smallHeader{coded(msg::CodedType::smallString)}; + array longHeader{coded(msg::CodedType::string), byte{4}}; + array smallBody{coded(msg::CodedType::smallString), byte{8}, byte{'a'}}; + array longBody{coded(msg::CodedType::string), byte{8}, byte{0}, byte{'a'}}; + + requireThrows([&] { + decodeInto(target, smallHeader); + }); + requireThrows([&] { + decodeInto(target, longHeader); + }); + requireThrows([&] { + decodeInto(target, smallBody); + }); + requireThrows([&] { + decodeInto(target, longBody); + }); + }); + + given("A number payload shorter than a double", [&] { + double target{}; + array shortNumber{coded(msg::CodedType::number), byte{0}, byte{0}, byte{0}}; + requireThrows([&] { + decodeInto(target, shortNumber); + }); + }); + + given("A tuple whose declared arity differs from the destination", [&] { + tuple target; + array wrongArity{coded(msg::CodedType::tuple), byte{3}}; + array truncatedHeader{coded(msg::CodedType::tuple)}; + requireThrows([&] { + decodeInto(target, wrongArity); + }); + requireThrows([&] { + decodeInto(target, truncatedHeader); + }); + }); + }}; const Scenario bufferOverflow{"BufferOverflow", [] { - using Net = networking::NetworkingMock; - using TinyPolicy = http::CustomBuffersPolicy<8192, 8192, 12>; - - given("A FunctionCall with a tiny buffer", [&] { - msg::FunctionCall message; - websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; - - when("Number overflows the buffer", [&] { - message.encodeParameter("fn", frame); // 2 bytes in buffer (type + uint8 size) - message.encodeParameter(1, frame); // 9 bytes in buffer (type + double) → total 11 - - then("Next number overflows", [&] { - requireThrows([&] { message.encodeParameter(2, frame); }); - }); - }); - - when("Boolean overflows the buffer", [&] { - message.encodeParameter("fn", frame); // 2 bytes → total 2 - message.encodeParameter(1, frame); // 9 bytes → total 11 - message.encodeParameter(true, frame); // 1 byte → total 12 (exactly full) - - then("Next boolean overflows", [&] { - requireThrows([&] { message.encodeParameter(false, frame); }); - }); - }); - - when("String header overflows the buffer", [&] { - message.encodeParameter("fn", frame); // 2 bytes → total 2 - message.encodeParameter(1, frame); // 9 bytes → total 11 - - then("Next string header overflows", [&] { - requireThrows([&] { message.encodeParameter("x", frame); }); - }); - }); - }); -}}; + using Net = networking::NetworkingMock; + using TinyPolicy = http::CustomBuffersPolicy<8192, 8192, 12>; + + given("A FunctionCall with a tiny buffer", [&] { + msg::FunctionCall message; + websocket::Frame frame{ + std::span(reinterpret_cast(message.header().data()), message.header().size())}; + + when("Number overflows the buffer", [&] { + message.encodeParameter("fn", frame); // 2 bytes in buffer (type + uint8 size) + message.encodeParameter(1, frame); // 9 bytes in buffer (type + double) → total 11 + + then("Next number overflows", [&] { + requireThrows([&] { + message.encodeParameter(2, frame); + }); + }); + }); + + when("Boolean overflows the buffer", [&] { + message.encodeParameter("fn", frame); // 2 bytes → total 2 + message.encodeParameter(1, frame); // 9 bytes → total 11 + message.encodeParameter(true, frame); // 1 byte → total 12 (exactly full) + + then("Next boolean overflows", [&] { + requireThrows([&] { + message.encodeParameter(false, frame); + }); + }); + }); + + when("String header overflows the buffer", [&] { + message.encodeParameter("fn", frame); // 2 bytes → total 2 + message.encodeParameter(1, frame); // 9 bytes → total 11 + + then("Next string header overflows", [&] { + requireThrows([&] { + message.encodeParameter("x", frame); + }); + }); + }); + }); + }}; const Scenario emptyWire{"Empty wire strings are decoded without indexing past the input", [] { - for (auto bytes : { - std::vector{std::byte{4}, std::byte{0}}, - std::vector{std::byte{5}, std::byte{0}, std::byte{0}} - }) { - std::span input(bytes); - std::string value = "previous"; - msg::FunctionCall<>::decodeParameter(value, input); - require(value.empty()); - require(input.empty()); - } -}}; + for (auto bytes : { + std::vector{std::byte{4}, std::byte{0}}, + std::vector{std::byte{5}, std::byte{0}, std::byte{0}} + }) { + std::span input(bytes); + std::string value = "previous"; + msg::FunctionCall<>::decodeParameter(value, input); + require(value.empty()); + require(input.empty()); + } + }}; const Scenario wireNumbers{"Wire numbers outside an integer result range are rejected", [] { - for (double number : {std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN(), 2147483648.0, -2147483649.0}) { - std::array bytes{std::byte{3}}; - std::memcpy(bytes.data() + 1, &number, sizeof(number)); - std::span input(bytes); - int value{}; - requireThrows([&] { msg::FunctionCall<>::decodeParameter(value, input); }); - } -}}; + for (double number : + {std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN(), 2147483648.0, -2147483649.0}) { + std::array bytes{std::byte{3}}; + std::memcpy(bytes.data() + 1, &number, sizeof(number)); + std::span input(bytes); + int value{}; + requireThrows([&] { + msg::FunctionCall<>::decodeParameter(value, input); + }); + } + }}; const Scenario wireInteger{"Wire integer conversion keeps truncation and handles 64-bit boundaries", [] { - auto decode = [](double number, T& value) { - std::array bytes{std::byte{3}}; - std::memcpy(bytes.data() + 1, &number, sizeof(number)); - std::span input(bytes); - msg::FunctionCall<>::decodeParameter(value, input); - require(input.empty()); - }; - int value{}; - decode(42.75, value); - require(value == 42); - decode(-42.75, value); - require(value == -42); - decode(2147483647.75, value); - require(value == std::numeric_limits::max()); - - std::uint64_t unsignedValue{}; - requireThrows([&] { decode(18446744073709551616.0, unsignedValue); }); - requireThrows([&] { decode(-1.0, unsignedValue); }); - decode(9223372036854775808.0, unsignedValue); - require(unsignedValue == (std::uint64_t{1} << 63)); - std::int64_t signedValue{}; - requireThrows([&] { decode(9223372036854775808.0, signedValue); }); - decode(-9223372036854775808.0, signedValue); - require(signedValue == std::numeric_limits::min()); -}}; + auto decode = [](double number, T& value) { + std::array bytes{std::byte{3}}; + std::memcpy(bytes.data() + 1, &number, sizeof(number)); + std::span input(bytes); + msg::FunctionCall<>::decodeParameter(value, input); + require(input.empty()); + }; + int value{}; + decode(42.75, value); + require(value == 42); + decode(-42.75, value); + require(value == -42); + decode(2147483647.75, value); + require(value == std::numeric_limits::max()); + + std::uint64_t unsignedValue{}; + requireThrows([&] { + decode(18446744073709551616.0, unsignedValue); + }); + requireThrows([&] { + decode(-1.0, unsignedValue); + }); + decode(9223372036854775808.0, unsignedValue); + require(unsignedValue == (std::uint64_t{1} << 63)); + std::int64_t signedValue{}; + requireThrows([&] { + decode(9223372036854775808.0, signedValue); + }); + decode(-9223372036854775808.0, signedValue); + require(signedValue == std::numeric_limits::min()); + }}; namespace { template @@ -903,7 +1057,7 @@ vector bitsetPayload(const Values&... values) { template void expectPackedBitsetBytes(span bytes, const bitset& input) { - constexpr size_t count = N / 8 + (N % 8 != 0); + constexpr size_t count = N / 8 + (N % 8 != 0); constexpr size_t header = count < 256 ? 2 : 5; if constexpr (N != 0) for (size_t b = 0; b < count; ++b) { @@ -917,143 +1071,147 @@ void expectPackedBitsetBytes(span bytes, const bitset& input) { } // namespace const Scenario bitsetsUse{"Bitsets use canonical packed Uint8Array bytes at every size boundary", [] { - auto check = []() { - bitset input; - if constexpr (N != 0) - for (size_t i = 0; i < N; ++i) - input[i] = i % 3 == 0 || i + 1 == N; - const auto bytes = bitsetPayload(input); - constexpr size_t count = N / 8 + (N % 8 != 0); - constexpr size_t header = count < 256 ? 2 : 5; - require(bytes.size() == header + count); - require(bytes[0] == byte(count < 256 ? msg::CodedType::smallArrayU8 : msg::CodedType::arrayU8)); - uint32_t length{}; - if constexpr (count < 256) - length = to_integer(bytes[1]); - else - memcpy(&length, bytes.data() + 1, sizeof(length)); - require(length == count); - expectPackedBitsetBytes(span{bytes}, input); - span data{bytes}; - bitset output; - output.set(); - msg::FunctionReturn<>::decodeParameter(output, data); - // Boolean assertions avoid MSVC STL stream diagnostics for bitset<0>. - require((output == input)); - require(data.empty()); - // All-one and all-zero patterns also exercise the partial last byte. - input.set(); - const auto ones = bitsetPayload(input); - data = ones; - msg::FunctionReturn<>::decodeParameter(output, data); - require((output == input)); - input.reset(); - const auto zeros = bitsetPayload(input); - data = zeros; - msg::FunctionReturn<>::decodeParameter(output, data); - require(output.none()); - }; - check.template operator()<0>(); - check.template operator()<1>(); - check.template operator()<7>(); - check.template operator()<8>(); - check.template operator()<9>(); - check.template operator()<63>(); - check.template operator()<64>(); - check.template operator()<65>(); - check.template operator()<1024>(); - check.template operator()<2040>(); - check.template operator()<2048>(); - require(bitsetPayload(bitset<9>{0x181}) == vector{byte(msg::CodedType::smallArrayU8), byte{2}, byte{0x81}, byte{1}}); -}}; + auto check = []() { + bitset input; + if constexpr (N != 0) + for (size_t i = 0; i < N; ++i) + input[i] = i % 3 == 0 || i + 1 == N; + const auto bytes = bitsetPayload(input); + constexpr size_t count = N / 8 + (N % 8 != 0); + constexpr size_t header = count < 256 ? 2 : 5; + require(bytes.size() == header + count); + require(bytes[0] == byte(count < 256 ? msg::CodedType::smallArrayU8 : msg::CodedType::arrayU8)); + uint32_t length{}; + if constexpr (count < 256) + length = to_integer(bytes[1]); + else + memcpy(&length, bytes.data() + 1, sizeof(length)); + require(length == count); + expectPackedBitsetBytes(span{bytes}, input); + span data{bytes}; + bitset output; + output.set(); + msg::FunctionReturn<>::decodeParameter(output, data); + // Boolean assertions avoid MSVC STL stream diagnostics for bitset<0>. + require((output == input)); + require(data.empty()); + // All-one and all-zero patterns also exercise the partial last byte. + input.set(); + const auto ones = bitsetPayload(input); + data = ones; + msg::FunctionReturn<>::decodeParameter(output, data); + require((output == input)); + input.reset(); + const auto zeros = bitsetPayload(input); + data = zeros; + msg::FunctionReturn<>::decodeParameter(output, data); + require(output.none()); + }; + check.template operator()<0>(); + check.template operator()<1>(); + check.template operator()<7>(); + check.template operator()<8>(); + check.template operator()<9>(); + check.template operator()<63>(); + check.template operator()<64>(); + check.template operator()<65>(); + check.template operator()<1024>(); + check.template operator()<2040>(); + check.template operator()<2048>(); + require(bitsetPayload(bitset<9>{0x181}) == vector{byte(msg::CodedType::smallArrayU8), byte{2}, byte{0x81}, byte{1}}); + }}; const Scenario packedBitsetsScenario{"Packed bitsets retain owned bytes, tuple counts and the decoder cursor", [] { - const auto expected = tuple{ - bitset<9>{0x181}, - tuple{bitset<0>{}, bitset<65>{9}}, - string("tail") - }; - const auto bytes = bitsetPayload(expected, bitset<8>{0xa5}, 42); - span data{bytes}; - remove_cvref_t output{}; - msg::FunctionReturn<>::decodeParameter(output, data); - require((output == expected)); - bitset<8> bits; - msg::FunctionReturn<>::decodeParameter(bits, data); - require(bits.to_ulong() == 0xa5); - int tail{}; - msg::FunctionReturn<>::decodeParameter(tail, data); - require(tail == 42); - require(data.empty()); -}}; + const auto expected = tuple{ + bitset<9>{0x181}, + tuple{bitset<0>{}, bitset<65>{9}}, + string("tail") + }; + const auto bytes = bitsetPayload(expected, bitset<8>{0xa5}, 42); + span data{bytes}; + remove_cvref_t output{}; + msg::FunctionReturn<>::decodeParameter(output, data); + require((output == expected)); + bitset<8> bits; + msg::FunctionReturn<>::decodeParameter(bits, data); + require(bits.to_ulong() == 0xa5); + int tail{}; + msg::FunctionReturn<>::decodeParameter(tail, data); + require(tail == 42); + require(data.empty()); + }}; const Scenario bitsetDecoding{"Bitset decoding rejects wrong types, lengths, padding and truncation", [] { - const auto valid = bitsetPayload(bitset<9>{0x181}); - auto reject = [](const vector& bytes) { - span data{bytes}; - bitset<9> output{7}; - requireThrows([&] { msg::FunctionReturn<>::decodeParameter(output, data); }); - require(output.to_ulong() == 7); - require(data.size() == bytes.size()); - }; - for (size_t size = 0; size < valid.size(); ++size) - reject(vector(valid.begin(), valid.begin() + static_cast(size))); - for (auto count : {0, 1, 3}) { - auto wrong = valid; - wrong[1] = byte(count); - reject(wrong); - } - auto padding = valid; - padding.back() = byte{3}; - reject(padding); - reject(bitsetPayload(vector{1, 0})); - reject(bitsetPayload(vector{1, 0})); - reject(bitsetPayload(string("01"))); - reject(bitsetPayload(true)); - reject(bitsetPayload(3)); - reject(bitsetPayload(tuple{1, 2})); - // A regular U8 header is valid even for a small destination. - vector regular{byte(msg::CodedType::arrayU8), byte{2}, byte{}, byte{}, byte{}, byte{0x81}, byte{1}}; - uint32_t count = 2; - memcpy(regular.data() + 1, &count, sizeof(count)); - for (size_t size = 1; size < regular.size(); ++size) - reject(vector(regular.begin(), regular.begin() + static_cast(size))); - bitset<9> output; - span data{regular}; - msg::FunctionReturn<>::decodeParameter(output, data); - require(output.to_ulong() == 0x181); - require(data.empty()); -}}; - -const Scenario encodingBridge{"Encoding bridge messages writes nothing to the standard output", [] { - given("the standard output captured while a call and a return are encoded with every scalar kind", [&] { - ostringstream captured; - auto* previous = cout.rdbuf(captured.rdbuf()); - try { - // The frame refers to the encoded strings, which therefore outlive it. Messages and frames own their buffers - // inline: on the heap, since MSVC rejects a test function of 66 KB of stack (C6262). - using Frame = websocket::Frame; - const string name("echo"), small(16, 'x'), large(1024, 'x'); - const runtime_error failure("failure"); - const tuple pair{1, "tuple"}; - const auto call = make_unique>(); - const auto callFrame = make_unique(span(reinterpret_cast(call->header().data()), call->header().size())); - call->encodeParameter(name, *callFrame); - call->encodeParameter(small, *callFrame); - call->encodeParameter(large, *callFrame); - call->encodeParameter(true, *callFrame); - call->encodeParameter(42.5, *callFrame); - const auto result = make_unique>(); - const auto resultFrame = make_unique(span(reinterpret_cast(result->header().data()), result->header().size())); - result->encodeParameter(failure, *resultFrame); - result->encodeParameter(pair, *resultFrame); - } catch (...) { + const auto valid = bitsetPayload(bitset<9>{0x181}); + auto reject = [](const vector& bytes) { + span data{bytes}; + bitset<9> output{7}; + requireThrows([&] { + msg::FunctionReturn<>::decodeParameter(output, data); + }); + require(output.to_ulong() == 7); + require(data.size() == bytes.size()); + }; + for (size_t size = 0; size < valid.size(); ++size) + reject(vector(valid.begin(), valid.begin() + static_cast(size))); + for (auto count : {0, 1, 3}) { + auto wrong = valid; + wrong[1] = byte(count); + reject(wrong); + } + auto padding = valid; + padding.back() = byte{3}; + reject(padding); + reject(bitsetPayload(vector{1, 0})); + reject(bitsetPayload(vector{1, 0})); + reject(bitsetPayload(string("01"))); + reject(bitsetPayload(true)); + reject(bitsetPayload(3)); + reject(bitsetPayload(tuple{1, 2})); + // A regular U8 header is valid even for a small destination. + vector regular{byte(msg::CodedType::arrayU8), byte{2}, byte{}, byte{}, byte{}, byte{0x81}, byte{1}}; + uint32_t count = 2; + memcpy(regular.data() + 1, &count, sizeof(count)); + for (size_t size = 1; size < regular.size(); ++size) + reject(vector(regular.begin(), regular.begin() + static_cast(size))); + bitset<9> output; + span data{regular}; + msg::FunctionReturn<>::decodeParameter(output, data); + require(output.to_ulong() == 0x181); + require(data.empty()); + }}; + +const Scenario encodingBridge{ + "Encoding bridge messages writes nothing to the standard output", + [] { + given("the standard output captured while a call and a return are encoded with every scalar kind", [&] { + ostringstream captured; + auto* previous = cout.rdbuf(captured.rdbuf()); + try { + // The frame refers to the encoded strings, which therefore outlive it. Messages and frames own their buffers + // inline: on the heap, since MSVC rejects a test function of 66 KB of stack (C6262). + using Frame = websocket::Frame; + const string name("echo"), small(16, 'x'), large(1024, 'x'); + const runtime_error failure("failure"); + const tuple pair{1, "tuple"}; + const auto call = make_unique>(); + const auto callFrame = make_unique(span(reinterpret_cast(call->header().data()), call->header().size())); + call->encodeParameter(name, *callFrame); + call->encodeParameter(small, *callFrame); + call->encodeParameter(large, *callFrame); + call->encodeParameter(true, *callFrame); + call->encodeParameter(42.5, *callFrame); + const auto result = make_unique>(); + const auto resultFrame = make_unique(span(reinterpret_cast(result->header().data()), result->header().size())); + result->encodeParameter(failure, *resultFrame); + result->encodeParameter(pair, *resultFrame); + } catch (...) { + cout.rdbuf(previous); + throw; + } cout.rdbuf(previous); - throw; - } - cout.rdbuf(previous); - then("the encoder printed nothing (the HTML bridge paid for console output on every message)", [&] { - require(captured.str().empty()); + then("the encoder printed nothing (the HTML bridge paid for console output on every message)", [&] { + require(captured.str().empty()); + }); }); - }); -}}; + }}; diff --git a/test/unit/MimeTypeTests.cpp b/test/unit/MimeTypeTests.cpp index fb9123a4..6de3b6d9 100644 --- a/test/unit/MimeTypeTests.cpp +++ b/test/unit/MimeTypeTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include @@ -8,48 +8,48 @@ using namespace webfront::bdd; using namespace webfront::http; const Scenario mimeTypes{"MimeTypes", [] { - require(MimeType::fromExtension("jpg").type == MimeType::jpg); - require(MimeType::fromExtension("js").type == MimeType::js); - require(MimeType::fromExtension("mjs").type == MimeType::js); - require(MimeType::fromExtension("css").type == MimeType::css); - require(MimeType::fromExtension("png").type == MimeType::png); - require(MimeType::fromExtension("json").type == MimeType::json); - require(MimeType::fromExtension("ttf").type == MimeType::ttf); - require(MimeType::fromExtension("svg").type == MimeType::svg); - require(MimeType::fromExtension("csv").type == MimeType::csv); + require(MimeType::fromExtension("jpg").type == MimeType::jpg); + require(MimeType::fromExtension("js").type == MimeType::js); + require(MimeType::fromExtension("mjs").type == MimeType::js); + require(MimeType::fromExtension("css").type == MimeType::css); + require(MimeType::fromExtension("png").type == MimeType::png); + require(MimeType::fromExtension("json").type == MimeType::json); + require(MimeType::fromExtension("ttf").type == MimeType::ttf); + require(MimeType::fromExtension("svg").type == MimeType::svg); + require(MimeType::fromExtension("csv").type == MimeType::csv); - require(std::string(MimeType::fromExtension("html").toString()) == "text/html"); - require(std::string(MimeType::fromExtension("htm").toString()) == "text/html"); - require(std::string(MimeType::fromExtension("bozo").toString()) == "text/plain"); - require(std::string(MimeType::fromExtension("gif").toString()) == "image/gif"); + require(std::string(MimeType::fromExtension("html").toString()) == "text/html"); + require(std::string(MimeType::fromExtension("htm").toString()) == "text/html"); + require(std::string(MimeType::fromExtension("bozo").toString()) == "text/plain"); + require(std::string(MimeType::fromExtension("gif").toString()) == "image/gif"); - require(std::string(MimeType("pdf").toString()) == "application/pdf"); - require(std::string(MimeType(".ico").toString()) == "image/x-icon"); - require(std::string(MimeType(".webp").toString()) == "image/webp"); - require(std::string(MimeType("webp").toString()) == "image/webp"); -}}; + require(std::string(MimeType("pdf").toString()) == "application/pdf"); + require(std::string(MimeType(".ico").toString()) == "image/x-icon"); + require(std::string(MimeType(".webp").toString()) == "image/webp"); + require(std::string(MimeType("webp").toString()) == "image/webp"); + }}; const Scenario everyMIME{"Every MIME type has its own name", [] { - given("each extension and the content type a browser expects for it", [&] { - const std::pair types[]{ - { "txt", "text/plain"}, - {"html", "text/html"}, - { "css", "text/css"}, - { "js", "application/javascript"}, - { "jpg", "image/jpeg"}, - { "png", "image/png"}, - { "gif", "image/gif"}, - {"json", "application/json"}, - { "pdf", "application/pdf"}, - { "ttf", "font/ttf"}, - { "ico", "image/x-icon"}, - { "svg", "image/svg+xml"}, - {"webp", "image/webp"}, - { "csv", "text/csv"}, - {"wasm", "application/wasm"}, - }; - for (const auto& [extension, contentType] : types) - then(extension + " is served as " + contentType, [&] { - require(std::string(MimeType::fromExtension(extension).toString()) == contentType); - }); - }); -}}; + given("each extension and the content type a browser expects for it", [&] { + const std::pair types[]{ + { "txt", "text/plain"}, + {"html", "text/html"}, + { "css", "text/css"}, + { "js", "application/javascript"}, + { "jpg", "image/jpeg"}, + { "png", "image/png"}, + { "gif", "image/gif"}, + {"json", "application/json"}, + { "pdf", "application/pdf"}, + { "ttf", "font/ttf"}, + { "ico", "image/x-icon"}, + { "svg", "image/svg+xml"}, + {"webp", "image/webp"}, + { "csv", "text/csv"}, + {"wasm", "application/wasm"}, + }; + for (const auto& [extension, contentType] : types) + then(extension + " is served as " + contentType, [&] { + require(std::string(MimeType::fromExtension(extension).toString()) == contentType); + }); + }); + }}; diff --git a/test/unit/Mocks.hpp b/test/unit/Mocks.hpp index 0548a6dc..87d452f4 100644 --- a/test/unit/Mocks.hpp +++ b/test/unit/Mocks.hpp @@ -17,13 +17,15 @@ struct NoNames { static inline std::list names{}; }; -template +template struct MockFileSystem { - MockFileSystem(std::filesystem::path docRoot) { root = docRoot; }; + MockFileSystem(std::filesystem::path docRoot) { + root = docRoot; + }; struct Data { static constexpr std::array data{0}; - static constexpr size_t dataSize{0}; - static constexpr std::string_view encoding{"br"}; + static constexpr size_t dataSize{0}; + static constexpr std::string_view encoding{"br"}; }; std::optional open(std::filesystem::path file) { @@ -35,6 +37,6 @@ struct MockFileSystem { return {}; } - inline static auto openingsCounter = 0; + inline static auto openingsCounter = 0; inline static std::filesystem::path root; }; diff --git a/test/unit/ModuleHTTPServerTests.cpp b/test/unit/ModuleHTTPServerTests.cpp index 306946a5..677e64ef 100644 --- a/test/unit/ModuleHTTPServerTests.cpp +++ b/test/unit/ModuleHTTPServerTests.cpp @@ -1,7 +1,7 @@ #include "Mocks.hpp" -#include #include #include +#include #include #include @@ -26,13 +26,12 @@ struct ModuleFile { struct GzipModuleData { static constexpr std::string_view encoding{"gzip"}; static constexpr std::size_t dataSize{55}; - static constexpr std::array data{ - 0x1f8b080000000000, 0x02ff4bad28c82f2a, 0x5148cecf2b2e5148, 0xcc2b2e4f2d52b055, - 0x3031b2e64a1d9519, 0x95199519613200fb, 0x95b0441004000000}; + static constexpr std::array + data{0x1f8b080000000000, 0x02ff4bad28c82f2a, 0x5148cecf2b2e5148, 0xcc2b2e4f2d52b055, 0x3031b2e64a1d9519, 0x95199519613200fb, 0x95b0441004000000}; }; struct GzipModuleFS { - explicit GzipModuleFS(std::filesystem::path) { } + explicit GzipModuleFS(std::filesystem::path) {} static std::optional open(std::filesystem::path file) { if (file.relative_path().generic_string() == "modules/answer.mjs") @@ -50,56 +49,58 @@ std::string decodedModule() { } // namespace const Scenario requestHandlerServes{"RequestHandler serves JavaScript modules", [] { - std::string input{"GET /modules/main.mjs HTTP/1.1\r\nHost: localhost\r\nAccept-encoding: gzip, br, deflate\r\n\r\n"}; - Request request; - requireNothrow([&] { request.parseSomeData(input.cbegin(), input.cend()); }); + std::string input{"GET /modules/main.mjs HTTP/1.1\r\nHost: localhost\r\nAccept-encoding: gzip, br, deflate\r\n\r\n"}; + Request request; + requireNothrow([&] { + request.parseSomeData(input.cbegin(), input.cend()); + }); - RequestHandler> handler{"."}; - auto response = handler.handleRequest(request); + RequestHandler> handler{"."}; + auto response = handler.handleRequest(request); - require(response.statusCode == Response::ok); - require(response.getHeaderValue("Content-Encoding") == "br"); - require(response.getHeaderValue("Content-Type") == "application/javascript"); - require(response.getHeaderValue("Content-Length") == "0"); -}}; + require(response.statusCode == Response::ok); + require(response.getHeaderValue("Content-Encoding") == "br"); + require(response.getHeaderValue("Content-Type") == "application/javascript"); + require(response.getHeaderValue("Content-Length") == "0"); + }}; // WebKit does not advertise Brotli over loopback HTTP. const Scenario embeddedGzip{"Embedded gzip assets are served to gzip-only HTTP clients", [] { - RequestHandler handler{"."}; - when("the client requests the module without Brotli support", [&] { - const std::string input = "GET /modules/answer.mjs HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip, deflate\r\n\r\n"; - Request request; - request.parseSomeData(input.begin(), input.end()); - auto response = handler.handleRequest(request); - then("the stored gzip bytes are returned", [&] { - require(response.statusCode == Response::ok); - require(response.getHeaderValue("Content-Encoding") == "gzip"); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); - require(response.content.size() == GzipModuleData::dataSize); - require(response.getHeaderValue("Content-Type") == "application/javascript"); - }); - }); -}}; + RequestHandler handler{"."}; + when("the client requests the module without Brotli support", [&] { + const std::string input = "GET /modules/answer.mjs HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip, deflate\r\n\r\n"; + Request request; + request.parseSomeData(input.begin(), input.end()); + auto response = handler.handleRequest(request); + then("the stored gzip bytes are returned", [&] { + require(response.statusCode == Response::ok); + require(response.getHeaderValue("Content-Encoding") == "gzip"); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + require(response.getHeaderValue("Content-Length") == std::to_string(response.content.size())); + require(response.content.size() == GzipModuleData::dataSize); + require(response.getHeaderValue("Content-Type") == "application/javascript"); + }); + }); + }}; const Scenario embeddedGzipAssets{"Embedded gzip assets are served to identity-only HTTP clients", [] { - RequestHandler handler{"."}; - const auto expected = decodedModule(); - for (const auto accept : {"", "Accept-Encoding: identity\r\n", "Accept-Encoding: gzip;q=0, identity;q=1\r\n"}) { - when("the client requests identity with ", accept, [&] { - const auto input = std::string("GET /modules/answer.mjs HTTP/1.1\r\nHost: localhost\r\n") + accept + "\r\n"; - Request request; - request.parseSomeData(input.begin(), input.end()); - auto response = handler.handleRequest(request); - then("the server returns the decoded bytes with their decoded length", [&] { - require(response.statusCode == Response::ok); - require(!response.getHeaderValue("Content-Encoding")); - require(response.getHeaderValue("Content-Length") == std::to_string(expected.size())); - require(response.content == expected); - require(response.getHeaderValue("Content-Type") == "application/javascript"); - require(response.getHeaderValue("Vary") == "Accept-Encoding"); - }); - }); - } -}}; + RequestHandler handler{"."}; + const auto expected = decodedModule(); + for (const auto accept : {"", "Accept-Encoding: identity\r\n", "Accept-Encoding: gzip;q=0, identity;q=1\r\n"}) { + when("the client requests identity with ", accept, [&] { + const auto input = std::string("GET /modules/answer.mjs HTTP/1.1\r\nHost: localhost\r\n") + accept + "\r\n"; + Request request; + request.parseSomeData(input.begin(), input.end()); + auto response = handler.handleRequest(request); + then("the server returns the decoded bytes with their decoded length", [&] { + require(response.statusCode == Response::ok); + require(!response.getHeaderValue("Content-Encoding")); + require(response.getHeaderValue("Content-Length") == std::to_string(expected.size())); + require(response.content == expected); + require(response.getHeaderValue("Content-Type") == "application/javascript"); + require(response.getHeaderValue("Vary") == "Accept-Encoding"); + }); + }); + } + }}; diff --git a/test/unit/NativeFSTests.cpp b/test/unit/NativeFSTests.cpp index c1bc1d31..0b0fecad 100644 --- a/test/unit/NativeFSTests.cpp +++ b/test/unit/NativeFSTests.cpp @@ -1,7 +1,5 @@ -#include #include "TemporaryDirectory.hpp" #include - #include #include @@ -25,12 +23,11 @@ using DebugFS = fs::NativeDebugFS; class TemporaryTestEnvironment { public: TemporaryTestEnvironment() : testDir(root.path()) { - // Create subdirectory subDir = testDir / "subdir"; filesystem::create_directories(subDir); } - + ~TemporaryTestEnvironment() { try { filesystem::remove_all(testDir); @@ -38,371 +35,389 @@ class TemporaryTestEnvironment { cerr << "Warning: Failed to clean up test directory: " << e.what() << endl; } } - + // Create a text file with specific content filesystem::path createTextFile(const string& relativePath, const string& content) { filesystem::path filePath = testDir / relativePath; - ofstream file(filePath, ios::out); + ofstream file(filePath, ios::out); file << content; file.close(); return filePath; } - + // Create a binary file with random content filesystem::path createBinaryFile(const string& relativePath, size_t size) { filesystem::path filePath = testDir / relativePath; - ofstream file(filePath, ios::binary); - + ofstream file(filePath, ios::binary); + // Generate random bytes - vector data(size); - random_device rd; - mt19937 gen(rd()); + vector data(size); + random_device rd; + mt19937 gen(rd()); uniform_int_distribution<> distrib(0, 255); - + for (auto& byte : data) { byte = static_cast(distrib(gen)); } - + file.write(reinterpret_cast(data.data()), static_cast(size)); file.close(); - + binaryData[relativePath] = std::move(data); return filePath; } - - filesystem::path getTestDir() const { return testDir; } - filesystem::path getSubDir() const { return subDir; } - + + filesystem::path getTestDir() const { + return testDir; + } + filesystem::path getSubDir() const { + return subDir; + } + const vector& getBinaryData(const string& relativePath) const { return binaryData.at(relativePath); } - + private: webfront::test::TemporaryDirectory root; - filesystem::path testDir; - filesystem::path subDir; - map> binaryData; + filesystem::path testDir; + filesystem::path subDir; + map> binaryData; }; namespace { - std::string normaliseNewlines(const std::string& s) { - std::string out; - out.reserve(s.size()); - for (size_t i = 0; i < s.size(); ++i) { - if (s[i] == '\r') { - if (i + 1 < s.size() && s[i + 1] == '\n') continue; // skip, handled by \n - } - out += s[i]; +std::string normaliseNewlines(const std::string& s) { + std::string out; + out.reserve(s.size()); + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '\r') { + if (i + 1 < s.size() && s[i + 1] == '\n') + continue; // skip, handled by \n } - return out; + out += s[i]; } + return out; +} - void checkFileRead(DebugFS& debugFS, const std::string& filename, const std::string& expectedContent) { - auto file = debugFS.open(filename); - require(file.has_value()); - require(!file->isEncoded()); - std::array buffer; - auto bytesRead = file->read(buffer); - std::string content(buffer.data(), bytesRead); - require(normaliseNewlines(content) == normaliseNewlines(expectedContent)); - require(file->eof()); - } +void checkFileRead(DebugFS& debugFS, const std::string& filename, const std::string& expectedContent) { + auto file = debugFS.open(filename); + require(file.has_value()); + require(!file->isEncoded()); + std::array buffer; + auto bytesRead = file->read(buffer); + std::string content(buffer.data(), bytesRead); + require(normaliseNewlines(content) == normaliseNewlines(expectedContent)); + require(file->eof()); } +} // namespace const Scenario nativeDebugFSProvides{"NativeDebugFS provides access to local files", [] { - given("A local file", [&] { - filesystem::path testFilename{"test.tmp"}; - { - ofstream testFile(testFilename, ios::binary); - testFile << "TestFile for NativeFSTests\n"; - } - when("NativeDebugFS opens it", [&] { - DebugFS debugFS("."); - auto file = debugFS.open("test.tmp"); - then("A file with the correct content is returned", [&] { - require(file); - require(!file->isEncoded()); - array buffer; - auto bytesRead = file->read(buffer); - require(bytesRead == 27); - require(string(buffer.data(), 27) == "TestFile for NativeFSTests\n"); - require(file->eof()); - }); - }); - filesystem::remove(testFilename); - }); -}}; + given("A local file", [&] { + filesystem::path testFilename{"test.tmp"}; + { + ofstream testFile(testFilename, ios::binary); + testFile << "TestFile for NativeFSTests\n"; + } + when("NativeDebugFS opens it", [&] { + DebugFS debugFS("."); + auto file = debugFS.open("test.tmp"); + then("A file with the correct content is returned", [&] { + require(file); + require(!file->isEncoded()); + array buffer; + auto bytesRead = file->read(buffer); + require(bytesRead == 27); + require(string(buffer.data(), 27) == "TestFile for NativeFSTests\n"); + require(file->eof()); + }); + }); + filesystem::remove(testFilename); + }); + }}; const Scenario nativeDebugFSOpens{"NativeDebugFS opens an existing text file using a relative path", [] { - TemporaryTestEnvironment testEnv; - auto textFilePath = testEnv.createTextFile("sample.txt", "This is a sample text file\nwith multiple lines\nfor testing."); - DebugFS debugFS(testEnv.getTestDir().string()); + TemporaryTestEnvironment testEnv; + auto textFilePath = testEnv.createTextFile("sample.txt", "This is a sample text file\nwith multiple lines\nfor testing."); + DebugFS debugFS(testEnv.getTestDir().string()); - when("The file sample.txt is opened", [&] { - then("The file is opened and the content is correct", [&] { - checkFileRead(debugFS, "sample.txt", "This is a sample text file\nwith multiple lines\nfor testing."); - }); - }); -}}; + when("The file sample.txt is opened", [&] { + then("The file is opened and the content is correct", [&] { + checkFileRead(debugFS, "sample.txt", "This is a sample text file\nwith multiple lines\nfor testing."); + }); + }); + }}; const Scenario nativeDebugFSOpensJSON{"NativeDebugFS opens a JSON configuration file", [] { - TemporaryTestEnvironment testEnv; - auto configFilePath = testEnv.createTextFile("config.json", "{ \"name\": \"NativeFS\", \"version\": 1.0, \"isTest\": true }"); - DebugFS debugFS(testEnv.getTestDir().string()); + TemporaryTestEnvironment testEnv; + auto configFilePath = testEnv.createTextFile("config.json", + "{ \"name\": \"NativeFS\", \"version\": 1.0, \"isTest\": true }"); + DebugFS debugFS(testEnv.getTestDir().string()); - when("The file config.json is opened", [&] { - then("The file is opened and the JSON content is correct", [&] { - checkFileRead(debugFS, "config.json", "{ \"name\": \"NativeFS\", \"version\": 1.0, \"isTest\": true }"); - }); - }); -}}; + when("The file config.json is opened", [&] { + then("The file is opened and the JSON content is correct", [&] { + checkFileRead(debugFS, "config.json", "{ \"name\": \"NativeFS\", \"version\": 1.0, \"isTest\": true }"); + }); + }); + }}; const Scenario nativeDebugFSOpensBinary{"NativeDebugFS opens a binary file", [] { - TemporaryTestEnvironment testEnv; - auto binaryFilePath = testEnv.createBinaryFile("data.bin", 1024); - DebugFS debugFS(testEnv.getTestDir().string()); - const auto& originalData = testEnv.getBinaryData("data.bin"); - - when("The file data.bin is opened", [&] { - auto file = debugFS.open("data.bin"); - then("The binary content matches the original data", [&] { - require(file.has_value()); - require(!file->isEncoded()); - vector buffer(1024); - auto bytesRead = file->read(span(buffer)); - require(bytesRead == 1024); - require(memcmp(buffer.data(), originalData.data(), bytesRead) == 0); - }); - }); -}}; + TemporaryTestEnvironment testEnv; + auto binaryFilePath = testEnv.createBinaryFile("data.bin", 1024); + DebugFS debugFS(testEnv.getTestDir().string()); + const auto& originalData = testEnv.getBinaryData("data.bin"); + + when("The file data.bin is opened", [&] { + auto file = debugFS.open("data.bin"); + then("The binary content matches the original data", [&] { + require(file.has_value()); + require(!file->isEncoded()); + vector buffer(1024); + auto bytesRead = file->read(span(buffer)); + require(bytesRead == 1024); + require(memcmp(buffer.data(), originalData.data(), bytesRead) == 0); + }); + }); + }}; const Scenario nativeDebugFSOpensEmpty{"NativeDebugFS opens an empty file", [] { - TemporaryTestEnvironment testEnv; - auto emptyFilePath = testEnv.createTextFile("empty.txt", ""); - DebugFS debugFS(testEnv.getTestDir().string()); - - when("The file empty.txt is opened", [&] { - auto file = debugFS.open("empty.txt"); - then("The file is opened but it is empty", [&] { - require(file.has_value()); - array buffer; - auto bytesRead = file->read(buffer); - require(bytesRead == 0); - require(file->eof()); - }); - }); -}}; + TemporaryTestEnvironment testEnv; + auto emptyFilePath = testEnv.createTextFile("empty.txt", ""); + DebugFS debugFS(testEnv.getTestDir().string()); + + when("The file empty.txt is opened", [&] { + auto file = debugFS.open("empty.txt"); + then("The file is opened but it is empty", [&] { + require(file.has_value()); + array buffer; + auto bytesRead = file->read(buffer); + require(bytesRead == 0); + require(file->eof()); + }); + }); + }}; const Scenario nativeDebugFSOpensFile{"NativeDebugFS opens a file in a subdirectory", [] { - TemporaryTestEnvironment testEnv; - auto subdirFilePath = testEnv.createTextFile("subdir/nested.txt", "This is a nested file in a subdirectory"); - DebugFS debugFS(testEnv.getTestDir().string()); + TemporaryTestEnvironment testEnv; + auto subdirFilePath = testEnv.createTextFile("subdir/nested.txt", "This is a nested file in a subdirectory"); + DebugFS debugFS(testEnv.getTestDir().string()); - when("The file subdir/nested.txt is opened", [&] { - then("The file is opened successfully", [&] { - checkFileRead(debugFS, "subdir/nested.txt", "This is a nested file in a subdirectory"); - }); - }); -}}; + when("The file subdir/nested.txt is opened", [&] { + then("The file is opened successfully", [&] { + checkFileRead(debugFS, "subdir/nested.txt", "This is a nested file in a subdirectory"); + }); + }); + }}; const Scenario nativeDebugFSAttempts{"NativeDebugFS attempts to open a non-existent file", [] { - TemporaryTestEnvironment testEnv; - DebugFS debugFS(testEnv.getTestDir().string()); + TemporaryTestEnvironment testEnv; + DebugFS debugFS(testEnv.getTestDir().string()); - when("An attempt is made to open non_existent.txt", [&] { - auto file = debugFS.open("non_existent.txt"); - then("An empty optional is returned", [&] { - require(!file.has_value()); - }); - }); + when("An attempt is made to open non_existent.txt", [&] { + auto file = debugFS.open("non_existent.txt"); + then("An empty optional is returned", [&] { + require(!file.has_value()); + }); + }); - when("An attempt is made to open ../unauthorized.txt", [&] { - auto file = debugFS.open("../unauthorized.txt"); - then("An empty optional is returned for security reasons", [&] { - require(!file.has_value()); - }); - }); -}}; + when("An attempt is made to open ../unauthorized.txt", [&] { + auto file = debugFS.open("../unauthorized.txt"); + then("An empty optional is returned for security reasons", [&] { + require(!file.has_value()); + }); + }); + }}; const Scenario temporaryTestEnvironmentGetBinaryData{"TemporaryTestEnvironment::getBinaryData returns the correct binary data", [] { - TemporaryTestEnvironment testEnv; - auto binaryFilePath = testEnv.createBinaryFile("data.bin", 1024); - - when("Binary data is retrieved via getBinaryData", [&] { - const auto& data = testEnv.getBinaryData("data.bin"); - then("The size and content are correct", [&] { - require(data.size() == 1024); - require(!data.empty()); - }); - }); -}}; + TemporaryTestEnvironment testEnv; + auto binaryFilePath = testEnv.createBinaryFile("data.bin", 1024); + + when("Binary data is retrieved via getBinaryData", [&] { + const auto& data = testEnv.getBinaryData("data.bin"); + then("The size and content are correct", [&] { + require(data.size() == 1024); + require(!data.empty()); + }); + }); + }}; const Scenario nativeDebugFSRoot{"NativeDebugFS root path handling", [] { - TemporaryTestEnvironment testEnv; - auto testFile = testEnv.createTextFile("test_root.txt", "Root path test"); - - given("A NativeDebugFS with the root path set to the test directory", [&] { - DebugFS debugFS(testEnv.getTestDir().string()); - - when("A file is opened using an absolute path that does not respect the root path", [&] { - auto file = debugFS.open(filesystem::absolute("test_root.txt").string()); - - then("File access should fail as it is not under the root path", [&] { - require(!file.has_value()); - }); - }); - - when("The working directory is changed and relative paths are used", [&] { - auto originalPath = filesystem::current_path(); - - filesystem::current_path(testEnv.getTestDir()); - auto file = debugFS.open("test_root.txt"); - filesystem::current_path(originalPath); - - then("File access should succeed as the path is resolved correctly", [&] { - require(file.has_value()); - array buffer; - auto bytesRead = file->read(buffer); - require(string(buffer.data(), bytesRead) == "Root path test"); - }); - }); - }); - - given("A NativeDebugFS with the root path set to a subdirectory", [&] { - DebugFS debugFS(testEnv.getSubDir().string()); - auto subDirFile = testEnv.createTextFile("subdir/subdir_test.txt", "Subdir test"); - - when("An attempt is made to access a file in the parent directory", [&] { - auto file = debugFS.open("../test_root.txt"); - - then("File access behaviour depends on the implementation's security policy", [&] { - if (file.has_value()) { - array buffer; - auto bytesRead = file->read(buffer); - require(string(buffer.data(), bytesRead) == "Root path test"); - } - }); - }); - }); -}}; + TemporaryTestEnvironment testEnv; + auto testFile = testEnv.createTextFile("test_root.txt", "Root path test"); + + given("A NativeDebugFS with the root path set to the test directory", [&] { + DebugFS debugFS(testEnv.getTestDir().string()); + + when("A file is opened using an absolute path that does not respect the root path", [&] { + auto file = debugFS.open(filesystem::absolute("test_root.txt").string()); + + then("File access should fail as it is not under the root path", [&] { + require(!file.has_value()); + }); + }); + + when("The working directory is changed and relative paths are used", [&] { + auto originalPath = filesystem::current_path(); + + filesystem::current_path(testEnv.getTestDir()); + auto file = debugFS.open("test_root.txt"); + filesystem::current_path(originalPath); -const Scenario temporaryTestEnvironmentDestructor{"TemporaryTestEnvironment destructor handles remove_all exception", [] { - unique_ptr testEnv = make_unique(); - auto protectedDir = testEnv->getTestDir() / "protected"; - filesystem::create_directory(protectedDir); - filesystem::permissions(protectedDir, filesystem::perms::owner_read, filesystem::perm_options::replace); + then("File access should succeed as the path is resolved correctly", [&] { + require(file.has_value()); + array buffer; + auto bytesRead = file->read(buffer); + require(string(buffer.data(), bytesRead) == "Root path test"); + }); + }); + }); - stringstream capturedCerr; - auto* oldCerrBuf = cerr.rdbuf(capturedCerr.rdbuf()); + given("A NativeDebugFS with the root path set to a subdirectory", [&] { + DebugFS debugFS(testEnv.getSubDir().string()); + auto subDirFile = testEnv.createTextFile("subdir/subdir_test.txt", "Subdir test"); - testEnv.reset(); + when("An attempt is made to access a file in the parent directory", [&] { + auto file = debugFS.open("../test_root.txt"); - // Restore permissions to allow cleanup after the test - error_code ec; - filesystem::permissions(protectedDir, filesystem::perms::owner_all, filesystem::perm_options::replace, ec); + then("File access behaviour depends on the implementation's security policy", [&] { + if (file.has_value()) { + array buffer; + auto bytesRead = file->read(buffer); + require(string(buffer.data(), bytesRead) == "Root path test"); + } + }); + }); + }); + }}; - cerr.rdbuf(oldCerrBuf); +const Scenario temporaryTestEnvironmentDestructor{ + "TemporaryTestEnvironment destructor handles remove_all exception", + [] { + unique_ptr testEnv = make_unique(); + auto protectedDir = testEnv->getTestDir() / "protected"; + filesystem::create_directory(protectedDir); + filesystem::permissions(protectedDir, filesystem::perms::owner_read, filesystem::perm_options::replace); - // The test passes if the warning message is present OR if nothing is written (removal succeeded) - auto warningFound = capturedCerr.str().find("Warning: Failed to clean up test directory") != string::npos; - require((warningFound || capturedCerr.str().empty())); -}}; + stringstream capturedCerr; + auto* oldCerrBuf = cerr.rdbuf(capturedCerr.rdbuf()); + + testEnv.reset(); + + // Restore permissions to allow cleanup after the test + error_code ec; + filesystem::permissions(protectedDir, filesystem::perms::owner_all, filesystem::perm_options::replace, ec); + + cerr.rdbuf(oldCerrBuf); + + // The test passes if the warning message is present OR if nothing is written (removal succeeded) + auto warningFound = capturedCerr.str().find("Warning: Failed to clean up test directory") != string::npos; + require((warningFound || capturedCerr.str().empty())); + }}; // A stylesheet whose font-family lists many families is reported once by the development file system (#611). -const Scenario nativeDebugFSFontStacks{"NativeDebugFS warns once about costly font stacks in stylesheets", [] { - given("stylesheets in a document root", [&] { - TemporaryTestEnvironment env; - env.createTextFile("long-stack.css", "/* font-family: a, b, c, d, e */ body { font-family: system-ui, -apple-system, \"Segoe UI\", \"Inter\", sans-serif; }"); - env.createTextFile("short-stack.css", "body { font-family: system-ui, sans-serif; } code { font-family: \"A, B\", monospace; }"); - env.createTextFile("variable.css", "body { font-family: var(--a), x, y, z, w; --font-family: p, q, r, s, t; }"); - env.createTextFile("quoted.css", ".a { font-family: \"font-family: a, b, c, d, e\"; }"); - env.createTextFile("empty.css", ""); - when("each is opened twice", [&] { - std::ostringstream warnings; - struct WarningOutputScope { // restored even when a require() throws - explicit WarningOutputScope(std::ostream& out) { fonts::warningOutput = &out; } - ~WarningOutputScope() { fonts::warningOutput = nullptr; } - } const output{warnings}; - DebugFS root(env.getTestDir()); - for (int i = 0; i < 2; ++i) - for (const auto* name : {"long-stack.css", "short-stack.css", "variable.css", "quoted.css", "empty.css"}) - require(root.open(name).has_value()); - checkFileRead(root, "empty.css", ""); - checkFileRead(root, "short-stack.css", "body { font-family: system-ui, sans-serif; } code { font-family: \"A, B\", monospace; }"); - const auto text = warnings.str(); - then("only the long stack is reported, once, with its count", [&] { - require(text.find("long-stack.css") != string::npos); - require(text.find("lists 4 families") != string::npos); - require(text.find("short-stack.css") == string::npos); - require(text.find("variable.css") == string::npos); - require(text.find("quoted.css") == string::npos); - require(text.find("long-stack.css") == text.rfind("long-stack.css")); - require(count(text.begin(), text.end(), '\n') == 1); +const Scenario nativeDebugFSFontStacks{ + "NativeDebugFS warns once about costly font stacks in stylesheets", + [] { + given("stylesheets in a document root", [&] { + TemporaryTestEnvironment env; + env.createTextFile("long-stack.css", + "/* font-family: a, b, c, d, e */ body { font-family: system-ui, -apple-system, \"Segoe UI\", \"Inter\", sans-serif; }"); + env.createTextFile("short-stack.css", "body { font-family: system-ui, sans-serif; } code { font-family: \"A, B\", monospace; }"); + env.createTextFile("variable.css", "body { font-family: var(--a), x, y, z, w; --font-family: p, q, r, s, t; }"); + env.createTextFile("quoted.css", ".a { font-family: \"font-family: a, b, c, d, e\"; }"); + env.createTextFile("empty.css", ""); + when("each is opened twice", [&] { + std::ostringstream warnings; + struct WarningOutputScope { // restored even when a require() throws + explicit WarningOutputScope(std::ostream& out) { + fonts::warningOutput = &out; + } + ~WarningOutputScope() { + fonts::warningOutput = nullptr; + } + } const output{warnings}; + DebugFS root(env.getTestDir()); + for (int i = 0; i < 2; ++i) + for (const auto* name : {"long-stack.css", "short-stack.css", "variable.css", "quoted.css", "empty.css"}) + require(root.open(name).has_value()); + checkFileRead(root, "empty.css", ""); + checkFileRead(root, "short-stack.css", "body { font-family: system-ui, sans-serif; } code { font-family: \"A, B\", monospace; }"); + const auto text = warnings.str(); + then("only the long stack is reported, once, with its count", [&] { + require(text.find("long-stack.css") != string::npos); + require(text.find("lists 4 families") != string::npos); + require(text.find("short-stack.css") == string::npos); + require(text.find("variable.css") == string::npos); + require(text.find("quoted.css") == string::npos); + require(text.find("long-stack.css") == text.rfind("long-stack.css")); + require(count(text.begin(), text.end(), '\n') == 1); + }); }); }); - }); -}}; + }}; // Two document roots serving a stylesheet of the same name are each checked (#611). const Scenario nativeDebugFSFontStacksPerRoot{"NativeDebugFS checks a same-named stylesheet of each document root", [] { - given("two roots with a long font stack in style.css", [&] { - TemporaryTestEnvironment first; - TemporaryTestEnvironment second; - first.createTextFile("style.css", "body { font-family: aa1, bb1, cc1, dd1; }"); - second.createTextFile("style.css", "body { font-family: aa2, bb2, cc2, dd2; }"); - when("each root serves it", [&] { - std::ostringstream warnings; - fonts::warningOutput = &warnings; - DebugFS one(first.getTestDir()); - DebugFS two(second.getTestDir()); - require(one.open("style.css").has_value()); - require(two.open("style.css").has_value()); - fonts::warningOutput = nullptr; - const auto text = warnings.str(); - then("both are reported", [&] { - require(text.find("aa1") != string::npos); - require(text.find("aa2") != string::npos); - }); - }); - }); -}}; + given("two roots with a long font stack in style.css", [&] { + TemporaryTestEnvironment first; + TemporaryTestEnvironment second; + first.createTextFile("style.css", "body { font-family: aa1, bb1, cc1, dd1; }"); + second.createTextFile("style.css", "body { font-family: aa2, bb2, cc2, dd2; }"); + when("each root serves it", [&] { + std::ostringstream warnings; + fonts::warningOutput = &warnings; + DebugFS one(first.getTestDir()); + DebugFS two(second.getTestDir()); + require(one.open("style.css").has_value()); + require(two.open("style.css").has_value()); + fonts::warningOutput = nullptr; + const auto text = warnings.str(); + then("both are reported", [&] { + require(text.find("aa1") != string::npos); + require(text.find("aa2") != string::npos); + }); + }); + }); + }}; // A stylesheet edited after its first check is checked again, and an unchanged one is not (#611). const Scenario nativeDebugFSFontStacksEdited{"NativeDebugFS checks an edited stylesheet again", [] { - given("a stylesheet without a long stack that is served once", [&] { - TemporaryTestEnvironment env; - env.createTextFile("live.css", "body { font-family: sans-serif; }"); - std::ostringstream warnings; - fonts::warningOutput = &warnings; - DebugFS root(env.getTestDir()); - require(root.open("live.css").has_value()); - when("the developer adds a long stack and reloads twice", [&] { - env.createTextFile("live.css", "body { font-family: edited1, edited2, edited3, edited4, sans-serif; }"); - require(root.open("live.css").has_value()); - require(root.open("live.css").has_value()); - fonts::warningOutput = nullptr; - const auto text = warnings.str(); - then("the new stack is reported once", [&] { - require(text.find("edited1") != string::npos); - require(count(text.begin(), text.end(), '\n') == 1); - }); - }); - }); -}}; + given("a stylesheet without a long stack that is served once", [&] { + TemporaryTestEnvironment env; + env.createTextFile("live.css", "body { font-family: sans-serif; }"); + std::ostringstream warnings; + fonts::warningOutput = &warnings; + DebugFS root(env.getTestDir()); + require(root.open("live.css").has_value()); + when("the developer adds a long stack and reloads twice", [&] { + env.createTextFile("live.css", + "body { font-family: edited1, edited2, edited3, edited4, sans-serif; }"); + require(root.open("live.css").has_value()); + require(root.open("live.css").has_value()); + fonts::warningOutput = nullptr; + const auto text = warnings.str(); + then("the new stack is reported once", [&] { + require(text.find("edited1") != string::npos); + require(count(text.begin(), text.end(), '\n') == 1); + }); + }); + }); + }}; // Declarations are told from text, whatever the case of the property name (#611). -const Scenario fontStacksParsing{"Font stack detection reads declarations, not quoted text, and ignores the property's case", [] { - given("a quoted string that looks like a declaration", [&] { - then("it is not reported", [&] { - check(fonts::longStacks("a::before { content: \"font-family: a,b,c,d\"; } b { content: 'x /* font-family: a,b,c,d */'; }").empty()); +const Scenario fontStacksParsing{ + "Font stack detection reads declarations, not quoted text, and ignores the property's case", + [] { + given("a quoted string that looks like a declaration", [&] { + then("it is not reported", [&] { + check(fonts::longStacks("a::before { content: \"font-family: a,b,c,d\"; } b { content: 'x /* font-family: a,b,c,d */'; }").empty()); + }); }); - }); - given("a property name in capitals", [&] { - const auto found = fonts::longStacks("body { FONT-FAMILY: a, b, c, d; } p { Font-Family : e, f, g, h }"); - then("both are reported", [&] { - require(found.size() == 2); - check(found[0].costly == 4 && found[1].costly == 4); + given("a property name in capitals", [&] { + const auto found = fonts::longStacks("body { FONT-FAMILY: a, b, c, d; } p { Font-Family : e, f, g, h }"); + then("both are reported", [&] { + require(found.size() == 2); + check(found[0].costly == 4 && found[1].costly == 4); + }); }); - }); - given("a family whose quoted name contains a semicolon", [&] { - then("the value is not cut inside the quotes", [&] { - check(fonts::longStacks("x { font-family: \"A;B\", b, c, d; }").size() == 1); + given("a family whose quoted name contains a semicolon", [&] { + then("the value is not cut inside the quotes", [&] { + check(fonts::longStacks("x { font-family: \"A;B\", b, c, d; }").size() == 1); + }); }); - }); -}}; + }}; diff --git a/test/unit/NativeStorageTests.cpp b/test/unit/NativeStorageTests.cpp index 2e07722f..e6e93b1a 100644 --- a/test/unit/NativeStorageTests.cpp +++ b/test/unit/NativeStorageTests.cpp @@ -1,6 +1,6 @@ #include "TemporaryDirectory.hpp" -#include #include +#include #include #include @@ -156,806 +156,818 @@ shared_ptr hooksAt(function buffer{}; - require(file.seek(3)); - require(file.read(buffer) == 2); - require(string_view(buffer.data(), 2) == "ha"); - }); - then("a write replaces atomically only when asked to", [&] { - require(errorOf([&] { - writeFile(storage, "b.txt", "other"); - }) - == fs::StorageErrc::alreadyExists); - writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); - require(readDisk(sandbox.root / "b.txt") == "gamma"); - require(errorOf([&] { - writeFile(storage, "docs", "x", fs::WriteMode::replace); - }) - == fs::StorageErrc::isDirectory); - }); - then("entries are renamed without replacing and removed", [&] { - require(errorOf([&] { - storage.rename("b.txt", "docs/a.txt"); - }) - == fs::StorageErrc::alreadyExists); - storage.rename("b.txt", "docs/b.txt"); - require(stdfs::exists(sandbox.root / "docs" / "b.txt")); - require(errorOf([&] { - storage.remove("docs"); - }) - == fs::StorageErrc::notEmpty); - storage.remove("docs/a.txt"); - storage.remove("docs/b.txt"); - storage.remove("docs"); - require(namesOn(sandbox.root).empty()); - }); - then("operations through a file or a missing entry fail with their reason", [&] { - require(errorOf([&] { - storage.list("b.txt"); - }) - == fs::StorageErrc::notDirectory); - require(errorOf([&] { - storage.openRead("b.txt/x"); - }) - == fs::StorageErrc::notDirectory); - require(errorOf([&] { - storage.openRead("missing.txt"); - }) - == fs::StorageErrc::notFound); - require(errorOf([&] { - storage.openRead("docs"); - }) - == fs::StorageErrc::isDirectory); - require(errorOf([&] { - storage.createDirectory("docs"); - }) - == fs::StorageErrc::alreadyExists); - }); - }); - given("paths SafePath rejects", [&] { - then("they are refused before touching the disk", [&] { - for (string path : {"../outside/secret.txt", "/etc/passwd", "a/../../outside", "C:/x", "nul", "a\\..\\b"}) { - auto scope = info(path); - require(errorOf([&] { storage.openRead(path); }) == fs::StorageErrc::invalidPath); - require(errorOf([&] { storage.createDirectory(path); }) == fs::StorageErrc::invalidPath); - require(sandbox.outsideUntouched()); - } - }); - }); - given("a location that is not a directory", [&] { - writeDisk(sandbox.base.path() / "file", "x"); - then("it cannot be declared", [&] { - require(errorOf([&] { - fs::NativeStorage{sandbox.base.path() / "missing"}; - }) - == fs::StorageErrc::notFound); - require(errorOf([&] { - fs::NativeStorage{sandbox.base.path() / "file"}; - }) - == fs::StorageErrc::notDirectory); - }); - }); -}}; + then("they are on disk, listed, inspected and read", [&] { + require(readDisk(sandbox.root / "docs" / "a.txt") == "alpha"); + auto page = storage.list(""); + require(page.entries.size() == 2); + require(page.entries[0].name == "b.txt"); + require(page.entries[0].type == fs::EntryType::file); + require(page.entries[0].size == 4); + require(page.entries[0].readable); + require(page.entries[0].writable); + require(page.entries[1].type == fs::EntryType::directory); + require(storage.status("docs/a.txt").size == 5); + require(storage.status("").type == fs::EntryType::directory); + auto file = storage.openRead("docs/a.txt"); + require(file.knownSize() == 5u); + require(readAll(std::move(file)) == "alpha"); + }); + then("a file is read from any position", [&] { + auto file = storage.openRead("docs/a.txt"); + array buffer{}; + require(file.seek(3)); + require(file.read(buffer) == 2); + require(string_view(buffer.data(), 2) == "ha"); + }); + then("a write replaces atomically only when asked to", [&] { + require(errorOf([&] { + writeFile(storage, "b.txt", "other"); + }) + == fs::StorageErrc::alreadyExists); + writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); + require(readDisk(sandbox.root / "b.txt") == "gamma"); + require(errorOf([&] { + writeFile(storage, "docs", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::isDirectory); + }); + then("entries are renamed without replacing and removed", [&] { + require(errorOf([&] { + storage.rename("b.txt", "docs/a.txt"); + }) + == fs::StorageErrc::alreadyExists); + storage.rename("b.txt", "docs/b.txt"); + require(stdfs::exists(sandbox.root / "docs" / "b.txt")); + require(errorOf([&] { + storage.remove("docs"); + }) + == fs::StorageErrc::notEmpty); + storage.remove("docs/a.txt"); + storage.remove("docs/b.txt"); + storage.remove("docs"); + require(namesOn(sandbox.root).empty()); + }); + then("operations through a file or a missing entry fail with their reason", [&] { + require(errorOf([&] { + storage.list("b.txt"); + }) + == fs::StorageErrc::notDirectory); + require(errorOf([&] { + storage.openRead("b.txt/x"); + }) + == fs::StorageErrc::notDirectory); + require(errorOf([&] { + storage.openRead("missing.txt"); + }) + == fs::StorageErrc::notFound); + require(errorOf([&] { + storage.openRead("docs"); + }) + == fs::StorageErrc::isDirectory); + require(errorOf([&] { + storage.createDirectory("docs"); + }) + == fs::StorageErrc::alreadyExists); + }); + }); + given("paths SafePath rejects", [&] { + then("they are refused before touching the disk", [&] { + for (string path : {"../outside/secret.txt", "/etc/passwd", "a/../../outside", "C:/x", "nul", "a\\..\\b"}) { + auto scope = info(path); + require(errorOf([&] { + storage.openRead(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.createDirectory(path); + }) + == fs::StorageErrc::invalidPath); + require(sandbox.outsideUntouched()); + } + }); + }); + given("a location that is not a directory", [&] { + writeDisk(sandbox.base.path() / "file", "x"); + then("it cannot be declared", [&] { + require(errorOf([&] { + fs::NativeStorage{sandbox.base.path() / "missing"}; + }) + == fs::StorageErrc::notFound); + require(errorOf([&] { + fs::NativeStorage{sandbox.base.path() / "file"}; + }) + == fs::StorageErrc::notDirectory); + }); + }); + }}; const Scenario nativeStorageReserves{"A native storage reserves the names of its temporary files", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - require(errorOf([&] { - writeFile(storage, ".wf-tmp-report.txt", "report"); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.rename("a", ".wf-tmp-a"); - }) - == fs::StorageErrc::invalidPath); - require(namesOn(sandbox.root).empty()); - given("a write in progress, its temporary file named in another case", [&] { - auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); - writer.write(span("partial", 7)); - const auto temporary = namesOn(sandbox.root).at(0); - auto upper = temporary; - ranges::transform(upper, upper.begin(), [](char c) { - return c >= 'a' && c <= 'z' ? static_cast(c - 'a' + 'A') : c; - }); - then("it can be neither read nor published, on a case-insensitive volume as elsewhere", [&] { - // macOS (by default) and Windows volumes name the same file in any case: the reservation must cover it. - if (!stdfs::exists(sandbox.root / upper)) - warn("This volume is case-sensitive: the other case names no file here"); - require(errorOf([&] { - storage.openRead(upper); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.rename(upper, "published.txt"); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.remove(upper); - }) - == fs::StorageErrc::invalidPath); - require(!stdfs::exists(sandbox.root / "published.txt")); - }); - }); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + require(errorOf([&] { + writeFile(storage, ".wf-tmp-report.txt", "report"); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.rename("a", ".wf-tmp-a"); + }) + == fs::StorageErrc::invalidPath); + require(namesOn(sandbox.root).empty()); + given("a write in progress, its temporary file named in another case", [&] { + auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + const auto temporary = namesOn(sandbox.root).at(0); + auto upper = temporary; + ranges::transform(upper, upper.begin(), [](char c) { + return c >= 'a' && c <= 'z' ? static_cast(c - 'a' + 'A') : c; + }); + then("it can be neither read nor published, on a case-insensitive volume as elsewhere", [&] { + // macOS (by default) and Windows volumes name the same file in any case: the reservation must cover it. + if (!stdfs::exists(sandbox.root / upper)) + warn("This volume is case-sensitive: the other case names no file here"); + require(errorOf([&] { + storage.openRead(upper); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.rename(upper, "published.txt"); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.remove(upper); + }) + == fs::StorageErrc::invalidPath); + require(!stdfs::exists(sandbox.root / "published.txt")); + }); + }); + }}; const Scenario interruptedWrite{"An interrupted write leaves no partial file", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - writeFile(storage, "kept.txt", "original"); + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeFile(storage, "kept.txt", "original"); - given("writes destroyed before their commit, new or replacing", [&] { - { - auto writer = storage.beginWrite("new.txt", fs::WriteMode::createNew); - writer.write(span("partial", 7)); - require(namesOn(sandbox.root).size() == 2); // kept.txt and the temporary file - require(storage.list("").entries.size() == 1); - require(errorOf([&] { - storage.status("new.txt"); - }) - == fs::StorageErrc::notFound); - } - { - auto writer = storage.beginWrite("kept.txt", fs::WriteMode::replace); - writer.write(span("half", 4)); - } - then("neither the partial file nor the temporary one remains, and the replaced file is intact", [&] { - require(namesOn(sandbox.root) == vector{"kept.txt"}); - require(readDisk(sandbox.root / "kept.txt") == "original"); - }); - }); -}}; + given("writes destroyed before their commit, new or replacing", [&] { + { + auto writer = storage.beginWrite("new.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + require(namesOn(sandbox.root).size() == 2); // kept.txt and the temporary file + require(storage.list("").entries.size() == 1); + require(errorOf([&] { + storage.status("new.txt"); + }) + == fs::StorageErrc::notFound); + } + { + auto writer = storage.beginWrite("kept.txt", fs::WriteMode::replace); + writer.write(span("half", 4)); + } + then("neither the partial file nor the temporary one remains, and the replaced file is intact", [&] { + require(namesOn(sandbox.root) == vector{"kept.txt"}); + require(readDisk(sandbox.root / "kept.txt") == "original"); + }); + }); + }}; const Scenario committedWriter{"A committed writer holds none of its directories", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - storage.createDirectory("dir"); - auto writer = storage.beginWrite("dir/file.txt", fs::WriteMode::createNew); - writer.write(span("data", 4)); - writer.commit(); - // The writer stays alive: on Windows, handles it kept without FILE_SHARE_DELETE would make these fail. - std::error_code renamed, removed; - stdfs::rename(sandbox.root / "dir", sandbox.root / "moved", renamed); - require(!renamed); - stdfs::remove(sandbox.root / "moved" / "file.txt", removed); - require(!removed); - stdfs::remove(sandbox.root / "moved", removed); - require(!removed); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("dir"); + auto writer = storage.beginWrite("dir/file.txt", fs::WriteMode::createNew); + writer.write(span("data", 4)); + writer.commit(); + // The writer stays alive: on Windows, handles it kept without FILE_SHARE_DELETE would make these fail. + std::error_code renamed, removed; + stdfs::rename(sandbox.root / "dir", sandbox.root / "moved", renamed); + require(!renamed); + stdfs::remove(sandbox.root / "moved" / "file.txt", removed); + require(!removed); + stdfs::remove(sandbox.root / "moved", removed); + require(!removed); + }}; const Scenario nativeListings{"Native listings are paginated and stable", [] { - Sandbox sandbox; - for (int index = 10; index < 40; ++index) - writeDisk(sandbox.root / ("f" + to_string(index)), "x"); + Sandbox sandbox; + for (int index = 10; index < 40; ++index) + writeDisk(sandbox.root / ("f" + to_string(index)), "x"); #ifndef _WIN32 - writeDisk(sandbox.root / "trailing.", "unaddressable"); // a name SafePath rejects is not listed + writeDisk(sandbox.root / "trailing.", "unaddressable"); // a name SafePath rejects is not listed #endif - fs::NativeStorage storage(sandbox.root); + fs::NativeStorage storage(sandbox.root); - auto first = storage.list("", {}, 10); - require(first.entries.size() == 10); - require(first.next == "f19"); - writeDisk(sandbox.root / "f05", "x"); - writeDisk(sandbox.root / "f195", "x"); - stdfs::remove(sandbox.root / "f30"); - vector seen; - for (auto& entry : first.entries) - seen.push_back(entry.name); - for (auto after = first.next; after;) { - auto page = storage.list("", *after, 10); - for (auto& entry : page.entries) - seen.push_back(entry.name); - after = page.next; - } - vector expected; - for (int index = 10; index < 40; ++index) - if (index != 30) - expected.push_back("f" + to_string(index)); - expected.push_back("f195"); - ranges::sort(expected); - require(seen == expected); -}}; + auto first = storage.list("", {}, 10); + require(first.entries.size() == 10); + require(first.next == "f19"); + writeDisk(sandbox.root / "f05", "x"); + writeDisk(sandbox.root / "f195", "x"); + stdfs::remove(sandbox.root / "f30"); + vector seen; + for (auto& entry : first.entries) + seen.push_back(entry.name); + for (auto after = first.next; after;) { + auto page = storage.list("", *after, 10); + for (auto& entry : page.entries) + seen.push_back(entry.name); + after = page.next; + } + vector expected; + for (int index = 10; index < 40; ++index) + if (index != 30) + expected.push_back("f" + to_string(index)); + expected.push_back("f195"); + ranges::sort(expected); + require(seen == expected); + }}; const Scenario linksNever{"Links never lead a native storage outside its root", [] { - Sandbox sandbox; - makeDirectories(sandbox.root / "inside"); - writeDisk(sandbox.root / "inside" / "note.txt", "note"); - linkDirectory(sandbox.outside, sandbox.root / "escape"); + Sandbox sandbox; + makeDirectories(sandbox.root / "inside"); + writeDisk(sandbox.root / "inside" / "note.txt", "note"); + linkDirectory(sandbox.outside, sandbox.root / "escape"); - given("a root that refuses links (the default)", [&] { - fs::NativeStorage storage(sandbox.root); - then("every operation through the link is refused and the outside is untouched", [&] { - require(errorOf([&] { - storage.list("escape"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.openRead("escape/secret.txt"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - writeFile(storage, "escape/new.txt", "x"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - writeFile(storage, "escape/secret.txt", "x", fs::WriteMode::replace); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.createDirectory("escape/dir"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.remove("escape/secret.txt"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.rename("escape/secret.txt", "stolen.txt"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.rename("inside/note.txt", "escape/note.txt"); - }) - == fs::StorageErrc::linkRefused); - require(sandbox.outsideUntouched()); - }); - then("the link is listed as a link, not followed", [&] { - auto page = storage.list(""); - require(page.entries.size() == 2); - require(page.entries[0].name == "escape"); - require(page.entries[0].type == fs::EntryType::link); - require(storage.status("escape").type == fs::EntryType::link); - }); - then("removing the link removes the link only", [&] { - storage.remove("escape"); - require(!stdfs::exists(stdfs::symlink_status(sandbox.root / "escape"))); - require(sandbox.outsideUntouched()); - }); - }); + given("a root that refuses links (the default)", [&] { + fs::NativeStorage storage(sandbox.root); + then("every operation through the link is refused and the outside is untouched", [&] { + require(errorOf([&] { + storage.list("escape"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.openRead("escape/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + writeFile(storage, "escape/new.txt", "x"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + writeFile(storage, "escape/secret.txt", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.createDirectory("escape/dir"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.remove("escape/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.rename("escape/secret.txt", "stolen.txt"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.rename("inside/note.txt", "escape/note.txt"); + }) + == fs::StorageErrc::linkRefused); + require(sandbox.outsideUntouched()); + }); + then("the link is listed as a link, not followed", [&] { + auto page = storage.list(""); + require(page.entries.size() == 2); + require(page.entries[0].name == "escape"); + require(page.entries[0].type == fs::EntryType::link); + require(storage.status("escape").type == fs::EntryType::link); + }); + then("removing the link removes the link only", [&] { + storage.remove("escape"); + require(!stdfs::exists(stdfs::symlink_status(sandbox.root / "escape"))); + require(sandbox.outsideUntouched()); + }); + }); #ifndef _WIN32 - given("a file link to the outside", [&] { - stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "secret-link"); - fs::NativeStorage storage(sandbox.root); - then("it is not read, and replacing it replaces the link, not its target", [&] { - require(errorOf([&] { - storage.openRead("secret-link"); - }) - == fs::StorageErrc::linkRefused); - writeFile(storage, "secret-link", "replaced", fs::WriteMode::replace); - require(stdfs::is_regular_file(stdfs::symlink_status(sandbox.root / "secret-link"))); - require(sandbox.outsideUntouched()); - }); - }); - given("a root that follows links inside it", [&] { - stdfs::create_directory_symlink("inside", sandbox.root / "alias"); - stdfs::create_symlink("../inside/note.txt", sandbox.root / "inside" / "self"); - stdfs::create_directory_symlink("../../outside", sandbox.root / "inside" / "up"); - stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "absolute"); - stdfs::create_symlink("loop", sandbox.root / "loop"); - stdfs::create_symlink("..", sandbox.root / "parent"); - fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); - then("a link whose resolution stays inside is followed", [&] { - require(readAll(storage.openRead("alias/note.txt")) == "note"); - require(readAll(storage.openRead("inside/self")) == "note"); - writeFile(storage, "alias/added.txt", "added"); - require(readDisk(sandbox.root / "inside" / "added.txt") == "added"); - require(storage.list("alias").entries.size() == 4); // note.txt, self, up, added.txt - }); - then("a link that leaves the root, an absolute link and a loop are refused", [&] { - require(errorOf([&] { - storage.list("escape"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.openRead("inside/up/secret.txt"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - writeFile(storage, "inside/up/new.txt", "x"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.openRead("absolute"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.openRead("loop"); - }) - == fs::StorageErrc::linkRefused); - require(sandbox.outsideUntouched()); - }); - }); + given("a file link to the outside", [&] { + stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "secret-link"); + fs::NativeStorage storage(sandbox.root); + then("it is not read, and replacing it replaces the link, not its target", [&] { + require(errorOf([&] { + storage.openRead("secret-link"); + }) + == fs::StorageErrc::linkRefused); + writeFile(storage, "secret-link", "replaced", fs::WriteMode::replace); + require(stdfs::is_regular_file(stdfs::symlink_status(sandbox.root / "secret-link"))); + require(sandbox.outsideUntouched()); + }); + }); + given("a root that follows links inside it", [&] { + stdfs::create_directory_symlink("inside", sandbox.root / "alias"); + stdfs::create_symlink("../inside/note.txt", sandbox.root / "inside" / "self"); + stdfs::create_directory_symlink("../../outside", sandbox.root / "inside" / "up"); + stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "absolute"); + stdfs::create_symlink("loop", sandbox.root / "loop"); + stdfs::create_symlink("..", sandbox.root / "parent"); + fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); + then("a link whose resolution stays inside is followed", [&] { + require(readAll(storage.openRead("alias/note.txt")) == "note"); + require(readAll(storage.openRead("inside/self")) == "note"); + writeFile(storage, "alias/added.txt", "added"); + require(readDisk(sandbox.root / "inside" / "added.txt") == "added"); + require(storage.list("alias").entries.size() == 4); // note.txt, self, up, added.txt + }); + then("a link that leaves the root, an absolute link and a loop are refused", [&] { + require(errorOf([&] { + storage.list("escape"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.openRead("inside/up/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + writeFile(storage, "inside/up/new.txt", "x"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.openRead("absolute"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.openRead("loop"); + }) + == fs::StorageErrc::linkRefused); + require(sandbox.outsideUntouched()); + }); + }); #endif -}}; + }}; const Scenario componentReplaced{"A component replaced by a link during the resolution does not lead outside", [] { - Sandbox sandbox; + Sandbox sandbox; - // Before each operation: root/a/b/file.txt. When `a` has been opened and `b` not yet, b is replaced by a link to - // the outside directory, as a concurrent local process could do between two resolution steps. - auto prepare = [&] { - stdfs::remove_all(sandbox.root / "a"); - makeDirectories(sandbox.root / "a" / "b"); - writeDisk(sandbox.root / "a" / "b" / "secret.txt", "inner"); - }; - auto swapB = hooksAt([&](fs::StoragePoint point, string_view name) { - if (point == fs::StoragePoint::componentOpened && name == "a") { - stdfs::rename(sandbox.root / "a" / "b", sandbox.root / "b-moved"); - linkDirectory(sandbox.outside, sandbox.root / "a" / "b"); - } - }); - fs::NativeStorage storage(sandbox.root, {}, swapB); + // Before each operation: root/a/b/file.txt. When `a` has been opened and `b` not yet, b is replaced by a link to + // the outside directory, as a concurrent local process could do between two resolution steps. + auto prepare = [&] { + stdfs::remove_all(sandbox.root / "a"); + makeDirectories(sandbox.root / "a" / "b"); + writeDisk(sandbox.root / "a" / "b" / "secret.txt", "inner"); + }; + auto swapB = hooksAt([&](fs::StoragePoint point, string_view name) { + if (point == fs::StoragePoint::componentOpened && name == "a") { + stdfs::rename(sandbox.root / "a" / "b", sandbox.root / "b-moved"); + linkDirectory(sandbox.outside, sandbox.root / "a" / "b"); + } + }); + fs::NativeStorage storage(sandbox.root, {}, swapB); - const vector> operations{[&] { - storage.openRead("a/b/secret.txt"); - }, - [&] { - storage.list("a/b"); - }, - [&] { - writeFile(storage, "a/b/new.txt", "x"); - }, - [&] { - writeFile(storage, "a/b/secret.txt", "x", fs::WriteMode::replace); - }, - [&] { - storage.createDirectory("a/b/dir"); - }, - [&] { - storage.remove("a/b/secret.txt"); - }, - [&] { - storage.rename("a/b/secret.txt", "stolen.txt"); - }, - [&] { - storage.status("a/b/secret.txt"); - }}; - for (size_t index = 0; index != operations.size(); ++index) - section("operation " + to_string(index), [&] { - prepare(); - stdfs::remove_all(sandbox.root / "b-moved"); - require(errorOf(operations[index]) == fs::StorageErrc::linkRefused); - require(sandbox.outsideUntouched()); - }); -}}; + const vector> operations{[&] { + storage.openRead("a/b/secret.txt"); + }, + [&] { + storage.list("a/b"); + }, + [&] { + writeFile(storage, "a/b/new.txt", "x"); + }, + [&] { + writeFile(storage, "a/b/secret.txt", "x", fs::WriteMode::replace); + }, + [&] { + storage.createDirectory("a/b/dir"); + }, + [&] { + storage.remove("a/b/secret.txt"); + }, + [&] { + storage.rename("a/b/secret.txt", "stolen.txt"); + }, + [&] { + storage.status("a/b/secret.txt"); + }}; + for (size_t index = 0; index != operations.size(); ++index) + section("operation " + to_string(index), [&] { + prepare(); + stdfs::remove_all(sandbox.root / "b-moved"); + require(errorOf(operations[index]) == fs::StorageErrc::linkRefused); + require(sandbox.outsideUntouched()); + }); + }}; const Scenario finalFile{"A final file replaced by a link after the resolution does not lead outside", [] { - Sandbox sandbox; - auto swapFile = hooksAt([&](fs::StoragePoint point, string_view name) { - if (point == fs::StoragePoint::resolved && name == "target.txt") { - stdfs::remove(sandbox.root / "target.txt"); + Sandbox sandbox; + auto swapFile = hooksAt([&](fs::StoragePoint point, string_view name) { + if (point == fs::StoragePoint::resolved && name == "target.txt") { + stdfs::remove(sandbox.root / "target.txt"); #ifdef _WIN32 - linkDirectory(sandbox.outside, sandbox.root / "target.txt"); + linkDirectory(sandbox.outside, sandbox.root / "target.txt"); #else stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "target.txt"); #endif - } - }); - fs::NativeStorage storage(sandbox.root, {}, swapFile); - writeDisk(sandbox.root / "target.txt", "inner"); + } + }); + fs::NativeStorage storage(sandbox.root, {}, swapFile); + writeDisk(sandbox.root / "target.txt", "inner"); - when("it is read", [&] { - then("the link is refused", [&] { - require(errorOf([&] { - storage.openRead("target.txt"); - }) - == fs::StorageErrc::linkRefused); - }); - }); - when("it is removed", [&] { - storage.remove("target.txt"); - then("the link goes, not the outside file", [&] { - require(!stdfs::exists(stdfs::symlink_status(sandbox.root / "target.txt"))); - }); - }); - when("it is inspected", [&] { - then("the link is reported, not followed", [&] { - require(storage.status("target.txt").type == fs::EntryType::link); - }); - }); - require(sandbox.outsideUntouched()); -}}; + when("it is read", [&] { + then("the link is refused", [&] { + require(errorOf([&] { + storage.openRead("target.txt"); + }) + == fs::StorageErrc::linkRefused); + }); + }); + when("it is removed", [&] { + storage.remove("target.txt"); + then("the link goes, not the outside file", [&] { + require(!stdfs::exists(stdfs::symlink_status(sandbox.root / "target.txt"))); + }); + }); + when("it is inspected", [&] { + then("the link is reported, not followed", [&] { + require(storage.status("target.txt").type == fs::EntryType::link); + }); + }); + require(sandbox.outsideUntouched()); + }}; #ifndef _WIN32 const Scenario repeatedRaces{"Repeated races between a link swap and the operations never reach the outside", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - makeDirectories(sandbox.root / "a"); - atomic stop{false}; - // Swaps `a` between a real directory and a link to the outside, as fast as it can. - thread swapper([&] { - const auto directory = sandbox.root / "a"; - const auto parked = sandbox.root / "parked"; - const auto link = sandbox.base.path() / "link"; - while (!stop) { - std::error_code ignored; - stdfs::create_directory_symlink(sandbox.outside, link, ignored); - stdfs::rename(directory, parked, ignored); - stdfs::rename(link, directory, ignored); - std::this_thread::yield(); - stdfs::rename(directory, link, ignored); - stdfs::rename(parked, directory, ignored); - } - }); - int refused = 0; - auto attempt = [&](auto&& operation) { - try { - operation(); - } catch (const fs::StorageError& error) { - refused += error.errc() == fs::StorageErrc::linkRefused; - } - }; - for (int iteration = 0; iteration < 2000; ++iteration) { - const auto name = "f" + to_string(iteration); - attempt([&] { - writeFile(storage, "a/" + name, "x"); - }); - attempt([&] { - storage.createDirectory("a/d" + name); - }); - attempt([&] { - storage.remove("a/secret.txt"); - }); - attempt([&] { - storage.rename("a/secret.txt", "stolen" + name); - }); - attempt([&] { - readAll(storage.openRead("a/secret.txt")); - fail("The outside file was read"); - }); - } - stop = true; - swapper.join(); - require(sandbox.outsideUntouched()); - require(refused > 0); // the operations did meet the link -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + makeDirectories(sandbox.root / "a"); + atomic stop{false}; + // Swaps `a` between a real directory and a link to the outside, as fast as it can. + thread swapper([&] { + const auto directory = sandbox.root / "a"; + const auto parked = sandbox.root / "parked"; + const auto link = sandbox.base.path() / "link"; + while (!stop) { + std::error_code ignored; + stdfs::create_directory_symlink(sandbox.outside, link, ignored); + stdfs::rename(directory, parked, ignored); + stdfs::rename(link, directory, ignored); + std::this_thread::yield(); + stdfs::rename(directory, link, ignored); + stdfs::rename(parked, directory, ignored); + } + }); + int refused = 0; + auto attempt = [&](auto&& operation) { + try { + operation(); + } catch (const fs::StorageError& error) { + refused += error.errc() == fs::StorageErrc::linkRefused; + } + }; + for (int iteration = 0; iteration < 2000; ++iteration) { + const auto name = "f" + to_string(iteration); + attempt([&] { + writeFile(storage, "a/" + name, "x"); + }); + attempt([&] { + storage.createDirectory("a/d" + name); + }); + attempt([&] { + storage.remove("a/secret.txt"); + }); + attempt([&] { + storage.rename("a/secret.txt", "stolen" + name); + }); + attempt([&] { + readAll(storage.openRead("a/secret.txt")); + fail("The outside file was read"); + }); + } + stop = true; + swapper.join(); + require(sandbox.outsideUntouched()); + require(refused > 0); // the operations did meet the link + }}; const Scenario directoryMoved{"A directory moved out of the root by the same user is detected before the commit", [] { - Sandbox sandbox; - makeDirectories(sandbox.root / "a" / "b"); - const auto moved = sandbox.outside / "b"; + Sandbox sandbox; + makeDirectories(sandbox.root / "a" / "b"); + const auto moved = sandbox.outside / "b"; - given("a directory moved out while the temporary file is written", [&] { - auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { - if (point == fs::StoragePoint::temporaryCreated) - stdfs::rename(sandbox.root / "a" / "b", moved); - }); - fs::NativeStorage storage(sandbox.root, {}, hooks); - auto writer = storage.beginWrite("a/b/file.txt", fs::WriteMode::createNew); - writer.write(span("data", 4)); - then("the commit is abandoned with confinementViolated, without a file nor a temporary file outside", [&] { - require(errorOf([&] { - writer.commit(); - }) - == fs::StorageErrc::confinementViolated); - require(stdfs::is_empty(moved)); - }); - }); - given("a directory moved out just before the commit's check", [&] { - auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { - if (point == fs::StoragePoint::beforeCommit) - stdfs::rename(sandbox.root / "a", sandbox.outside / "a"); - }); - fs::NativeStorage storage(sandbox.root, {}, hooks); - then("the rename does not happen", [&] { - require(errorOf([&] { - writeFile(storage, "a/b/file.txt", "data"); - }) - == fs::StorageErrc::confinementViolated); - require(stdfs::is_empty(sandbox.outside / "a" / "b")); - }); - }); - given("a directory moved out between its opening and the operation", [&] { - bool once = true; - auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { - if (point == fs::StoragePoint::resolved && std::exchange(once, false)) - stdfs::rename(sandbox.root / "a" / "b", moved); - }); - fs::NativeStorage storage(sandbox.root, {}, hooks); - then("the operation reports the violation it detected afterwards", [&] { - require(errorOf([&] { - storage.createDirectory("a/b/dir"); - }) - == fs::StorageErrc::confinementViolated); - require(errorOf([&] { - storage.status("a/b"); - }) - == fs::StorageErrc::notFound); - }); - }); -}}; + given("a directory moved out while the temporary file is written", [&] { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) + stdfs::rename(sandbox.root / "a" / "b", moved); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + auto writer = storage.beginWrite("a/b/file.txt", fs::WriteMode::createNew); + writer.write(span("data", 4)); + then("the commit is abandoned with confinementViolated, without a file nor a temporary file outside", [&] { + require(errorOf([&] { + writer.commit(); + }) + == fs::StorageErrc::confinementViolated); + require(stdfs::is_empty(moved)); + }); + }); + given("a directory moved out just before the commit's check", [&] { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::beforeCommit) + stdfs::rename(sandbox.root / "a", sandbox.outside / "a"); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + then("the rename does not happen", [&] { + require(errorOf([&] { + writeFile(storage, "a/b/file.txt", "data"); + }) + == fs::StorageErrc::confinementViolated); + require(stdfs::is_empty(sandbox.outside / "a" / "b")); + }); + }); + given("a directory moved out between its opening and the operation", [&] { + bool once = true; + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::resolved && std::exchange(once, false)) + stdfs::rename(sandbox.root / "a" / "b", moved); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + then("the operation reports the violation it detected afterwards", [&] { + require(errorOf([&] { + storage.createDirectory("a/b/dir"); + }) + == fs::StorageErrc::confinementViolated); + require(errorOf([&] { + storage.status("a/b"); + }) + == fs::StorageErrc::notFound); + }); + }); + }}; const Scenario rootMovedSame{"A root moved by the same user is no longer used", [] { - Sandbox sandbox; - const auto elsewhere = sandbox.base.path() / "elsewhere"; + Sandbox sandbox; + const auto elsewhere = sandbox.base.path() / "elsewhere"; - given("a root moved before an operation", [&] { - fs::NativeStorage storage(sandbox.root); - stdfs::rename(sandbox.root, elsewhere); - then("every operation fails with rootMoved, without effect, even once a directory is back at the location", [&] { - require(errorOf([&] { - storage.createDirectory("dir"); - }) - == fs::StorageErrc::rootMoved); - require(stdfs::is_empty(elsewhere)); - stdfs::rename(elsewhere, sandbox.root); - require(errorOf([&] { - storage.list(""); - }) - == fs::StorageErrc::rootMoved); - require(stdfs::is_empty(sandbox.root)); - }); - }); - given("another directory put at the location", [&] { - fs::NativeStorage storage(sandbox.root); - stdfs::rename(sandbox.root, elsewhere); - makeDirectories(sandbox.root); - then("it is not taken for the root", [&] { - require(errorOf([&] { - writeFile(storage, "file.txt", "x"); - }) - == fs::StorageErrc::rootMoved); - require(stdfs::is_empty(sandbox.root)); - }); - }); - given("a root moved during a write", [&] { - auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { - if (point == fs::StoragePoint::temporaryCreated) - stdfs::rename(sandbox.root, elsewhere); - }); - fs::NativeStorage storage(sandbox.root, {}, hooks); - then("the commit is abandoned with confinementViolated", [&] { - require(errorOf([&] { - writeFile(storage, "file.txt", "x"); - }) - == fs::StorageErrc::confinementViolated); - require(stdfs::is_empty(elsewhere)); - }); - }); -}}; + given("a root moved before an operation", [&] { + fs::NativeStorage storage(sandbox.root); + stdfs::rename(sandbox.root, elsewhere); + then("every operation fails with rootMoved, without effect, even once a directory is back at the location", [&] { + require(errorOf([&] { + storage.createDirectory("dir"); + }) + == fs::StorageErrc::rootMoved); + require(stdfs::is_empty(elsewhere)); + stdfs::rename(elsewhere, sandbox.root); + require(errorOf([&] { + storage.list(""); + }) + == fs::StorageErrc::rootMoved); + require(stdfs::is_empty(sandbox.root)); + }); + }); + given("another directory put at the location", [&] { + fs::NativeStorage storage(sandbox.root); + stdfs::rename(sandbox.root, elsewhere); + makeDirectories(sandbox.root); + then("it is not taken for the root", [&] { + require(errorOf([&] { + writeFile(storage, "file.txt", "x"); + }) + == fs::StorageErrc::rootMoved); + require(stdfs::is_empty(sandbox.root)); + }); + }); + given("a root moved during a write", [&] { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) + stdfs::rename(sandbox.root, elsewhere); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + then("the commit is abandoned with confinementViolated", [&] { + require(errorOf([&] { + writeFile(storage, "file.txt", "x"); + }) + == fs::StorageErrc::confinementViolated); + require(stdfs::is_empty(elsewhere)); + }); + }); + }}; const Scenario pOSIXDirectories{"POSIX directories another user could move refuse the root or the operation", [] { - Sandbox sandbox; - const auto otherUser = ::geteuid() == 4242u ? 4243u : 4242u; - const auto base = stdfs::canonical(sandbox.base.path()); - const auto root = base / "root"; - auto hooks = make_shared(); - map overrides; - hooks->facts = [&](const stdfs::path& path, fs::DirectoryFacts& facts) { - if (auto found = overrides.find(path); found != overrides.end()) - facts = found->second; - }; - const auto own = static_cast(::geteuid()); - auto facts = [](uint32_t owner, uint32_t mode) { - return fs::DirectoryFacts{owner, S_IFDIR | mode}; - }; + Sandbox sandbox; + const auto otherUser = ::geteuid() == 4242u ? 4243u : 4242u; + const auto base = stdfs::canonical(sandbox.base.path()); + const auto root = base / "root"; + auto hooks = make_shared(); + map overrides; + hooks->facts = [&](const stdfs::path& path, fs::DirectoryFacts& facts) { + if (auto found = overrides.find(path); found != overrides.end()) + facts = found->second; + }; + const auto own = static_cast(::geteuid()); + auto facts = [](uint32_t owner, uint32_t mode) { + return fs::DirectoryFacts{owner, S_IFDIR | mode}; + }; - given("a root owned by another user, even in mode 0755", [&] { - overrides[root] = facts(otherUser, 0755); - then("its declaration is refused", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root, {}, hooks); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("a root its group can write", [&] { - stdfs::permissions(sandbox.root, stdfs::perms::group_write, stdfs::perm_options::add); - then("its declaration is refused, unless the root is declared shared", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root); - }) - == fs::StorageErrc::unsafeDirectory); - fs::NativeStorage shared(sandbox.root, {.shared = true}); - shared.createDirectory("dir"); - }); - }); - given("an ancestor owned by another user, in mode 0755", [&] { - overrides[base] = facts(otherUser, 0755); - then("the declaration is refused", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root, {}, hooks); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("an ancestor writable by the others", [&] { - overrides[base] = facts(own, 0777); - then("the declaration is refused", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root, {}, hooks); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("a sticky ancestor owned by another user", [&] { - overrides[base] = facts(otherUser, 01777); - then("the declaration is refused", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root, {}, hooks); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("a sticky ancestor of the superuser, as /tmp", [&] { - overrides[base] = facts(0, 01777); - then("a next element of the effective user is accepted", [&] { - fs::NativeStorage storage(sandbox.root, {}, hooks); - storage.createDirectory("dir"); - }); - then("a next element of another user is refused", [&] { - overrides[root] = facts(otherUser, 0755); - require(errorOf([&] { - fs::NativeStorage(sandbox.root, {}, hooks); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("a root declared, then an ancestor that becomes unsafe", [&] { - fs::NativeStorage storage(sandbox.root, {}, hooks); - overrides[base] = facts(otherUser, 0755); - then("the next operation is refused before any effect", [&] { - require(errorOf([&] { - storage.createDirectory("dir"); - }) - == fs::StorageErrc::unsafeDirectory); - require(stdfs::is_empty(sandbox.root)); - }); - }); - given("directories inside the root another user could move", [&] { - makeDirectories(sandbox.root / "group" / "deep"); - makeDirectories(sandbox.root / "foreign" / "deep"); - stdfs::permissions(sandbox.root / "group", stdfs::perms::group_write, stdfs::perm_options::add); - overrides[root / "foreign"] = facts(otherUser, 0755); - fs::NativeStorage storage(sandbox.root, {}, hooks); - then("operations traversing them are refused before any effect", [&] { - require(errorOf([&] { - storage.createDirectory("group/deep/new"); - }) - == fs::StorageErrc::unsafeDirectory); - require(errorOf([&] { - writeFile(storage, "foreign/deep/new.txt", "x"); - }) - == fs::StorageErrc::unsafeDirectory); - require(stdfs::is_empty(sandbox.root / "group" / "deep")); - require(stdfs::is_empty(sandbox.root / "foreign" / "deep")); - }); - }); - given("directories the storage creates, whatever the umask", [&] { - const auto previous = ::umask(0); - fs::NativeStorage storage(sandbox.root); - storage.createDirectory("created"); - writeFile(storage, "created/file.txt", "x"); - ::umask(previous); - then("they stay usable by the storage", [&] { - require((stdfs::status(sandbox.root / "created").permissions() & (stdfs::perms::group_write | stdfs::perms::others_write)) == stdfs::perms::none); - require(storage.list("created").entries.size() == 1); - }); - }); -}}; + given("a root owned by another user, even in mode 0755", [&] { + overrides[root] = facts(otherUser, 0755); + then("its declaration is refused", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + }); + }); + given("a root its group can write", [&] { + stdfs::permissions(sandbox.root, stdfs::perms::group_write, stdfs::perm_options::add); + then("its declaration is refused, unless the root is declared shared", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + fs::NativeStorage shared(sandbox.root, {.shared = true}); + shared.createDirectory("dir"); + }); + }); + given("an ancestor owned by another user, in mode 0755", [&] { + overrides[base] = facts(otherUser, 0755); + then("the declaration is refused", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + }); + }); + given("an ancestor writable by the others", [&] { + overrides[base] = facts(own, 0777); + then("the declaration is refused", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + }); + }); + given("a sticky ancestor owned by another user", [&] { + overrides[base] = facts(otherUser, 01777); + then("the declaration is refused", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + }); + }); + given("a sticky ancestor of the superuser, as /tmp", [&] { + overrides[base] = facts(0, 01777); + then("a next element of the effective user is accepted", [&] { + fs::NativeStorage storage(sandbox.root, {}, hooks); + storage.createDirectory("dir"); + }); + then("a next element of another user is refused", [&] { + overrides[root] = facts(otherUser, 0755); + require(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + }); + }); + given("a root declared, then an ancestor that becomes unsafe", [&] { + fs::NativeStorage storage(sandbox.root, {}, hooks); + overrides[base] = facts(otherUser, 0755); + then("the next operation is refused before any effect", [&] { + require(errorOf([&] { + storage.createDirectory("dir"); + }) + == fs::StorageErrc::unsafeDirectory); + require(stdfs::is_empty(sandbox.root)); + }); + }); + given("directories inside the root another user could move", [&] { + makeDirectories(sandbox.root / "group" / "deep"); + makeDirectories(sandbox.root / "foreign" / "deep"); + stdfs::permissions(sandbox.root / "group", stdfs::perms::group_write, stdfs::perm_options::add); + overrides[root / "foreign"] = facts(otherUser, 0755); + fs::NativeStorage storage(sandbox.root, {}, hooks); + then("operations traversing them are refused before any effect", [&] { + require(errorOf([&] { + storage.createDirectory("group/deep/new"); + }) + == fs::StorageErrc::unsafeDirectory); + require(errorOf([&] { + writeFile(storage, "foreign/deep/new.txt", "x"); + }) + == fs::StorageErrc::unsafeDirectory); + require(stdfs::is_empty(sandbox.root / "group" / "deep")); + require(stdfs::is_empty(sandbox.root / "foreign" / "deep")); + }); + }); + given("directories the storage creates, whatever the umask", [&] { + const auto previous = ::umask(0); + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("created"); + writeFile(storage, "created/file.txt", "x"); + ::umask(previous); + then("they stay usable by the storage", [&] { + require((stdfs::status(sandbox.root / "created").permissions() + & (stdfs::perms::group_write | stdfs::perms::others_write)) + == stdfs::perms::none); + require(storage.list("created").entries.size() == 1); + }); + }); + }}; #if defined(__APPLE__) -const Scenario macOSACLs{"macOS ACLs that let another user change a directory refuse the root or the operation", [] { - Sandbox sandbox; - auto grant = [](const stdfs::path& directory, const string& who) { - const auto command = "chmod +a '" + who + " allow add_file,add_subdirectory,delete_child' '" + directory.string() + "'"; - require(std::system(command.c_str()) == 0); - }; +const Scenario macOSACLs{ + "macOS ACLs that let another user change a directory refuse the root or the operation", + [] { + Sandbox sandbox; + auto grant = [](const stdfs::path& directory, const string& who) { + const auto command = "chmod +a '" + who + " allow add_file,add_subdirectory,delete_child' '" + directory.string() + "'"; + require(std::system(command.c_str()) == 0); + }; - given("a root in mode 0700 whose ACL lets everyone add and remove entries", [&] { - stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); - grant(sandbox.root, "everyone"); - then("its declaration is refused, unless the root is declared shared", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root); - }) - == fs::StorageErrc::unsafeDirectory); - fs::NativeStorage shared(sandbox.root, {.shared = true}); - shared.createDirectory("dir"); + given("a root in mode 0700 whose ACL lets everyone add and remove entries", [&] { + stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); + grant(sandbox.root, "everyone"); + then("its declaration is refused, unless the root is declared shared", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + fs::NativeStorage shared(sandbox.root, {.shared = true}); + shared.createDirectory("dir"); + }); }); - }); - given("an ancestor whose ACL lets everyone remove its entries", [&] { - grant(sandbox.base.path(), "everyone"); - then("the declaration is refused", [&] { - require(errorOf([&] { - fs::NativeStorage(sandbox.root); - }) - == fs::StorageErrc::unsafeDirectory); - }); - }); - given("a directory inside the root granted to everyone after the declaration", [&] { - fs::NativeStorage storage(sandbox.root); - makeDirectories(sandbox.root / "shared" / "deep"); - grant(sandbox.root / "shared", "everyone"); - then("operations through it are refused before any effect", [&] { - require(errorOf([&] { - storage.createDirectory("shared/deep/new"); - }) - == fs::StorageErrc::unsafeDirectory); - require(stdfs::is_empty(sandbox.root / "shared" / "deep")); + given("an ancestor whose ACL lets everyone remove its entries", [&] { + grant(sandbox.base.path(), "everyone"); + then("the declaration is refused", [&] { + require(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + }); }); - }); - given("a root whose ACL passes those rights to everyone, only to its descendants", [&] { - stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); - const auto command = "chmod +a 'everyone allow add_file,add_subdirectory,delete_child,file_inherit,directory_inherit,only_inherit' '" - + sandbox.root.string() + "'"; - require(std::system(command.c_str()) == 0); - then("the root is accepted, and a subdirectory that inherits the rights is refused when traversed", [&] { + given("a directory inside the root granted to everyone after the declaration", [&] { fs::NativeStorage storage(sandbox.root); - storage.createDirectory("inherits"); - require(errorOf([&] { - storage.list("inherits"); - }) - == fs::StorageErrc::unsafeDirectory); + makeDirectories(sandbox.root / "shared" / "deep"); + grant(sandbox.root / "shared", "everyone"); + then("operations through it are refused before any effect", [&] { + require(errorOf([&] { + storage.createDirectory("shared/deep/new"); + }) + == fs::StorageErrc::unsafeDirectory); + require(stdfs::is_empty(sandbox.root / "shared" / "deep")); + }); }); - }); - given("an ACL that grants those rights to the effective user only", [&] { - grant(sandbox.root, "user:" + string(::getpwuid(::geteuid())->pw_name)); - then("the root is accepted", [&] { - fs::NativeStorage storage(sandbox.root); - storage.createDirectory("dir"); + given("a root whose ACL passes those rights to everyone, only to its descendants", [&] { + stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); + const auto command = "chmod +a 'everyone allow add_file,add_subdirectory,delete_child,file_inherit,directory_inherit,only_inherit' '" + + sandbox.root.string() + "'"; + require(std::system(command.c_str()) == 0); + then("the root is accepted, and a subdirectory that inherits the rights is refused when traversed", [&] { + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("inherits"); + require(errorOf([&] { + storage.list("inherits"); + }) + == fs::StorageErrc::unsafeDirectory); + }); }); - }); -}}; + given("an ACL that grants those rights to the effective user only", [&] { + grant(sandbox.root, "user:" + string(::getpwuid(::geteuid())->pw_name)); + then("the root is accepted", [&] { + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("dir"); + }); + }); + }}; #endif const Scenario replacedFile{"A replaced file keeps the permission bits it has at the commit", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - static constexpr auto privateBits = stdfs::perms::owner_read | stdfs::perms::owner_write; - given("a private file", [&] { - writeDisk(sandbox.root / "private.txt", "old"); - stdfs::permissions(sandbox.root / "private.txt", privateBits, stdfs::perm_options::replace); - writeFile(storage, "private.txt", "new secret", fs::WriteMode::replace); - then("its replacement is private too", [&] { - require(readDisk(sandbox.root / "private.txt") == "new secret"); - require(stdfs::status(sandbox.root / "private.txt").permissions() == privateBits); - }); - }); - given("a public file that the storage replaces by a private one while a write to it is open", [&] { - writeDisk(sandbox.root / "doc.txt", "public"); - stdfs::permissions(sandbox.root / "doc.txt", privateBits | stdfs::perms::group_read | stdfs::perms::others_read, stdfs::perm_options::replace); - auto writer = storage.beginWrite("doc.txt", fs::WriteMode::replace); - writer.write(span("new", 3)); - writeDisk(sandbox.root / "private.txt", "private"); - stdfs::permissions(sandbox.root / "private.txt", privateBits, stdfs::perm_options::replace); - storage.remove("doc.txt"); - storage.rename("private.txt", "doc.txt"); - writer.commit(); - then("the commit takes the rights of the file it replaces at that moment", [&] { - require(readDisk(sandbox.root / "doc.txt") == "new"); - require(stdfs::status(sandbox.root / "doc.txt").permissions() == privateBits); - }); - }); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + static constexpr auto privateBits = stdfs::perms::owner_read | stdfs::perms::owner_write; + given("a private file", [&] { + writeDisk(sandbox.root / "private.txt", "old"); + stdfs::permissions(sandbox.root / "private.txt", privateBits, stdfs::perm_options::replace); + writeFile(storage, "private.txt", "new secret", fs::WriteMode::replace); + then("its replacement is private too", [&] { + require(readDisk(sandbox.root / "private.txt") == "new secret"); + require(stdfs::status(sandbox.root / "private.txt").permissions() == privateBits); + }); + }); + given("a public file that the storage replaces by a private one while a write to it is open", [&] { + writeDisk(sandbox.root / "doc.txt", "public"); + stdfs::permissions(sandbox.root / "doc.txt", + privateBits | stdfs::perms::group_read | stdfs::perms::others_read, + stdfs::perm_options::replace); + auto writer = storage.beginWrite("doc.txt", fs::WriteMode::replace); + writer.write(span("new", 3)); + writeDisk(sandbox.root / "private.txt", "private"); + stdfs::permissions(sandbox.root / "private.txt", privateBits, stdfs::perm_options::replace); + storage.remove("doc.txt"); + storage.rename("private.txt", "doc.txt"); + writer.commit(); + then("the commit takes the rights of the file it replaces at that moment", [&] { + require(readDisk(sandbox.root / "doc.txt") == "new"); + require(stdfs::status(sandbox.root / "doc.txt").permissions() == privateBits); + }); + }); + }}; #if !defined(__APPLE__) namespace { @@ -977,34 +989,34 @@ const string aclVersion("\x02\0\0\0", 4); #endif const Scenario replacedFileKeeps{"A replaced file keeps its access control list", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - const auto file = sandbox.root / "guarded.txt"; - writeDisk(file, "old"); + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "guarded.txt"; + writeDisk(file, "old"); #if defined(__APPLE__) - given("an ACL that denies another user reading the file", [&] { - require(std::system(("chmod +a 'user:nobody deny read' '" + file.string() + "'").c_str()) == 0); - writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); - then("the new file keeps it", [&] { - require(readDisk(file) == "new secret"); - require(std::system(("ls -le '" + file.string() + "' | grep -q 'user:nobody deny read'").c_str()) == 0); - }); - }); - given("an ACL that denies everyone, the effective user included, reading the file", [&] { - require(std::system(("chmod +a 'everyone deny read' '" + file.string() + "'").c_str()) == 0); - then("the ACL cannot be read, so the replacement is refused and the file left as it was", [&] { - require(errorOf([&] { - storage.openRead("guarded.txt"); - }) - == fs::StorageErrc::accessDenied); - require(errorOf([&] { - writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); - }) - == fs::StorageErrc::accessDenied); - require(std::system(("ls -le '" + file.string() + "' | grep -q 'everyone deny read'").c_str()) == 0); - require(namesOn(sandbox.root) == vector{"guarded.txt"}); - }); - }); + given("an ACL that denies another user reading the file", [&] { + require(std::system(("chmod +a 'user:nobody deny read' '" + file.string() + "'").c_str()) == 0); + writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); + then("the new file keeps it", [&] { + require(readDisk(file) == "new secret"); + require(std::system(("ls -le '" + file.string() + "' | grep -q 'user:nobody deny read'").c_str()) == 0); + }); + }); + given("an ACL that denies everyone, the effective user included, reading the file", [&] { + require(std::system(("chmod +a 'everyone deny read' '" + file.string() + "'").c_str()) == 0); + then("the ACL cannot be read, so the replacement is refused and the file left as it was", [&] { + require(errorOf([&] { + storage.openRead("guarded.txt"); + }) + == fs::StorageErrc::accessDenied); + require(errorOf([&] { + writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); + }) + == fs::StorageErrc::accessDenied); + require(std::system(("ls -le '" + file.string() + "' | grep -q 'everyone deny read'").c_str()) == 0); + require(namesOn(sandbox.root) == vector{"guarded.txt"}); + }); + }); #else // The POSIX access ACL: the owner reads and writes, the user nobody gets nothing, the group and the others read. const string acl = aclVersion + aclEntry(0x01, 6, aclUndefined) + aclEntry(0x02, 0, aclNobody) + aclEntry(0x04, 4, aclUndefined) @@ -1020,293 +1032,302 @@ const Scenario replacedFileKeeps{"A replaced file keeps its access control list" kept.resize(static_cast(size)); require(kept.find(aclEntry(0x02, 0, aclNobody)) != string::npos); #endif -}}; + }}; -const Scenario replacedFileWithout{"A replaced file without an ACL gets none from its directory", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - const auto file = sandbox.root / "plain.txt"; - writeDisk(file, "old"); - stdfs::permissions(file, stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, stdfs::perm_options::replace); +const Scenario replacedFileWithout{ + "A replaced file without an ACL gets none from its directory", + [] { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "plain.txt"; + writeDisk(file, "old"); + stdfs::permissions(file, stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, stdfs::perm_options::replace); #if defined(__APPLE__) - // Entries the directory passes on to new files: the temporary file receives them, the file it replaces had none. - require(std::system(("chmod +a 'user:nobody allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); - writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); - require(std::system(("ls -le '" + file.string() + "' | grep -q nobody").c_str()) != 0); + // Entries the directory passes on to new files: the temporary file receives them, the file it replaces had none. + require(std::system(("chmod +a 'user:nobody allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); + writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); + require(std::system(("ls -le '" + file.string() + "' | grep -q nobody").c_str()) != 0); #else - // A default ACL of the directory that lets the user nobody read new files. - const string defaults = aclVersion + aclEntry(0x01, 7, aclUndefined) + aclEntry(0x02, 4, aclNobody) + aclEntry(0x04, 5, aclUndefined) - + aclEntry(0x10, 5, aclUndefined) + aclEntry(0x20, 5, aclUndefined); - if (::setxattr(sandbox.root.c_str(), "system.posix_acl_default", defaults.data(), defaults.size(), 0) != 0) - skip("This file system has no POSIX ACL"); - writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); - require(::getxattr(file.c_str(), "system.posix_acl_access", nullptr, 0) < 0); + // A default ACL of the directory that lets the user nobody read new files. + const string defaults = aclVersion + aclEntry(0x01, 7, aclUndefined) + aclEntry(0x02, 4, aclNobody) + aclEntry(0x04, 5, aclUndefined) + + aclEntry(0x10, 5, aclUndefined) + aclEntry(0x20, 5, aclUndefined); + if (::setxattr(sandbox.root.c_str(), "system.posix_acl_default", defaults.data(), defaults.size(), 0) != 0) + skip("This file system has no POSIX ACL"); + writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); + require(::getxattr(file.c_str(), "system.posix_acl_access", nullptr, 0) < 0); #endif - require(readDisk(file) == "new secret"); - require(stdfs::status(file).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read)); -}}; + require(readDisk(file) == "new secret"); + require(stdfs::status(file).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read)); + }}; const Scenario runningOut{"Running out of descriptors does not mark the root as moved", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - // GCC 13's UBSan vptr check opens a pipe. Exercise the error types before denying it the descriptors for its - // first check; checks stay enabled, and an invalid vptr still misses that valid-type cache entry. - require(errorOf([&] { - storage.openRead("missing-before-exhaustion"); - }) - == fs::StorageErrc::notFound); - struct ::rlimit previous{}; - require(::getrlimit(RLIMIT_NOFILE, &previous) == 0); - struct Pressure { - ::rlimit previous; - vector held; - int release() { - for (const int descriptor : held) - ::close(descriptor); - held.clear(); - return ::setrlimit(RLIMIT_NOFILE, &previous); - } - ~Pressure() { - release(); - } - } pressure{previous, {}}; - auto lowered = previous; - lowered.rlim_cur = std::min(previous.rlim_cur, 256); - require(::setrlimit(RLIMIT_NOFILE, &lowered) == 0); - auto& held = pressure.held; - for (int descriptor = ::dup(0); descriptor >= 0; descriptor = ::dup(0)) - held.push_back(descriptor); - // One descriptor left: `/` opens, the next component of the declared location does not. - const bool hadDescriptors = !held.empty(); - std::exception_ptr exhausted; - if (hadDescriptors) { - ::close(held.back()); - held.pop_back(); - try { - storage.createDirectory("dir"); - } catch (...) { - exhausted = std::current_exception(); - } - } - // Failure reports and sanitizer diagnostics may themselves open files. Do not assert under descriptor exhaustion. - const int restored = pressure.release(); - require(restored == 0); - require(hadDescriptors); - require(exhausted); - try { - std::rethrow_exception(exhausted); - } catch (const fs::StorageError& error) { - require(error.errc() != fs::StorageErrc::rootMoved); - } - storage.createDirectory("dir"); - require(stdfs::is_directory(sandbox.root / "dir")); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + // GCC 13's UBSan vptr check opens a pipe. Exercise the error types before denying it the descriptors for its + // first check; checks stay enabled, and an invalid vptr still misses that valid-type cache entry. + require(errorOf([&] { + storage.openRead("missing-before-exhaustion"); + }) + == fs::StorageErrc::notFound); + struct ::rlimit previous{}; + require(::getrlimit(RLIMIT_NOFILE, &previous) == 0); + struct Pressure { + ::rlimit previous; + vector held; + int release() { + for (const int descriptor : held) + ::close(descriptor); + held.clear(); + return ::setrlimit(RLIMIT_NOFILE, &previous); + } + ~Pressure() { + release(); + } + } pressure{previous, {}}; + auto lowered = previous; + lowered.rlim_cur = std::min(previous.rlim_cur, 256); + require(::setrlimit(RLIMIT_NOFILE, &lowered) == 0); + auto& held = pressure.held; + for (int descriptor = ::dup(0); descriptor >= 0; descriptor = ::dup(0)) + held.push_back(descriptor); + // One descriptor left: `/` opens, the next component of the declared location does not. + const bool hadDescriptors = !held.empty(); + std::exception_ptr exhausted; + if (hadDescriptors) { + ::close(held.back()); + held.pop_back(); + try { + storage.createDirectory("dir"); + } catch (...) { + exhausted = std::current_exception(); + } + } + // Failure reports and sanitizer diagnostics may themselves open files. Do not assert under descriptor exhaustion. + const int restored = pressure.release(); + require(restored == 0); + require(hadDescriptors); + require(exhausted); + try { + std::rethrow_exception(exhausted); + } catch (const fs::StorageError& error) { + require(error.errc() != fs::StorageErrc::rootMoved); + } + storage.createDirectory("dir"); + require(stdfs::is_directory(sandbox.root / "dir")); + }}; #if defined(__APPLE__) const Scenario temporaryFile{"The temporary file of a replacing write keeps no inherited ACL", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - writeDisk(sandbox.root / "private.txt", "old"); - stdfs::permissions(sandbox.root / "private.txt", stdfs::perms::owner_read | stdfs::perms::owner_write, stdfs::perm_options::replace); - // The ACL the directory passes on lets everyone read new files: not the temporary file of a private one. - require(std::system(("chmod +a 'everyone allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); - auto writer = storage.beginWrite("private.txt", fs::WriteMode::replace); - writer.write(span("secret", 6)); - // The temporary file lives in a private directory created without the inherited entries, so it never had them. - const auto temporary = temporaryOf(sandbox.root); - require(std::system(("ls -led '" + temporary.parent_path().string() + "' | grep -q everyone").c_str()) != 0); - require(std::system(("ls -le '" + temporary.string() + "' | grep -q everyone").c_str()) != 0); - writer.commit(); - require(std::system(("ls -le '" + (sandbox.root / "private.txt").string() + "' | grep -q everyone").c_str()) != 0); - require(stdfs::status(sandbox.root / "private.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeDisk(sandbox.root / "private.txt", "old"); + stdfs::permissions(sandbox.root / "private.txt", + stdfs::perms::owner_read | stdfs::perms::owner_write, + stdfs::perm_options::replace); + // The ACL the directory passes on lets everyone read new files: not the temporary file of a private one. + require(std::system(("chmod +a 'everyone allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); + auto writer = storage.beginWrite("private.txt", fs::WriteMode::replace); + writer.write(span("secret", 6)); + // The temporary file lives in a private directory created without the inherited entries, so it never had them. + const auto temporary = temporaryOf(sandbox.root); + require(std::system(("ls -led '" + temporary.parent_path().string() + "' | grep -q everyone").c_str()) != 0); + require(std::system(("ls -le '" + temporary.string() + "' | grep -q everyone").c_str()) != 0); + writer.commit(); + require(std::system(("ls -le '" + (sandbox.root / "private.txt").string() + "' | grep -q everyone").c_str()) != 0); + require(stdfs::status(sandbox.root / "private.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); + }}; #endif const Scenario replacingWrite{"A replacing write is private from the creation of its temporary file", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - // No file to replace when the write begins: a private one may appear under that name before the commit. - auto writer = storage.beginWrite("later.txt", fs::WriteMode::replace); - writer.write(span("secret", 6)); - const auto temporary = temporaryOf(sandbox.root); - require(fs::isTemporaryName(temporary.parent_path().filename().string())); - require(stdfs::status(temporary).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); - require(stdfs::status(temporary.parent_path()).permissions() == stdfs::perms::owner_all); - writer.commit(); - require(readDisk(sandbox.root / "later.txt") == "secret"); - require(stdfs::status(sandbox.root / "later.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); - require(namesOn(sandbox.root) == vector{"later.txt"}); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + // No file to replace when the write begins: a private one may appear under that name before the commit. + auto writer = storage.beginWrite("later.txt", fs::WriteMode::replace); + writer.write(span("secret", 6)); + const auto temporary = temporaryOf(sandbox.root); + require(fs::isTemporaryName(temporary.parent_path().filename().string())); + require(stdfs::status(temporary).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); + require(stdfs::status(temporary.parent_path()).permissions() == stdfs::perms::owner_all); + writer.commit(); + require(readDisk(sandbox.root / "later.txt") == "secret"); + require(stdfs::status(sandbox.root / "later.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); + require(namesOn(sandbox.root) == vector{"later.txt"}); + }}; const Scenario replacedFileKeepsGroup{"A replaced file keeps its group", [] { - // A group of the effective user other than its effective group, which a new file would not get. - const int count = ::getgroups(0, nullptr); - vector groups(static_cast(max(count, 0))); - if (count > 0) - groups.resize(static_cast(::getgroups(count, groups.data()))); - const auto other = ranges::find_if(groups, [](gid_t group) { - return group != ::getegid(); - }); - if (other == groups.end()) - skip("The effective user belongs to no other group"); - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root); - const auto file = sandbox.root / "shared.txt"; - writeDisk(file, "old"); - require(::chown(file.c_str(), static_cast(-1), *other) == 0); - stdfs::permissions(file, stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, stdfs::perm_options::replace); - writeFile(storage, "shared.txt", "new", fs::WriteMode::replace); - struct ::stat status{}; - require(::stat(file.c_str(), &status) == 0); - require(status.st_gid == *other); - require((status.st_mode & 0777) == 0640); - require(readDisk(file) == "new"); -}}; + // A group of the effective user other than its effective group, which a new file would not get. + const int count = ::getgroups(0, nullptr); + vector groups(static_cast(max(count, 0))); + if (count > 0) + groups.resize(static_cast(::getgroups(count, groups.data()))); + const auto other = ranges::find_if(groups, [](gid_t group) { + return group != ::getegid(); + }); + if (other == groups.end()) + skip("The effective user belongs to no other group"); + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "shared.txt"; + writeDisk(file, "old"); + require(::chown(file.c_str(), static_cast(-1), *other) == 0); + stdfs::permissions(file, + stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, + stdfs::perm_options::replace); + writeFile(storage, "shared.txt", "new", fs::WriteMode::replace); + struct ::stat status{}; + require(::stat(file.c_str(), &status) == 0); + require(status.st_gid == *other); + require((status.st_mode & 0777) == 0640); + require(readDisk(file) == "new"); + }}; -#ifndef _WIN32 + #ifndef _WIN32 const Scenario directoriesMade{"Directories made by the tests stay closed to group and others under a permissive umask", [] { - // Restores the umask on every exit, a failing REQUIRE or an exception included: it is process-wide. - struct UmaskScope { - mode_t previous; - UmaskScope() : previous(::umask(0)) {} - UmaskScope(const UmaskScope&) = delete; - UmaskScope& operator=(const UmaskScope&) = delete; - ~UmaskScope() { - ::umask(previous); - } - } umaskScope; - Sandbox sandbox; - makeDirectories(sandbox.root / "a" / "b"); - for (const auto& directory : {sandbox.root / "a", sandbox.root / "a" / "b"}) { - struct stat status{}; - require(::stat(directory.c_str(), &status) == 0); - require((status.st_mode & (S_IWGRP | S_IWOTH)) == 0); - } - fs::NativeStorage storage(sandbox.root); - require(storage.list("a").entries.size() == 1); - require(storage.list("a/b").entries.empty()); -}}; -#endif + // Restores the umask on every exit, a failing REQUIRE or an exception included: it is process-wide. + struct UmaskScope { + mode_t previous; + UmaskScope() : previous(::umask(0)) {} + UmaskScope(const UmaskScope&) = delete; + UmaskScope& operator=(const UmaskScope&) = delete; + ~UmaskScope() { + ::umask(previous); + } + } umaskScope; + Sandbox sandbox; + makeDirectories(sandbox.root / "a" / "b"); + for (const auto& directory : {sandbox.root / "a", sandbox.root / "a" / "b"}) { + struct stat status{}; + require(::stat(directory.c_str(), &status) == 0); + require((status.st_mode & (S_IWGRP | S_IWOTH)) == 0); + } + fs::NativeStorage storage(sandbox.root); + require(storage.list("a").entries.size() == 1); + require(storage.list("a/b").entries.empty()); + }}; + #endif const Scenario linkFollowed{"A link followed inside the root never reaches a temporary file", [] { - Sandbox sandbox; - fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); - auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); - writer.write(span("partial", 7)); - const auto temporary = namesOn(sandbox.root).at(0); - stdfs::create_symlink(temporary, sandbox.root / "alias"); - makeDirectories(sandbox.root / "dir"); - stdfs::create_symlink("../" + temporary, sandbox.root / "dir" / "deep"); - require(errorOf([&] { - storage.openRead("alias"); - }) - == fs::StorageErrc::linkRefused); - require(errorOf([&] { - storage.openRead("dir/deep"); - }) - == fs::StorageErrc::linkRefused); - writer.commit(); - require(readAll(storage.openRead("report.txt")) == "partial"); -}}; + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); + auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + const auto temporary = namesOn(sandbox.root).at(0); + stdfs::create_symlink(temporary, sandbox.root / "alias"); + makeDirectories(sandbox.root / "dir"); + stdfs::create_symlink("../" + temporary, sandbox.root / "dir" / "deep"); + require(errorOf([&] { + storage.openRead("alias"); + }) + == fs::StorageErrc::linkRefused); + require(errorOf([&] { + storage.openRead("dir/deep"); + }) + == fs::StorageErrc::linkRefused); + writer.commit(); + require(readAll(storage.openRead("report.txt")) == "partial"); + }}; const Scenario rootUnder{"A root under the real /tmp of the superuser is accepted", [] { - // /tmp is owned by the superuser, writable by all and sticky: an element of the effective user under it is safe. - std::error_code error; - if (!stdfs::is_directory("/tmp", error)) - skip("No /tmp on this system"); - struct ::stat status{}; - require(::stat("/tmp", &status) == 0); - if (status.st_uid != 0 || (status.st_mode & S_ISVTX) == 0) - skip("/tmp is not a sticky directory of the superuser here"); - const auto root = stdfs::path("/tmp") / ("webfront_storage_" + to_string(::getpid())); - stdfs::create_directory(root); - stdfs::permissions(root, stdfs::perms::owner_all, stdfs::perm_options::replace); - fs::NativeStorage storage(root); - writeFile(storage, "file.txt", "x"); - require(storage.list("").entries.size() == 1); - stdfs::remove_all(root); -}}; + // /tmp is owned by the superuser, writable by all and sticky: an element of the effective user under it is safe. + std::error_code error; + if (!stdfs::is_directory("/tmp", error)) + skip("No /tmp on this system"); + struct ::stat status{}; + require(::stat("/tmp", &status) == 0); + if (status.st_uid != 0 || (status.st_mode & S_ISVTX) == 0) + skip("/tmp is not a sticky directory of the superuser here"); + const auto root = stdfs::path("/tmp") / ("webfront_storage_" + to_string(::getpid())); + stdfs::create_directory(root); + stdfs::permissions(root, stdfs::perms::owner_all, stdfs::perm_options::replace); + fs::NativeStorage storage(root); + writeFile(storage, "file.txt", "x"); + require(storage.list("").entries.size() == 1); + stdfs::remove_all(root); + }}; #endif #ifdef _WIN32 -const Scenario windowsOpens{"Windows opens a root from its drive, its share or its volume", [] { - using Split = std::pair>; - const auto split = [](const wchar_t* path) { - return fs::detail::windows::splitLocation(path); - }; - require(split(LR"(C:\a\b)") - == Split{ - LR"(\\?\C:\)", - {"a", "b"} - }); - require(split(LR"(C:\)") == Split{LR"(\\?\C:\)", {}}); - require(split(LR"(\\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); - require(split(LR"(\\server\share)") == Split{LR"(\\?\UNC\server\share\)", {}}); - // Extended paths, whose root name MSVC reports as `\\?`. - require(split(LR"(\\?\C:\a\b)") - == Split{ - LR"(\\?\C:\)", - {"a", "b"} - }); - require(split(LR"(\\?\UNC\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); - require(split(LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\a)") == Split{LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\)", {"a"}}); - for (const auto* refused : {LR"(\\server)", LR"(\\?\UNC\server)", LR"(\\?\GLOBALROOT\Device\HarddiskVolume1\a)", LR"(\\?\globalroot\Device\X)", LR"(a\b)"}) - require(errorOf([&] { - split(refused); - }) - == fs::StorageErrc::invalidPath); -}}; +const Scenario windowsOpens{ + "Windows opens a root from its drive, its share or its volume", + [] { + using Split = std::pair>; + const auto split = [](const wchar_t* path) { + return fs::detail::windows::splitLocation(path); + }; + require(split(LR"(C:\a\b)") + == Split{ + LR"(\\?\C:\)", + {"a", "b"} + }); + require(split(LR"(C:\)") == Split{LR"(\\?\C:\)", {}}); + require(split(LR"(\\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); + require(split(LR"(\\server\share)") == Split{LR"(\\?\UNC\server\share\)", {}}); + // Extended paths, whose root name MSVC reports as `\\?`. + require(split(LR"(\\?\C:\a\b)") + == Split{ + LR"(\\?\C:\)", + {"a", "b"} + }); + require(split(LR"(\\?\UNC\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); + require(split(LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\a)") == Split{LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\)", {"a"}}); + for (const auto* refused : + {LR"(\\server)", LR"(\\?\UNC\server)", LR"(\\?\GLOBALROOT\Device\HarddiskVolume1\a)", LR"(\\?\globalroot\Device\X)", LR"(a\b)"}) + require(errorOf([&] { + split(refused); + }) + == fs::StorageErrc::invalidPath); + }}; const Scenario windowsFinds{"Windows finds a directory below a root at the top of its volume", [] { - using fs::detail::windows::isBelow; - require(isBelow(LR"(\Device\HarddiskVolume3\Users)", LR"(\Device\HarddiskVolume3\)")); - require(isBelow(LR"(\Device\HarddiskVolume3\)", LR"(\Device\HarddiskVolume3\)")); - require(isBelow(LR"(\Device\HarddiskVolume3\a\b)", LR"(\device\harddiskvolume3\A)")); - require(!isBelow(LR"(\Device\HarddiskVolume3\ab)", LR"(\Device\HarddiskVolume3\a)")); - require(!isBelow(LR"(\Device\HarddiskVolume4\a)", LR"(\Device\HarddiskVolume3\)")); + using fs::detail::windows::isBelow; + require(isBelow(LR"(\Device\HarddiskVolume3\Users)", LR"(\Device\HarddiskVolume3\)")); + require(isBelow(LR"(\Device\HarddiskVolume3\)", LR"(\Device\HarddiskVolume3\)")); + require(isBelow(LR"(\Device\HarddiskVolume3\a\b)", LR"(\device\harddiskvolume3\A)")); + require(!isBelow(LR"(\Device\HarddiskVolume3\ab)", LR"(\Device\HarddiskVolume3\a)")); + require(!isBelow(LR"(\Device\HarddiskVolume4\a)", LR"(\Device\HarddiskVolume3\)")); - given("a root declared at the top of the volume of the temporary directory", [&] { - Sandbox sandbox; - const auto root = stdfs::canonical(sandbox.root).root_path(); - const auto relative = stdfs::canonical(sandbox.root).relative_path().generic_string(); - fs::NativeStorage storage(root); - then("its subdirectories are listed and written in, inside the root", [&] { - require(!storage.list("").entries.empty()); - storage.createDirectory(relative + "/dir"); - require(stdfs::is_directory(sandbox.root / "dir")); - require(storage.list(relative).entries.size() == 1); - writeFile(storage, relative + "/dir/file.txt", "data"); - require(readDisk(sandbox.root / "dir" / "file.txt") == "data"); - }); - }); -}}; + given("a root declared at the top of the volume of the temporary directory", [&] { + Sandbox sandbox; + const auto root = stdfs::canonical(sandbox.root).root_path(); + const auto relative = stdfs::canonical(sandbox.root).relative_path().generic_string(); + fs::NativeStorage storage(root); + then("its subdirectories are listed and written in, inside the root", [&] { + require(!storage.list("").entries.empty()); + storage.createDirectory(relative + "/dir"); + require(stdfs::is_directory(sandbox.root / "dir")); + require(storage.list(relative).entries.size() == 1); + writeFile(storage, relative + "/dir/file.txt", "data"); + require(readDisk(sandbox.root / "dir" / "file.txt") == "data"); + }); + }); + }}; const Scenario windowsHolds{"Windows holds the directories of an operation so that nobody moves them", [] { - Sandbox sandbox; - makeDirectories(sandbox.root / "a" / "b"); - std::error_code rootRename, directoryRename, ancestorRename, baseRename; + Sandbox sandbox; + makeDirectories(sandbox.root / "a" / "b"); + std::error_code rootRename, directoryRename, ancestorRename, baseRename; - given("moves attempted while the temporary file is written and before the commit", [&] { - auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { - if (point == fs::StoragePoint::temporaryCreated) { - stdfs::rename(sandbox.root / "a" / "b", sandbox.outside / "b", directoryRename); - // An ancestor of the root is not held: NTFS refuses to rename a directory below which a handle is open. - stdfs::rename(sandbox.base.path(), sandbox.base.path().string() + "-moved", baseRename); - } - if (point == fs::StoragePoint::beforeCommit) - stdfs::rename(sandbox.root / "a", sandbox.outside / "a", ancestorRename); - }); - fs::NativeStorage storage(sandbox.root, {}, hooks); - stdfs::rename(sandbox.root, sandbox.base.path() / "elsewhere", rootRename); - writeFile(storage, "a/b/file.txt", "data"); - then("each move fails and the write ends under the root", [&] { - require(rootRename); - require(directoryRename); - require(ancestorRename); - require(baseRename); - require(readDisk(sandbox.root / "a" / "b" / "file.txt") == "data"); - require(sandbox.outsideUntouched()); - }); - }); -}}; + given("moves attempted while the temporary file is written and before the commit", [&] { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) { + stdfs::rename(sandbox.root / "a" / "b", sandbox.outside / "b", directoryRename); + // An ancestor of the root is not held: NTFS refuses to rename a directory below which a handle is open. + stdfs::rename(sandbox.base.path(), sandbox.base.path().string() + "-moved", baseRename); + } + if (point == fs::StoragePoint::beforeCommit) + stdfs::rename(sandbox.root / "a", sandbox.outside / "a", ancestorRename); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + stdfs::rename(sandbox.root, sandbox.base.path() / "elsewhere", rootRename); + writeFile(storage, "a/b/file.txt", "data"); + then("each move fails and the write ends under the root", [&] { + require(rootRename); + require(directoryRename); + require(ancestorRename); + require(baseRename); + require(readDisk(sandbox.root / "a" / "b" / "file.txt") == "data"); + require(sandbox.outsideUntouched()); + }); + }); + }}; #endif diff --git a/test/unit/NativeWindowTests.cpp b/test/unit/NativeWindowTests.cpp index 108e99cf..277f7dc2 100644 --- a/test/unit/NativeWindowTests.cpp +++ b/test/unit/NativeWindowTests.cpp @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief Typed access to the native window of an embedded frontend, and its link to a connection (#463, ADR-020). #include "InjectableNetworking.hpp" -#include #include #include #include +#include #include #include @@ -22,7 +22,9 @@ using namespace webfront::frontend; namespace webfront::testing { template struct LaunchSecret { - static const std::string& of(const Application& app) { return app.viewSecret; } + static const std::string& of(const Application& app) { + return app.viewSecret; + } }; } // namespace webfront::testing @@ -56,9 +58,11 @@ struct LifecycleTag; // A frontend that publishes a window, and one that has none. struct WindowFrontend : DefaultBrowserFrontend { - static NativeWindow nativeWindow() { return nativeWindowHostOf().window(); } + static NativeWindow nativeWindow() { + return nativeWindowHostOf().window(); + } }; -struct NoWindowFrontend : DefaultBrowserFrontend { }; +struct NoWindowFrontend : DefaultBrowserFrontend {}; const std::string upgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; @@ -89,7 +93,9 @@ void freshNetwork() { template typename Application::UI connect(Application& app, const std::string& proof) { std::optional browser; - app.onUIStarted([&](typename Application::UI ui) { browser = ui; }); + app.onUIStarted([&](typename Application::UI ui) { + browser = ui; + }); BrowserSocket::receive(std::as_bytes(std::span(upgradeRequest))); msg::Handshake handshake; std::vector payload(handshake.header().begin(), handshake.header().end()); @@ -102,158 +108,166 @@ typename Application::UI connect(Application& app, const std::string& proof) { } // namespace const Scenario nativeWindowGiven{"The native window is given on the interface thread while it is published", {"native-window"}, [] { - given("a handle that belongs to no frontend", [&] { - then("it answers unsupported", [&] { - require(errorOf(NativeWindow{}.get()) == NativeWindowError::unsupported); - }); - }); - given("a frontend whose window is not created yet", [&] { - const auto handle = nativeWindowHostOf().window(); - then("it answers notOpen", [&] { - require(errorOf(handle.get()) == NativeWindowError::notOpen); - }); - andWhen("the loop is attached but nothing is published", [&] { - Session session; - then("it still answers notOpen", [&] { - require(errorOf(handle.get()) == NativeWindowError::notOpen); - }); - }); - }); - given("a published window", [&] { - Session session; - const auto handle = nativeWindowHostOf().window(); - const auto generation = session.publish("x11:1a2b"); - when("it is read on the interface thread", [&] { - const auto window = handle.get(); - then("it is the toolkit object, with its portal identifier", [&] { + given("a handle that belongs to no frontend", [&] { + then("it answers unsupported", [&] { + require(errorOf(NativeWindow{}.get()) == NativeWindowError::unsupported); + }); + }); + given("a frontend whose window is not created yet", [&] { + const auto handle = nativeWindowHostOf().window(); + then("it answers notOpen", [&] { + require(errorOf(handle.get()) == NativeWindowError::notOpen); + }); + andWhen("the loop is attached but nothing is published", [&] { + Session session; + then("it still answers notOpen", [&] { + require(errorOf(handle.get()) == NativeWindowError::notOpen); + }); + }); + }); + given("a published window", [&] { + Session session; + const auto handle = nativeWindowHostOf().window(); + const auto generation = session.publish("x11:1a2b"); + when("it is read on the interface thread", [&] { + const auto window = handle.get(); + then("it is the toolkit object, with its portal identifier", [&] { + require(window.has_value()); + check(window->kind == NativeWindowKind::gtk); + check(window->pointer == &windowObject); + check(window->portalParent == "x11:1a2b"); + }); + }); + when("it is read from another thread", [&] { + const auto answer = std::async(std::launch::async, [&] { + return handle.get(); + }).get(); + then("it is refused: a toolkit object belongs to the interface thread", [&] { + require(errorOf(answer) == NativeWindowError::wrongThread); + }); + }); + when("the portal identifier becomes known later", [&] { + session.window.setPortalParent("wayland:handle", generation); + then("the window carries it", [&] { + require(handle.get()->portalParent == "wayland:handle"); + }); + }); + when("the window is withdrawn", [&] { + session.window.retract(); + then("it answers closed, and a late portal identifier is dropped", [&] { + require(errorOf(handle.get()) == NativeWindowError::closed); + session.window.setPortalParent("wayland:late", generation); + require(errorOf(handle.get()) == NativeWindowError::closed); + }); + }); + when("the loop closes without the window being withdrawn", [&] { + session.executor.close(); + then("it is not given to a thread that is no longer the interface thread", [&] { + require(errorOf(handle.get()) == NativeWindowError::wrongThread); + }); + }); + }); + given("an asynchronous portal export that answers after its window was replaced", [&] { + const auto handle = nativeWindowHostOf().window(); + std::uint64_t first{}; + { + Session a; + first = a.publish(); // window A asks for its export, which has not answered yet + } + Session b; + const auto second = b.publish("x11:b"); + require(second != first); + when("the answer about window A arrives", [&] { + b.window.setPortalParent("wayland:stale-a", first); + then("window B keeps its own identifier", [&] { + require(handle.get()->portalParent == "x11:b"); + }); + }); + when("the answer about window B arrives", [&] { + b.window.setPortalParent("wayland:b", second); + then("window B takes it", [&] { + require(handle.get()->portalParent == "wayland:b"); + }); + }); + when("window B is withdrawn and the answer about window A arrives", [&] { + then("it is dropped as well", [&] { + b.window.retract(); + b.window.setPortalParent("wayland:stale-a", first); + require(errorOf(handle.get()) == NativeWindowError::closed); + }); + }); + }); + given("a window that was published and withdrawn", [&] { + const auto handle = nativeWindowHostOf().window(); + { + Session first; + first.publish(); + } + require(errorOf(handle.get()) == NativeWindowError::closed); + when("a new session publishes a window", [&] { + Session second; + second.publish(); + then("the same handle gives it", [&] { + require(handle.get().has_value()); + }); + }); + }); + }}; + +const Scenario connectionGiven{ + "A connection is given a window only when it is the view of the frontend's window", + {"native-window", "view-association"}, + [] { + freshNetwork(); + App app{WebFrontConfig{.port = "0"}}; + const auto secret = testing::LaunchSecret>::of(app); + Session session; + session.publish(); + + when("the connection presents the secret of the launch", [&] { + const auto ui = connect(app, secret); + then("its window is the frontend's", [&] { + const auto window = ui.nativeWindow(); require(window.has_value()); - check(window->kind == NativeWindowKind::gtk); check(window->pointer == &windowObject); - check(window->portalParent == "x11:1a2b"); - }); - }); - when("it is read from another thread", [&] { - const auto answer = std::async(std::launch::async, [&] { return handle.get(); }).get(); - then("it is refused: a toolkit object belongs to the interface thread", [&] { - require(errorOf(answer) == NativeWindowError::wrongThread); - }); - }); - when("the portal identifier becomes known later", [&] { - session.window.setPortalParent("wayland:handle", generation); - then("the window carries it", [&] { - require(handle.get()->portalParent == "wayland:handle"); - }); - }); - when("the window is withdrawn", [&] { - session.window.retract(); - then("it answers closed, and a late portal identifier is dropped", [&] { - require(errorOf(handle.get()) == NativeWindowError::closed); - session.window.setPortalParent("wayland:late", generation); - require(errorOf(handle.get()) == NativeWindowError::closed); - }); - }); - when("the loop closes without the window being withdrawn", [&] { - session.executor.close(); - then("it is not given to a thread that is no longer the interface thread", [&] { - require(errorOf(handle.get()) == NativeWindowError::wrongThread); - }); - }); - }); - given("an asynchronous portal export that answers after its window was replaced", [&] { - const auto handle = nativeWindowHostOf().window(); - std::uint64_t first{}; - { - Session a; - first = a.publish(); // window A asks for its export, which has not answered yet - } - Session b; - const auto second = b.publish("x11:b"); - require(second != first); - when("the answer about window A arrives", [&] { - b.window.setPortalParent("wayland:stale-a", first); - then("window B keeps its own identifier", [&] { - require(handle.get()->portalParent == "x11:b"); - }); - }); - when("the answer about window B arrives", [&] { - b.window.setPortalParent("wayland:b", second); - then("window B takes it", [&] { - require(handle.get()->portalParent == "wayland:b"); - }); - }); - when("window B is withdrawn and the answer about window A arrives", [&] { - then("it is dropped as well", [&] { - b.window.retract(); - b.window.setPortalParent("wayland:stale-a", first); - require(errorOf(handle.get()) == NativeWindowError::closed); }); - }); - }); - given("a window that was published and withdrawn", [&] { - const auto handle = nativeWindowHostOf().window(); - { - Session first; - first.publish(); - } - require(errorOf(handle.get()) == NativeWindowError::closed); - when("a new session publishes a window", [&] { - Session second; - second.publish(); - then("the same handle gives it", [&] { - require(handle.get().has_value()); + andWhen("the window is withdrawn", [&] { + session.window.retract(); + then("the connection no longer has one", [&] { + require(errorOf(ui.nativeWindow()) == NativeWindowError::closed); + }); }); - }); - }); -}}; - -const Scenario connectionGiven{"A connection is given a window only when it is the view of the frontend's window", {"native-window", "view-association"}, [] { - freshNetwork(); - App app{WebFrontConfig{.port = "0"}}; - const auto secret = testing::LaunchSecret>::of(app); - Session session; - session.publish(); - - when("the connection presents the secret of the launch", [&] { - const auto ui = connect(app, secret); - then("its window is the frontend's", [&] { - const auto window = ui.nativeWindow(); - require(window.has_value()); - check(window->pointer == &windowObject); - }); - andWhen("the window is withdrawn", [&] { - session.window.retract(); - then("the connection no longer has one", [&] { - require(errorOf(ui.nativeWindow()) == NativeWindowError::closed); + andWhen("the UI is used from another thread", [&] { + const auto answer = std::async(std::launch::async, [&] { + return ui.nativeWindow(); + }).get(); + then("it is refused", [&] { + require(errorOf(answer) == NativeWindowError::wrongThread); + }); }); }); - andWhen("the UI is used from another thread", [&] { - const auto answer = std::async(std::launch::async, [&] { return ui.nativeWindow(); }).get(); - then("it is refused", [&] { - require(errorOf(answer) == NativeWindowError::wrongThread); + when("the connection is a browser without the secret, whatever its address", [&] { + const auto ui = connect(app, {}); + then("it has no window to parent a dialog to", [&] { + require(errorOf(ui.nativeWindow()) == NativeWindowError::notEmbedded); }); }); - }); - when("the connection is a browser without the secret, whatever its address", [&] { - const auto ui = connect(app, {}); - then("it has no window to parent a dialog to", [&] { - require(errorOf(ui.nativeWindow()) == NativeWindowError::notEmbedded); - }); - }); -}}; + } +}; const Scenario frontendWithout{"A frontend without a native window gives none, even to its embedded view", {"native-window"}, [] { - freshNetwork(); - App app{WebFrontConfig{.port = "0"}}; - check(errorOf(app.nativeWindow().get()) == NativeWindowError::unsupported); - const auto ui = connect(app, testing::LaunchSecret>::of(app)); - require(ui.isEmbeddedView()); - then("the answer is unsupported", [&] { - require(errorOf(ui.nativeWindow()) == NativeWindowError::unsupported); - }); -}}; + freshNetwork(); + App app{WebFrontConfig{.port = "0"}}; + check(errorOf(app.nativeWindow().get()) == NativeWindowError::unsupported); + const auto ui = connect(app, testing::LaunchSecret>::of(app)); + require(ui.isEmbeddedView()); + then("the answer is unsupported", [&] { + require(errorOf(ui.nativeWindow()) == NativeWindowError::unsupported); + }); + }}; const Scenario browserFallback{"The browser fallback has no native window", {"native-window"}, [] { - using Fallback = NativeOrBrowserFrontendFor; - Fallback::initialize(); - require(errorOf(Fallback::nativeWindow().get()) == NativeWindowError::unsupported); -}}; + using Fallback = NativeOrBrowserFrontendFor; + Fallback::initialize(); + require(errorOf(Fallback::nativeWindow().get()) == NativeWindowError::unsupported); + }}; diff --git a/test/unit/ProfileLeaseTests.cpp b/test/unit/ProfileLeaseTests.cpp index b3debde2..116c2e17 100644 --- a/test/unit/ProfileLeaseTests.cpp +++ b/test/unit/ProfileLeaseTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -29,118 +29,124 @@ std::filesystem::path scratch(const std::string& name) { } // namespace const Scenario profileLease{"A browser profile is never used by two live instances", [] { - given("a profile directory", [&] { - const auto profile = scratch("profile"); - then("the process keeps the profile, and finds its data again when it asks again", [&] { - const auto first = frontend::leaseProfileDirectory(profile); - require(first == profile); - std::ofstream{first / "data"} << "saved by the first window"; - const auto reopened = frontend::leaseProfileDirectory(profile); - require(reopened == first && std::filesystem::exists(reopened / "data")); - require(!std::filesystem::exists(profile.string() + ".instances")); - }); - std::filesystem::remove_all(profile); - }); - given("the directory of an instance that died without cleaning up", [&] { - const auto profile = scratch("stale"); - const auto dead = std::filesystem::path(profile.string() + ".instances") / "1-0"; - std::filesystem::create_directories(dead); - std::ofstream{dead / "data"} << "left behind"; - then("the next lease removes it", [&] { - (void)frontend::leaseProfileDirectory(profile); // takes the profile itself and clears the abandoned instances - require(!std::filesystem::exists(dead)); - }); - std::filesystem::remove_all(profile); - std::filesystem::remove_all(profile.string() + ".instances"); - }); + given("a profile directory", [&] { + const auto profile = scratch("profile"); + then("the process keeps the profile, and finds its data again when it asks again", [&] { + const auto first = frontend::leaseProfileDirectory(profile); + require(first == profile); + std::ofstream{first / "data"} << "saved by the first window"; + const auto reopened = frontend::leaseProfileDirectory(profile); + require(reopened == first && std::filesystem::exists(reopened / "data")); + require(!std::filesystem::exists(profile.string() + ".instances")); + }); + std::filesystem::remove_all(profile); + }); + given("the directory of an instance that died without cleaning up", [&] { + const auto profile = scratch("stale"); + const auto dead = std::filesystem::path(profile.string() + ".instances") / "1-0"; + std::filesystem::create_directories(dead); + std::ofstream{dead / "data"} << "left behind"; + then("the next lease removes it", [&] { + (void)frontend::leaseProfileDirectory(profile); // takes the profile itself and clears the abandoned instances + require(!std::filesystem::exists(dead)); + }); + std::filesystem::remove_all(profile); + std::filesystem::remove_all(profile.string() + ".instances"); + }); - given("a lock file that cannot be taken for a reason other than contention", [&] { - const auto profile = scratch("broken"); - std::filesystem::create_directories(profile / ".webfront-lock"); // a directory where the lock file should be - then("the error is reported, not retried with new directories", [&] { - requireThrows([&] { (void)frontend::leaseProfileDirectory(profile); }, contains(".webfront-lock")); - require(!std::filesystem::exists(profile.string() + ".instances")); - }); - std::filesystem::remove_all(profile); - }); -}}; + given("a lock file that cannot be taken for a reason other than contention", [&] { + const auto profile = scratch("broken"); + std::filesystem::create_directories(profile / ".webfront-lock"); // a directory where the lock file should be + then("the error is reported, not retried with new directories", [&] { + requireThrows( + [&] { + (void)frontend::leaseProfileDirectory(profile); + }, + contains(".webfront-lock")); + require(!std::filesystem::exists(profile.string() + ".instances")); + }); + std::filesystem::remove_all(profile); + }); + }}; const Scenario concurrentProfileLeases{"Processes that start at the same time lease different profiles", [] { - given("a profile with directories left by dead instances, and several processes starting together", [&] { - const auto profile = scratch("concurrent"); - const auto instances = std::filesystem::path(profile.string() + ".instances"); - for (int i = 0; i < 5; ++i) { - std::filesystem::create_directories(instances / ("dead-" + std::to_string(i))); - std::ofstream{instances / ("dead-" + std::to_string(i)) / ".webfront-lock"}; - } - constexpr int count = 24; - std::vector children; - std::vector reports, releases; - int start[2]; - require(::pipe(start) == 0); - for (int i = 0; i < count; ++i) { - int report[2], release[2]; - require(::pipe(report) == 0 && ::pipe(release) == 0); - const pid_t child = ::fork(); - require(child >= 0); - if (child == 0) { - // Only async-signal-unsafe work the test needs; the process leaves with _exit, so no static destructor runs. - ::close(start[1]); - ::close(report[0]); - ::close(release[1]); // its own pipe's other ends, or the end-of-file of `release` would never come - for (const int inherited : reports) // the earlier children's pipes: their end-of-file must not wait for this process - ::close(inherited); - for (const int inherited : releases) - ::close(inherited); - char go; - (void)::read(start[0], &go, 1); // all the children begin together, when the parent closes the write end - std::string result; - try { - result = frontend::leaseProfileDirectory(profile).string(); - } catch (const std::exception& error) { - result = std::string("error: ") + error.what(); - } - result += '\n'; - (void)::write(report[1], result.data(), result.size()); - char hold; - (void)::read(release[0], &hold, 1); // alive until the parent has looked at every directory - ::_exit(0); - } - ::close(report[1]); - ::close(release[0]); - children.push_back(child); - reports.push_back(report[0]); - releases.push_back(release[1]); - } - ::close(start[0]); - ::close(start[1]); // releases the children - std::set paths; - for (const int fd : reports) { - std::string line; - char c; - while (::read(fd, &c, 1) == 1 && c != '\n') - line += c; - paths.insert(line); - } - then("each process has a directory of its own, which exists with its lock file", [&] { - require(paths.size() == count); - for (const auto& path : paths) { - require(path.rfind("error", 0) != 0); - require(std::filesystem::is_directory(path)); - require(std::filesystem::exists(std::filesystem::path(path) / ".webfront-lock")); - } - require(paths.contains(profile.string())); - for (int i = 0; i < 5; ++i) - require(!std::filesystem::exists(instances / ("dead-" + std::to_string(i)))); - }); - for (const int fd : releases) - ::close(fd); // the children end - for (const pid_t child : children) { - int status = 0; - ::waitpid(child, &status, 0); - } - std::filesystem::remove_all(profile); - std::filesystem::remove_all(instances); - }); -}}; + given("a profile with directories left by dead instances, and several processes starting together", [&] { + const auto profile = scratch("concurrent"); + const auto instances = std::filesystem::path(profile.string() + ".instances"); + for (int i = 0; i < 5; ++i) { + std::filesystem::create_directories(instances / ("dead-" + std::to_string(i))); + std::ofstream{instances / ("dead-" + std::to_string(i)) / ".webfront-lock"}; + } + constexpr int count = 24; + std::vector children; + std::vector reports, releases; + int start[2]; + require(::pipe(start) == 0); + for (int i = 0; i < count; ++i) { + int report[2], release[2]; + require(::pipe(report) == 0 && ::pipe(release) == 0); + const pid_t child = ::fork(); + require(child >= 0); + if (child == 0) { + // Only async-signal-unsafe work the test needs; the process leaves with _exit, so no static destructor + // runs. + ::close(start[1]); + ::close(report[0]); + ::close(release[1]); // its own pipe's other ends, or the end-of-file of `release` would never come + for (const int inherited : + reports) // the earlier children's pipes: their end-of-file must not wait for this process + ::close(inherited); + for (const int inherited : releases) + ::close(inherited); + char go; + (void)::read(start[0], &go, 1); // all the children begin together, when the parent closes the write end + std::string result; + try { + result = frontend::leaseProfileDirectory(profile).string(); + } catch (const std::exception& error) { + result = std::string("error: ") + error.what(); + } + result += '\n'; + (void)::write(report[1], result.data(), result.size()); + char hold; + (void)::read(release[0], &hold, 1); // alive until the parent has looked at every directory + ::_exit(0); + } + ::close(report[1]); + ::close(release[0]); + children.push_back(child); + reports.push_back(report[0]); + releases.push_back(release[1]); + } + ::close(start[0]); + ::close(start[1]); // releases the children + std::set paths; + for (const int fd : reports) { + std::string line; + char c; + while (::read(fd, &c, 1) == 1 && c != '\n') + line += c; + paths.insert(line); + } + then("each process has a directory of its own, which exists with its lock file", [&] { + require(paths.size() == count); + for (const auto& path : paths) { + require(path.rfind("error", 0) != 0); + require(std::filesystem::is_directory(path)); + require(std::filesystem::exists(std::filesystem::path(path) / ".webfront-lock")); + } + require(paths.contains(profile.string())); + for (int i = 0; i < 5; ++i) + require(!std::filesystem::exists(instances / ("dead-" + std::to_string(i)))); + }); + for (const int fd : releases) + ::close(fd); // the children end + for (const pid_t child : children) { + int status = 0; + ::waitpid(child, &status, 0); + } + std::filesystem::remove_all(profile); + std::filesystem::remove_all(instances); + }); + }}; #endif diff --git a/test/unit/PtyTests.cpp b/test/unit/PtyTests.cpp index f488ebf8..070b45d9 100644 --- a/test/unit/PtyTests.cpp +++ b/test/unit/PtyTests.cpp @@ -1,6 +1,6 @@ -#include #include "TemporaryDirectory.hpp" #include +#include #include #include @@ -54,11 +54,11 @@ std::string plain(std::string_view raw) { continue; } const char kind = raw[++i]; - if (kind == '[') { // CSI: parameters, then a final byte in 0x40-0x7e + if (kind == '[') { // CSI: parameters, then a final byte in 0x40-0x7e while (i + 1 < raw.size() && (raw[i + 1] < '@' || raw[i + 1] > '~')) ++i; ++i; - } else if (kind == ']') { // OSC: up to BEL or ESC followed by a backslash + } else if (kind == ']') { // OSC: up to BEL or ESC followed by a backslash while (i + 1 < raw.size() && raw[i + 1] != '\a' && raw[i + 1] != '\x1b') ++i; ++i; @@ -178,7 +178,8 @@ const Scenario ptyShell{"PTY exchanges bytes with an interactive shell and resiz const Scenario ptyControlSequences{"PTY test markers are found through terminal control sequences inserted in the output", [] { // ConPTY sets the window title while the probe starts, here in the middle of the marker. - const std::string raw = "\x1b[2J\x1b[4;1H> probe stall\r\nSTALLED:\x1b]0;cmd.exe - probe\a" "25776:END\r\n\x1b]0;t\x1b\\"; + const std::string raw = "\x1b[2J\x1b[4;1H> probe stall\r\nSTALLED:\x1b]0;cmd.exe - probe\a" + "25776:END\r\n\x1b]0;t\x1b\\"; require(plain(raw) == "> probe stall\r\nSTALLED:25776:END\r\n"); require(stallPid(raw) == 25776); }}; diff --git a/test/unit/ReactStoreTests.cpp b/test/unit/ReactStoreTests.cpp index 1a8c465b..55cd081c 100644 --- a/test/unit/ReactStoreTests.cpp +++ b/test/unit/ReactStoreTests.cpp @@ -1,6 +1,6 @@ #include "InjectableNetworking.hpp" -#include #include +#include #include #include @@ -58,153 +58,167 @@ struct UI { } // namespace const Scenario reactStores{"React stores coalesce a thousand writes into one snapshot per server cycle", {"react"}, [] { - Harness harness; - webfront::react::Store store{UI{&harness}, "counter"}; - auto copy = store; - for (int i = 0; i < 1000; ++i) - copy.set(i); - require(harness.sent.empty()); - require(harness.timers.size() == 1); - harness.tick(); - require(harness.sent == std::vector{999}); - when("an explicit flush precedes the timer", [&] { - store.set(1000); - store.flush(); - harness.tick(); - require(harness.sent == std::vector{999, 1000}); - store.set(1001); - harness.tick(); - require(harness.sent.back() == 1001); - }); - when("the connection closes before the next cycle", [&] { - store.set(1000); - harness.document->close(); - harness.tick(); - require(harness.sent.size() == 1); - require(!store.valid()); - requireThrows([&] { store.set(1001); }); - }); - when("the application shuts down with a pending cycle", [&] { - store.set(1000); - harness.app.shutdown(); - require(harness.sent.size() == 1); - }); - when("the store closes explicitly", [&] { - store.set(1000); - store.close(); - harness.tick(); - require(!copy.valid()); - require(harness.sent.size() == 1); - requireThrows([&] { copy.flush(); }); - }); - when("close releases a self-capturing error handler", [&] { - auto lifetime = std::make_shared(7); - std::weak_ptr observed = lifetime; - store.onError([keep = copy, lifetime](std::exception_ptr) { - check(!keep.valid()); - check(*lifetime == 7); - }); - lifetime.reset(); - require(!observed.expired()); - store.close(); - require(observed.expired()); - }); - when("automatic failure releases a self-capturing error handler", [&] { - auto lifetime = std::make_shared(7); - std::weak_ptr observed = lifetime; - unsigned calls{}; - store.onError([keep = copy, lifetime, &calls](std::exception_ptr) { - ++calls; - check(!keep.valid()); - check(*lifetime == 7); - }); - lifetime.reset(); - harness.fail = true; - store.set(1000); - harness.tick(); - require(calls == 1); - require(observed.expired()); - }); - when("sending the automatic snapshot fails", [&] { - unsigned errors{}; - store.onError([&](std::exception_ptr error) { - ++errors; - require(error != nullptr); - }); - harness.fail = true; - store.set(1000); - harness.tick(); - require(errors == 1); - require(!store.valid()); - }); - when("an explicit flush fails before the timer fires", [&] { - unsigned errors{}; - store.onError([&](std::exception_ptr) { - ++errors; - }); - store.set(1000); - harness.fail = true; - requireThrows([&] { store.flush(); }); - require(store.valid()); - require(errors == 0); - harness.fail = false; - store.flush(); - harness.tick(); - require(harness.sent == std::vector{999, 1000}); - }); - when("the automatic error callback throws", [&] { - std::vector logs; - const auto enabled = webfront::log::is(webfront::log::Error); - webfront::log::set(webfront::log::Error, true); - auto sink = webfront::log::addSinks([&](std::string_view text) { - logs.emplace_back(text); - }); - auto lifetime = std::make_shared(7); - std::weak_ptr observed = lifetime; - store.onError([keep = copy, lifetime](std::exception_ptr) { - check(!keep.valid()); - check(*lifetime == 7); - throw std::runtime_error("handler failed"); - }); - lifetime.reset(); - harness.fail = true; - store.set(1000); - harness.tick(); - webfront::log::removeSinks(sink); - webfront::log::set(webfront::log::Error, enabled); - require(!store.valid()); - require(logs.size() == 1); - require(logs.front().find("React store onError callback threw") != std::string::npos); - require(observed.expired()); - }); - when("a wrapper is moved while a snapshot is pending", [&] { - store.set(1000); - auto moved = std::move(copy); - require(!copy.valid()); - requireThrows([&] { copy.set(1001); }); - requireThrows([&] { copy.flush(); }); - requireThrows([&] { copy.close(); }); - requireThrows([&] { copy.onError({}); }); - require(moved.valid()); - require(store.valid()); - harness.tick(); - require(harness.sent == std::vector{999, 1000}); - moved.set(1002); - moved.flush(); - harness.tick(); - require(harness.sent == std::vector{999, 1000, 1002}); - }); - when("another thread attempts to update it", [&] { - bool rejected{}; - std::thread other([&] { - try { - store.set(1000); - } catch (const std::runtime_error&) { - rejected = true; - } - }); - other.join(); - require(rejected); - require(harness.timers.empty()); - }); -}}; + Harness harness; + webfront::react::Store store{UI{&harness}, "counter"}; + auto copy = store; + for (int i = 0; i < 1000; ++i) + copy.set(i); + require(harness.sent.empty()); + require(harness.timers.size() == 1); + harness.tick(); + require(harness.sent == std::vector{999}); + when("an explicit flush precedes the timer", [&] { + store.set(1000); + store.flush(); + harness.tick(); + require(harness.sent == std::vector{999, 1000}); + store.set(1001); + harness.tick(); + require(harness.sent.back() == 1001); + }); + when("the connection closes before the next cycle", [&] { + store.set(1000); + harness.document->close(); + harness.tick(); + require(harness.sent.size() == 1); + require(!store.valid()); + requireThrows([&] { + store.set(1001); + }); + }); + when("the application shuts down with a pending cycle", [&] { + store.set(1000); + harness.app.shutdown(); + require(harness.sent.size() == 1); + }); + when("the store closes explicitly", [&] { + store.set(1000); + store.close(); + harness.tick(); + require(!copy.valid()); + require(harness.sent.size() == 1); + requireThrows([&] { + copy.flush(); + }); + }); + when("close releases a self-capturing error handler", [&] { + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + store.onError([keep = copy, lifetime](std::exception_ptr) { + check(!keep.valid()); + check(*lifetime == 7); + }); + lifetime.reset(); + require(!observed.expired()); + store.close(); + require(observed.expired()); + }); + when("automatic failure releases a self-capturing error handler", [&] { + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + unsigned calls{}; + store.onError([keep = copy, lifetime, &calls](std::exception_ptr) { + ++calls; + check(!keep.valid()); + check(*lifetime == 7); + }); + lifetime.reset(); + harness.fail = true; + store.set(1000); + harness.tick(); + require(calls == 1); + require(observed.expired()); + }); + when("sending the automatic snapshot fails", [&] { + unsigned errors{}; + store.onError([&](std::exception_ptr error) { + ++errors; + require(error != nullptr); + }); + harness.fail = true; + store.set(1000); + harness.tick(); + require(errors == 1); + require(!store.valid()); + }); + when("an explicit flush fails before the timer fires", [&] { + unsigned errors{}; + store.onError([&](std::exception_ptr) { + ++errors; + }); + store.set(1000); + harness.fail = true; + requireThrows([&] { + store.flush(); + }); + require(store.valid()); + require(errors == 0); + harness.fail = false; + store.flush(); + harness.tick(); + require(harness.sent == std::vector{999, 1000}); + }); + when("the automatic error callback throws", [&] { + std::vector logs; + const auto enabled = webfront::log::is(webfront::log::Error); + webfront::log::set(webfront::log::Error, true); + auto sink = webfront::log::addSinks([&](std::string_view text) { + logs.emplace_back(text); + }); + auto lifetime = std::make_shared(7); + std::weak_ptr observed = lifetime; + store.onError([keep = copy, lifetime](std::exception_ptr) { + check(!keep.valid()); + check(*lifetime == 7); + throw std::runtime_error("handler failed"); + }); + lifetime.reset(); + harness.fail = true; + store.set(1000); + harness.tick(); + webfront::log::removeSinks(sink); + webfront::log::set(webfront::log::Error, enabled); + require(!store.valid()); + require(logs.size() == 1); + require(logs.front().find("React store onError callback threw") != std::string::npos); + require(observed.expired()); + }); + when("a wrapper is moved while a snapshot is pending", [&] { + store.set(1000); + auto moved = std::move(copy); + require(!copy.valid()); + requireThrows([&] { + copy.set(1001); + }); + requireThrows([&] { + copy.flush(); + }); + requireThrows([&] { + copy.close(); + }); + requireThrows([&] { + copy.onError({}); + }); + require(moved.valid()); + require(store.valid()); + harness.tick(); + require(harness.sent == std::vector{999, 1000}); + moved.set(1002); + moved.flush(); + harness.tick(); + require(harness.sent == std::vector{999, 1000, 1002}); + }); + when("another thread attempts to update it", [&] { + bool rejected{}; + std::thread other([&] { + try { + store.set(1000); + } catch (const std::runtime_error&) { + rejected = true; + } + }); + other.join(); + require(rejected); + require(harness.timers.empty()); + }); + }}; diff --git a/test/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index 921898a8..3c175174 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -2,13 +2,13 @@ /// @brief The binding of HTTP reads to the browser client of a connection: token, cookie, transport, neutralized content (#469, ADR-020). #include "InjectableNetworking.hpp" #include "Mocks.hpp" -#include -#include -#include #include #include +#include #include +#include #include +#include #include #include @@ -68,16 +68,18 @@ std::string cookiePair(const std::string& setCookie) { } struct Fixture { - using Clock = std::chrono::steady_clock; - Clock::time_point time = Clock::now(); - ReadBinding binding; - http::RouteHandler exchange = binding.exchangeHandler(); - http::RouteHandler read; - std::string lastRest; - std::any lastContext; + using Clock = std::chrono::steady_clock; + Clock::time_point time = Clock::now(); + ReadBinding binding; + http::RouteHandler exchange = binding.exchangeHandler(); + http::RouteHandler read; + std::string lastRest; + std::any lastContext; explicit Fixture(RemoteFileTransport transport = RemoteFileTransport::refused, bool secure = false) - : binding(ReadBinding::Options{.remote = transport, .secure = secure}, [this] { return time; }) { + : binding(ReadBinding::Options{.remote = transport, .secure = secure}, [this] { + return time; + }) { read = binding.readHandler("route-a", std::string(readPrefix), [this](const http::RouteRequest&, const ReadGrant& grant) { lastRest = std::string(grant.rest); lastContext = grant.context; @@ -102,392 +104,482 @@ struct Fixture { } // namespace const Scenario readNeeds{"A read needs the token and the cookie of the client of the connection that owns it", {"read-binding"}, [] { - Fixture fixture; - given("a local connection that exchanged its secret for a cookie", [&] { - const auto bound = fixture.bind(1, true); - const auto cookies = headers(bound, "Set-Cookie"); - require(bound.status == http::Response::ok); - require(cookies.size() == 1); - const auto cookie = cookiePair(cookies.front()); - const auto url = fixture.url(1, "dir/a b.txt"); - - then("the cookie is named after its client and restricted", [&] { - require(cookie.starts_with("wf-client-")); - require(cookies.front().contains("; Path=/webfront/services/")); - require(cookies.front().contains("; HttpOnly")); - require(cookies.front().contains("; SameSite=Strict")); - require(!cookies.front().contains("Secure")); - }); - then("the URL is under the readPrefix, followed by the token and the encoded path", [&] { - require(url.starts_with(readPrefix)); - require(url.ends_with("/dir/a%20b.txt")); - }); - when("the owner's client presents the URL with its cookie", [&] { - const auto reply = call(fixture.read, url, cookie); - then("the handler runs with the decoded rest of the path", [&] { - require(reply.status == http::Response::ok); - require(fixture.lastRest == "dir/a b.txt"); - }); - }); - when("the URL is presented without cookie", [&] { - require(call(fixture.read, url).status == http::Response::forbidden); - then("the handler did not run", [&] { require(fixture.lastRest.empty()); }); - }); - when("the URL is presented with the cookie of another client", [&] { - const auto other = cookiePair(headers(fixture.bind(2, true), "Set-Cookie").front()); - require(other != cookie); - then("it is refused", [&] { require(call(fixture.read, url, other).status == http::Response::forbidden); }); - }); - when("the URL is presented with the right cookie name and a wrong value", [&] { - const auto forged = cookie.substr(0, cookie.size() - 1) + (cookie.back() == '0' ? "1" : "0"); - then("it is refused", [&] { require(call(fixture.read, url, forged).status == http::Response::forbidden); }); - }); - when("the token is altered or absent", [&] { - auto altered = url; - altered[readPrefix.size() + 20] = altered[readPrefix.size() + 20] == 'a' ? 'b' : 'a'; - then("every refusal looks alike", [&] { - const auto unknown = call(fixture.read, altered, cookie); - const auto missing = call(fixture.read, std::string(readPrefix), cookie); - const auto garbage = call(fixture.read, std::string(readPrefix) + "nodot/x", cookie); - require(unknown.status == http::Response::forbidden); - require(missing.status == http::Response::forbidden); - require(garbage.status == http::Response::forbidden); - require(unknown.headers == missing.headers); - require(unknown.headers == garbage.headers); - }); - }); - when("the URL is requested repeatedly, as a media element does for its byte ranges", [&] { - then("the token stays valid", [&] { - for (int range = 0; range < 5; ++range) - require(call(fixture.read, url, cookie).status == http::Response::ok); - }); - }); - when("the owning connection closes", [&] { - fixture.binding.close(1); - then("the URL no longer works, cookie or not", [&] { require(call(fixture.read, url, cookie).status == http::Response::forbidden); }); - }); - when("the grant is revoked", [&] { - fixture.binding.revoke(url); - then("the URL no longer works", [&] { require(call(fixture.read, url, cookie).status == http::Response::forbidden); }); - }); - when("the server restarts: another binding sees the old cookie and URL", [&] { - Fixture restarted; - then("neither is known", [&] { require(call(restarted.read, url, cookie).status == http::Response::forbidden); }); - andThen("the old cookie, indistinguishable from another application's, is left alone (it is a session cookie)", [&] { - const auto again = restarted.bind(1, true, cookie); - for (const auto& line : headers(again, "Set-Cookie")) - require(!line.contains("Max-Age=0")); - }); - }); - }); -}}; + Fixture fixture; + given("a local connection that exchanged its secret for a cookie", [&] { + const auto bound = fixture.bind(1, true); + const auto cookies = headers(bound, "Set-Cookie"); + require(bound.status == http::Response::ok); + require(cookies.size() == 1); + const auto cookie = cookiePair(cookies.front()); + const auto url = fixture.url(1, "dir/a b.txt"); + + then("the cookie is named after its client and restricted", [&] { + require(cookie.starts_with("wf-client-")); + require(cookies.front().contains("; Path=/webfront/services/")); + require(cookies.front().contains("; HttpOnly")); + require(cookies.front().contains("; SameSite=Strict")); + require(!cookies.front().contains("Secure")); + }); + then("the URL is under the readPrefix, followed by the token and the encoded path", [&] { + require(url.starts_with(readPrefix)); + require(url.ends_with("/dir/a%20b.txt")); + }); + when("the owner's client presents the URL with its cookie", [&] { + const auto reply = call(fixture.read, url, cookie); + then("the handler runs with the decoded rest of the path", [&] { + require(reply.status == http::Response::ok); + require(fixture.lastRest == "dir/a b.txt"); + }); + }); + when("the URL is presented without cookie", [&] { + require(call(fixture.read, url).status == http::Response::forbidden); + then("the handler did not run", [&] { + require(fixture.lastRest.empty()); + }); + }); + when("the URL is presented with the cookie of another client", [&] { + const auto other = cookiePair(headers(fixture.bind(2, true), "Set-Cookie").front()); + require(other != cookie); + then("it is refused", [&] { + require(call(fixture.read, url, other).status == http::Response::forbidden); + }); + }); + when("the URL is presented with the right cookie name and a wrong value", [&] { + const auto forged = cookie.substr(0, cookie.size() - 1) + (cookie.back() == '0' ? "1" : "0"); + then("it is refused", [&] { + require(call(fixture.read, url, forged).status == http::Response::forbidden); + }); + }); + when("the token is altered or absent", [&] { + auto altered = url; + altered[readPrefix.size() + 20] = altered[readPrefix.size() + 20] == 'a' ? 'b' : 'a'; + then("every refusal looks alike", [&] { + const auto unknown = call(fixture.read, altered, cookie); + const auto missing = call(fixture.read, std::string(readPrefix), cookie); + const auto garbage = call(fixture.read, std::string(readPrefix) + "nodot/x", cookie); + require(unknown.status == http::Response::forbidden); + require(missing.status == http::Response::forbidden); + require(garbage.status == http::Response::forbidden); + require(unknown.headers == missing.headers); + require(unknown.headers == garbage.headers); + }); + }); + when("the URL is requested repeatedly, as a media element does for its byte ranges", [&] { + then("the token stays valid", [&] { + for (int range = 0; range < 5; ++range) + require(call(fixture.read, url, cookie).status == http::Response::ok); + }); + }); + when("the owning connection closes", [&] { + fixture.binding.close(1); + then("the URL no longer works, cookie or not", [&] { + require(call(fixture.read, url, cookie).status == http::Response::forbidden); + }); + }); + when("the grant is revoked", [&] { + fixture.binding.revoke(url); + then("the URL no longer works", [&] { + require(call(fixture.read, url, cookie).status == http::Response::forbidden); + }); + }); + when("the server restarts: another binding sees the old cookie and URL", [&] { + Fixture restarted; + then("neither is known", [&] { + require(call(restarted.read, url, cookie).status == http::Response::forbidden); + }); + andThen("the old cookie, indistinguishable from another application's, is left alone (it is a session cookie)", [&] { + const auto again = restarted.bind(1, true, cookie); + for (const auto& line : headers(again, "Set-Cookie")) + require(!line.contains("Max-Age=0")); + }); + }); + }); + }}; const Scenario connectionsOne{"The connections of one browser profile belong to one client", {"read-binding"}, [] { - Fixture fixture; - given("a first tab that exchanged and a second tab that presents the cookie it already holds", [&] { - const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); - const auto second = fixture.bind(2, true, cookie); - then("the second tab creates no cookie", [&] { require(headers(second, "Set-Cookie").empty()); }); - const auto url1 = fixture.url(1); - const auto url2 = fixture.url(2); - then("each tab's URL is read with the shared cookie, as the same profile does", [&] { - require(call(fixture.read, url1, cookie).status == http::Response::ok); - require(call(fixture.read, url2, cookie).status == http::Response::ok); - }); - andWhen("the first tab closes", [&] { + Fixture fixture; + given("a first tab that exchanged and a second tab that presents the cookie it already holds", [&] { + const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); + const auto second = fixture.bind(2, true, cookie); + then("the second tab creates no cookie", [&] { + require(headers(second, "Set-Cookie").empty()); + }); + const auto url1 = fixture.url(1); + const auto url2 = fixture.url(2); + then("each tab's URL is read with the shared cookie, as the same profile does", [&] { + require(call(fixture.read, url1, cookie).status == http::Response::ok); + require(call(fixture.read, url2, cookie).status == http::Response::ok); + }); + andWhen("the first tab closes", [&] { + fixture.binding.close(1); + then("the client lives on with the second", [&] { + require(call(fixture.read, url1, cookie).status == http::Response::forbidden); + require(call(fixture.read, url2, cookie).status == http::Response::ok); + }); + andWhen("the second closes too", [&] { + fixture.binding.close(2); + then("the client is forgotten: a third tab with the cookie gets a new client and the old cookie is erased", [&] { + const auto third = fixture.bind(3, true, cookie); + const auto lines = headers(third, "Set-Cookie"); + require(lines.size() == 2); + require(lines[0].contains("Max-Age=0")); + require(cookiePair(lines[1]) != cookie); + }); + }); + }); + }); + given("two tabs of a blank profile whose exchanges run at the same time", [&] { + // Both secrets are issued, and both requests are answered, before the browser stores either cookie. + const auto secretA = fixture.binding.open(1, true); + const auto secretB = fixture.binding.open(2, true); + const auto answerA = call(fixture.exchange, std::string(ReadBinding::bindPath) + secretA); + const auto answerB = call(fixture.exchange, std::string(ReadBinding::bindPath) + secretB); + const auto cookieA = cookiePair(headers(answerA, "Set-Cookie").front()); + const auto cookieB = cookiePair(headers(answerB, "Set-Cookie").front()); + then("the cookies have different names, so neither overwrites the other", [&] { + require(cookieA.substr(0, cookieA.find('=')) != cookieB.substr(0, cookieB.find('='))); + }); + then("the browser sends both, and both tabs read their URLs", [&] { + const auto both = cookieA + "; " + cookieB; + require(call(fixture.read, fixture.url(1), both).status == http::Response::ok); + require(call(fixture.read, fixture.url(2), both).status == http::Response::ok); + }); + then("each cookie alone opens its own tab's URL only", [&] { + require(call(fixture.read, fixture.url(1), cookieA).status == http::Response::ok); + require(call(fixture.read, fixture.url(2), cookieA).status == http::Response::forbidden); + }); + }); + }}; + +const Scenario exchangeSecret{ + "The exchange secret is single use and only the right one works", + {"read-binding"}, + [] { + Fixture fixture; + const auto secret = fixture.binding.open(1, true); + const auto path = std::string(ReadBinding::bindPath) + secret; + then("a wrong secret is refused and gives no cookie", [&] { + const auto reply = call(fixture.exchange, std::string(ReadBinding::bindPath) + std::string(64, '0')); + require(reply.status == http::Response::forbidden); + require(headers(reply, "Set-Cookie").empty()); + }); + then("the secret works once", [&] { + require(call(fixture.exchange, path).status == http::Response::ok); + const auto replay = call(fixture.exchange, path); + require(replay.status == http::Response::forbidden); + require(headers(replay, "Set-Cookie").empty()); + }); + then("a secret does not survive its connection", [&] { fixture.binding.close(1); - then("the client lives on with the second", [&] { - require(call(fixture.read, url1, cookie).status == http::Response::forbidden); - require(call(fixture.read, url2, cookie).status == http::Response::ok); - }); - andWhen("the second closes too", [&] { - fixture.binding.close(2); - then("the client is forgotten: a third tab with the cookie gets a new client and the old cookie is erased", [&] { - const auto third = fixture.bind(3, true, cookie); - const auto lines = headers(third, "Set-Cookie"); - require(lines.size() == 2); - require(lines[0].contains("Max-Age=0")); - require(cookiePair(lines[1]) != cookie); - }); - }); - }); - }); - given("two tabs of a blank profile whose exchanges run at the same time", [&] { - // Both secrets are issued, and both requests are answered, before the browser stores either cookie. - const auto secretA = fixture.binding.open(1, true); - const auto secretB = fixture.binding.open(2, true); - const auto answerA = call(fixture.exchange, std::string(ReadBinding::bindPath) + secretA); - const auto answerB = call(fixture.exchange, std::string(ReadBinding::bindPath) + secretB); - const auto cookieA = cookiePair(headers(answerA, "Set-Cookie").front()); - const auto cookieB = cookiePair(headers(answerB, "Set-Cookie").front()); - then("the cookies have different names, so neither overwrites the other", [&] { - require(cookieA.substr(0, cookieA.find('=')) != cookieB.substr(0, cookieB.find('='))); - }); - then("the browser sends both, and both tabs read their URLs", [&] { - const auto both = cookieA + "; " + cookieB; - require(call(fixture.read, fixture.url(1), both).status == http::Response::ok); - require(call(fixture.read, fixture.url(2), both).status == http::Response::ok); - }); - then("each cookie alone opens its own tab's URL only", [&] { - require(call(fixture.read, fixture.url(1), cookieA).status == http::Response::ok); - require(call(fixture.read, fixture.url(2), cookieA).status == http::Response::forbidden); - }); - }); -}}; - -const Scenario exchangeSecret{"The exchange secret is single use and only the right one works", {"read-binding"}, [] { - Fixture fixture; - const auto secret = fixture.binding.open(1, true); - const auto path = std::string(ReadBinding::bindPath) + secret; - then("a wrong secret is refused and gives no cookie", [&] { - const auto reply = call(fixture.exchange, std::string(ReadBinding::bindPath) + std::string(64, '0')); - require(reply.status == http::Response::forbidden); - require(headers(reply, "Set-Cookie").empty()); - }); - then("the secret works once", [&] { - require(call(fixture.exchange, path).status == http::Response::ok); - const auto replay = call(fixture.exchange, path); - require(replay.status == http::Response::forbidden); - require(headers(replay, "Set-Cookie").empty()); - }); - then("a secret does not survive its connection", [&] { - fixture.binding.close(1); - require(call(fixture.exchange, path).status == http::Response::forbidden); - }); - then("a connection key opened twice starts over", [&] { - const auto again = fixture.binding.open(1, true); - require(call(fixture.exchange, path).status == http::Response::forbidden); - require(call(fixture.exchange, std::string(ReadBinding::bindPath) + again).status == http::Response::ok); - }); - then("the check of one exchange is not satisfied by the cookie of a concurrent one", [&] { - // The browser kept the first cookie and rejected the second: the second client must not be told it is bound. - const auto cookieA = cookiePair(headers(call(fixture.exchange, path), "Set-Cookie").front()); - const auto clientB = *header(fixture.bind(2, true), "X-WebFront-Client"); - require(call(fixture.exchange, std::string(ReadBinding::bindPath) + "check/" + clientB, cookieA).status == http::Response::forbidden); - }); - then("the check answers only to a request whose cookies designate the client the exchange named", [&] { - const auto base = std::string(ReadBinding::bindPath) + "check/"; - const auto reply = call(fixture.exchange, path); - const auto client = *header(reply, "X-WebFront-Client"); - const auto cookie = cookiePair(headers(reply, "Set-Cookie").front()); - require(call(fixture.exchange, base + client).status == http::Response::forbidden); - require(call(fixture.exchange, base + client, cookie).status == http::Response::ok); - require(call(fixture.exchange, base + "0000000000000000", cookie).status == http::Response::forbidden); - require(call(fixture.exchange, base + "0000000000000000", fixture.binding.clientCookiePrefix() + "0000000000000000=" + std::string(64, 'a')).status == http::Response::forbidden); - }); -}}; + require(call(fixture.exchange, path).status == http::Response::forbidden); + }); + then("a connection key opened twice starts over", [&] { + const auto again = fixture.binding.open(1, true); + require(call(fixture.exchange, path).status == http::Response::forbidden); + require(call(fixture.exchange, std::string(ReadBinding::bindPath) + again).status == http::Response::ok); + }); + then("the check of one exchange is not satisfied by the cookie of a concurrent one", [&] { + // The browser kept the first cookie and rejected the second: the second client must not be told it is bound. + const auto cookieA = cookiePair(headers(call(fixture.exchange, path), "Set-Cookie").front()); + const auto clientB = *header(fixture.bind(2, true), "X-WebFront-Client"); + require(call(fixture.exchange, std::string(ReadBinding::bindPath) + "check/" + clientB, cookieA).status == http::Response::forbidden); + }); + then("the check answers only to a request whose cookies designate the client the exchange named", [&] { + const auto base = std::string(ReadBinding::bindPath) + "check/"; + const auto reply = call(fixture.exchange, path); + const auto client = *header(reply, "X-WebFront-Client"); + const auto cookie = cookiePair(headers(reply, "Set-Cookie").front()); + require(call(fixture.exchange, base + client).status == http::Response::forbidden); + require(call(fixture.exchange, base + client, cookie).status == http::Response::ok); + require(call(fixture.exchange, base + "0000000000000000", cookie).status == http::Response::forbidden); + require(call(fixture.exchange, base + "0000000000000000", fixture.binding.clientCookiePrefix() + "0000000000000000=" + std::string(64, 'a')).status + == http::Response::forbidden); + }); + }}; const Scenario grantWorks{"A grant works only on the route registration that issued it", {"read-binding"}, [] { - Fixture fixture; - const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); - const auto url = fixture.url(1, "a.txt", {.context = std::string("secret-of-route-a")}); - bool otherRan = false; - // A later route on the same readPrefix (route A was dropped and B registered), or a sibling readPrefix. - const auto other = fixture.binding.readHandler("route-b", std::string(readPrefix), [&](const http::RouteRequest&, const ReadGrant&) { - otherRan = true; - return http::RouteReply{}; - }); - then("the other route refuses the token without running its handler", [&] { - require(call(other, url, cookie).status == http::Response::forbidden); - require(!otherRan); - }); - then("the issuing route still accepts it", [&] { require(call(fixture.read, url, cookie).status == http::Response::ok); }); -}}; + Fixture fixture; + const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); + const auto url = fixture.url(1, "a.txt", {.context = std::string("secret-of-route-a")}); + bool otherRan = false; + // A later route on the same readPrefix (route A was dropped and B registered), or a sibling readPrefix. + const auto other = fixture.binding.readHandler("route-b", + std::string(readPrefix), + [&](const http::RouteRequest&, const ReadGrant&) { + otherRan = true; + return http::RouteReply{}; + }); + then("the other route refuses the token without running its handler", [&] { + require(call(other, url, cookie).status == http::Response::forbidden); + require(!otherRan); + }); + then("the issuing route still accepts it", [&] { + require(call(fixture.read, url, cookie).status == http::Response::ok); + }); + }}; const Scenario transferableMode{"The transferable mode makes the token alone a short-lived bearer capability", {"read-binding"}, [] { - Fixture fixture; - const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); - then("it needs an explicit short lifetime", [&] { - requireThrows([&] { fixture.url(1, "a", {.transferable = true}); }); - requireThrows([&] { fixture.url(1, "a", {.lifetime = 16min, .transferable = true}); }); - requireThrows([&] { fixture.url(1, "a", {.lifetime = -1s}); }); - }); - given("a transferable URL", [&] { - const auto url = fixture.url(1, "a", {.lifetime = 60s, .transferable = true}); - then("a client without any cookie reads it", [&] { require(call(fixture.read, url).status == http::Response::ok); }); - then("it stops at its expiry", [&] { - fixture.time += 59s; - require(call(fixture.read, url).status == http::Response::ok); - fixture.time += 2s; - require(call(fixture.read, url).status == http::Response::forbidden); - }); - then("it stops with the connection", [&] { - fixture.binding.close(1); - require(call(fixture.read, url).status == http::Response::forbidden); - }); - }); - given("a bound URL with a lifetime", [&] { - const auto url = fixture.url(1, "a", {.lifetime = 60s}); - then("the cookie is still required, and the lifetime still applies", [&] { - require(call(fixture.read, url).status == http::Response::forbidden); - require(call(fixture.read, url, cookie).status == http::Response::ok); - fixture.time += 61s; - require(call(fixture.read, url, cookie).status == http::Response::forbidden); - }); - }); - given("a lifetime the clock cannot represent", [&] { - then("it is refused instead of overflowing the expiry, and a lifetime that fits is accepted", [&] { - requireThrows([&] { fixture.url(1, "a", {.lifetime = std::chrono::seconds::max()}); }); - const auto remaining = std::chrono::duration_cast(Fixture::Clock::time_point::max() - fixture.time); - requireThrows([&] { fixture.url(1, "a", {.lifetime = remaining + 1s}); }); - const auto url = fixture.url(1, "a", {.lifetime = remaining - 1s}); - require(call(fixture.read, url, cookie).status == http::Response::ok); - }); - }); - then("the context of the grant reaches the handler", [&] { - const auto url = fixture.url(1, "a", {.context = std::string("handle-7")}); - require(call(fixture.read, url, cookie).status == http::Response::ok); - require(std::any_cast(fixture.lastContext) == "handle-7"); - }); -}}; - -const Scenario connectionNot{"A connection that is not the view of an embedded frontend reads only under a declared transport", {"read-binding"}, [] { - given("the default declaration", [&] { - Fixture fixture; - const auto cookie = cookiePair(headers(fixture.bind(1, false), "Set-Cookie").front()); - then("no URL is given to the system browser", [&] { requireThrows([&] { fixture.url(1); }); }); - then("a connection that is closed has none either", [&] { requireThrows([&] { fixture.url(9); }); }); - then("the embedded view reads", [&] { - const auto viewCookie = cookiePair(headers(fixture.bind(2, true), "Set-Cookie").front()); - require(call(fixture.read, fixture.url(2), viewCookie).status == http::Response::ok); + Fixture fixture; + const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); + then("it needs an explicit short lifetime", [&] { + requireThrows([&] { + fixture.url(1, "a", {.transferable = true}); + }); + requireThrows([&] { + fixture.url(1, "a", {.lifetime = 16min, .transferable = true}); + }); + requireThrows([&] { + fixture.url(1, "a", {.lifetime = -1s}); + }); + }); + given("a transferable URL", [&] { + const auto url = fixture.url(1, "a", {.lifetime = 60s, .transferable = true}); + then("a client without any cookie reads it", [&] { + require(call(fixture.read, url).status == http::Response::ok); + }); + then("it stops at its expiry", [&] { + fixture.time += 59s; + require(call(fixture.read, url).status == http::Response::ok); + fixture.time += 2s; + require(call(fixture.read, url).status == http::Response::forbidden); + }); + then("it stops with the connection", [&] { + fixture.binding.close(1); + require(call(fixture.read, url).status == http::Response::forbidden); + }); + }); + given("a bound URL with a lifetime", [&] { + const auto url = fixture.url(1, "a", {.lifetime = 60s}); + then("the cookie is still required, and the lifetime still applies", [&] { + require(call(fixture.read, url).status == http::Response::forbidden); + require(call(fixture.read, url, cookie).status == http::Response::ok); + fixture.time += 61s; + require(call(fixture.read, url, cookie).status == http::Response::forbidden); + }); + }); + given("a lifetime the clock cannot represent", [&] { + then("it is refused instead of overflowing the expiry, and a lifetime that fits is accepted", [&] { + requireThrows([&] { + fixture.url(1, "a", {.lifetime = std::chrono::seconds::max()}); + }); + const auto remaining = std::chrono::duration_cast(Fixture::Clock::time_point::max() + - fixture.time); + requireThrows([&] { + fixture.url(1, "a", {.lifetime = remaining + 1s}); + }); + const auto url = fixture.url(1, "a", {.lifetime = remaining - 1s}); + require(call(fixture.read, url, cookie).status == http::Response::ok); + }); + }); + then("the context of the grant reaches the handler", [&] { + const auto url = fixture.url(1, "a", {.context = std::string("handle-7")}); + require(call(fixture.read, url, cookie).status == http::Response::ok); + require(std::any_cast(fixture.lastContext) == "handle-7"); + }); + }}; + +const Scenario connectionNot{ + "A connection that is not the view of an embedded frontend reads only under a declared transport", + {"read-binding"}, + [] { + given("the default declaration", [&] { + Fixture fixture; + const auto cookie = cookiePair(headers(fixture.bind(1, false), "Set-Cookie").front()); + then("no URL is given to the system browser", [&] { + requireThrows([&] { + fixture.url(1); + }); + }); + then("a connection that is closed has none either", [&] { + requireThrows([&] { + fixture.url(9); + }); + }); + then("the embedded view reads", [&] { + const auto viewCookie = cookiePair(headers(fixture.bind(2, true), "Set-Cookie").front()); + require(call(fixture.read, fixture.url(2), viewCookie).status == http::Response::ok); + }); }); - }); - for (const auto transport : {RemoteFileTransport::loopbackAttested, RemoteFileTransport::encryptedByDeployment, RemoteFileTransport::httpsByDeployment, RemoteFileTransport::plaintextAccepted}) { - given("the declared transport ", static_cast(transport), [&] { - Fixture fixture{transport}; - const auto bound = fixture.bind(1, false); - const auto cookie = cookiePair(headers(bound, "Set-Cookie").front()); - const auto url = fixture.url(1); - then("the system browser reads with its cookie, whatever the forwarding headers claim", [&] { - require(call(fixture.read, url, cookie, "X-Forwarded-Proto: https\r\nForwarded: for=127.0.0.1;proto=https\r\n").status == http::Response::ok); - require(call(fixture.read, url).status == http::Response::forbidden); + for (const auto transport : {RemoteFileTransport::loopbackAttested, + RemoteFileTransport::encryptedByDeployment, + RemoteFileTransport::httpsByDeployment, + RemoteFileTransport::plaintextAccepted}) { + given("the declared transport ", static_cast(transport), [&] { + Fixture fixture{transport}; + const auto bound = fixture.bind(1, false); + const auto cookie = cookiePair(headers(bound, "Set-Cookie").front()); + const auto url = fixture.url(1); + then("the system browser reads with its cookie, whatever the forwarding headers claim", [&] { + require(call(fixture.read, url, cookie, "X-Forwarded-Proto: https\r\nForwarded: for=127.0.0.1;proto=https\r\n").status + == http::Response::ok); + require(call(fixture.read, url).status == http::Response::forbidden); + }); + then("the cookie is Secure only when the browser is declared to use https://, not for an encrypted tunnel under http://", [&] { + require(headers(bound, "Set-Cookie").front().contains("; Secure") == (transport == RemoteFileTransport::httpsByDeployment)); + }); + }); + } + given("a connection to the integrated TLS listener", [&] { + Fixture fixture{RemoteFileTransport::refused, true}; + const auto cookies = headers(fixture.bind(1, false), "Set-Cookie"); + then("its binding uses a Secure cookie and the default still refuses reads", [&] { + require(cookies.front().contains("; Secure")); + requireThrows([&] { + fixture.url(1); + }); }); - then("the cookie is Secure only when the browser is declared to use https://, not for an encrypted tunnel under http://", [&] { - require(headers(bound, "Set-Cookie").front().contains("; Secure") == (transport == RemoteFileTransport::httpsByDeployment)); + then("an explicit HTTPS declaration authorizes reads with the binding cookie", [&] { + Fixture authorized{RemoteFileTransport::httpsByDeployment, true}; + const auto bound = headers(authorized.bind(2, false), "Set-Cookie").front(); + require(bound.contains("; Secure")); + require(call(authorized.read, authorized.url(2), cookiePair(bound)).status == http::Response::ok); }); }); - } - given("a connection to the integrated TLS listener", [&] { - Fixture fixture{RemoteFileTransport::refused, true}; - const auto cookies = headers(fixture.bind(1, false), "Set-Cookie"); - then("its binding uses a Secure cookie and the default still refuses reads", [&] { - require(cookies.front().contains("; Secure")); - requireThrows([&] { fixture.url(1); }); + given("a request through a local proxy that forges the forwarding headers, with the default declaration", [&] { + Fixture fixture; + fixture.bind(1, false); + then("nothing makes the connection local: the headers and the address are never consulted", [&] { + requireThrows([&] { + fixture.url(1); + }); + }); }); - then("an explicit HTTPS declaration authorizes reads with the binding cookie", [&] { - Fixture authorized{RemoteFileTransport::httpsByDeployment, true}; - const auto bound = headers(authorized.bind(2, false), "Set-Cookie").front(); - require(bound.contains("; Secure")); - require(call(authorized.read, authorized.url(2), cookiePair(bound)).status == http::Response::ok); + }}; + +const Scenario declarationLoopback{ + "A declaration of a loopback server is checked against the address it listens on", + {"read-binding"}, + [] { + for (const auto* address : + {"127.0.0.1", "127.1.2.3", "::1", "[::1]", "0:0:0:0:0:0:0:1", "0000:0000:0000:0000:0000:0000:0000:0001", "0::1", "::0001", "[0:0::1]"}) + then("'", address, "' is a loopback address", [&] { + require(detail::isLoopbackName(address)); + }); + for (const auto* address : + {"0.0.0.0", "::", "", "192.168.1.5", "10.0.0.1", "127.0.0", "127.0.0.1.5", "127.a.0.1", + "127..0.1", "example.com", "localhost", "LocalHost", "127.0.0.1.", "127.256.0.1", "127.0.256.1", "127.0.0.1000", + "127.0.0.010", "127.00.0.1", "127.0.0.", ":::1", "0:0:0:0:0:0:0:2", "1:0:0:0:0:0:0:1", "0:0:0:0:0:0:0:0:1", "::1::", + "::12345", "::g"}) + then("'", address, "' is not", [&] { + require(!detail::isLoopbackName(address)); + }); + then("loopbackAttested is refused for a server that listens elsewhere, and accepted on the loopback", [&] { + requireThrows([&] { + detail::checkedAddress(WebFrontConfig{.address = "0.0.0.0", .remoteFileTransport = RemoteFileTransport::loopbackAttested}); + }); + requireNothrow([&] { + detail::checkedAddress(WebFrontConfig{.address = "127.0.0.1", .remoteFileTransport = RemoteFileTransport::loopbackAttested}); + }); + requireNothrow([&] { + detail::checkedAddress(WebFrontConfig{.address = "0.0.0.0", .remoteFileTransport = RemoteFileTransport::plaintextAccepted}); + }); }); - }); - given("a request through a local proxy that forges the forwarding headers, with the default declaration", [&] { - Fixture fixture; - fixture.bind(1, false); - then("nothing makes the connection local: the headers and the address are never consulted", [&] { - requireThrows([&] { fixture.url(1); }); + }}; + +const Scenario readResponses{ + "Read responses neutralize active content", + {"read-binding"}, + [] { + const auto present = [](std::string contentType, std::string rest = "dir/file.bin") { + http::RouteReply reply; + if (!contentType.empty()) + reply.headers.emplace_back("Content-Type", std::move(contentType)); + reply.headers.emplace_back("Content-Disposition", "inline"); // a handler cannot choose + detail::hardenRead(reply, rest); + return reply; + }; + given("any response", [&] { + const auto reply = present("image/png"); + then("it carries the protective headers", [&] { + require(header(reply, "Cache-Control") == "no-store"); + require(header(reply, "Referrer-Policy") == "no-referrer"); + require(header(reply, "Content-Security-Policy") == "sandbox; default-src 'none'"); + require(header(reply, "X-Content-Type-Options") == "nosniff"); + require(header(reply, "Cross-Origin-Resource-Policy") == "same-origin"); + }); }); - }); -}}; - -const Scenario declarationLoopback{"A declaration of a loopback server is checked against the address it listens on", {"read-binding"}, [] { - for (const auto* address : {"127.0.0.1", "127.1.2.3", "::1", "[::1]", "0:0:0:0:0:0:0:1", "0000:0000:0000:0000:0000:0000:0000:0001", "0::1", "::0001", "[0:0::1]"}) - then("'", address, "' is a loopback address", [&] { require(detail::isLoopbackName(address)); }); - for (const auto* address : {"0.0.0.0", "::", "", "192.168.1.5", "10.0.0.1", "127.0.0", "127.0.0.1.5", "127.a.0.1", "127..0.1", "example.com", "localhost", "LocalHost", "127.0.0.1.", "127.256.0.1", "127.0.256.1", "127.0.0.1000", "127.0.0.010", "127.00.0.1", "127.0.0.", ":::1", "0:0:0:0:0:0:0:2", "1:0:0:0:0:0:0:1", "0:0:0:0:0:0:0:0:1", "::1::", "::12345", "::g"}) - then("'", address, "' is not", [&] { require(!detail::isLoopbackName(address)); }); - then("loopbackAttested is refused for a server that listens elsewhere, and accepted on the loopback", [&] { - requireThrows([&] { detail::checkedAddress(WebFrontConfig{.address = "0.0.0.0", .remoteFileTransport = RemoteFileTransport::loopbackAttested}); }); - requireNothrow([&] { detail::checkedAddress(WebFrontConfig{.address = "127.0.0.1", .remoteFileTransport = RemoteFileTransport::loopbackAttested}); }); - requireNothrow([&] { detail::checkedAddress(WebFrontConfig{.address = "0.0.0.0", .remoteFileTransport = RemoteFileTransport::plaintextAccepted}); }); - }); -}}; - -const Scenario readResponses{"Read responses neutralize active content", {"read-binding"}, [] { - const auto present = [](std::string contentType, std::string rest = "dir/file.bin") { - http::RouteReply reply; - if (!contentType.empty()) - reply.headers.emplace_back("Content-Type", std::move(contentType)); - reply.headers.emplace_back("Content-Disposition", "inline"); // a handler cannot choose - detail::hardenRead(reply, rest); - return reply; - }; - given("any response", [&] { - const auto reply = present("image/png"); - then("it carries the protective headers", [&] { - require(header(reply, "Cache-Control") == "no-store"); - require(header(reply, "Referrer-Policy") == "no-referrer"); - require(header(reply, "Content-Security-Policy") == "sandbox; default-src 'none'"); - require(header(reply, "X-Content-Type-Options") == "nosniff"); - require(header(reply, "Cross-Origin-Resource-Policy") == "same-origin"); + given("passive types", [&] { + for (const auto* type : + {"image/png", "image/jpeg", "image/gif", "image/webp", "audio/mpeg", "video/mp4", "text/plain", "text/plain; charset=utf-8", "VIDEO/WEBM"}) { + then(type, " is shown inline with its type", [&] { + const auto reply = present(type); + require(header(reply, "Content-Type") == type); + require(!header(reply, "Content-Disposition")); + }); + } + }); + given("active types", [&] { + for (const auto* type : {"text/html", + "text/html; charset=utf-8", + "application/xhtml+xml", + "text/xml", + "application/xml", + "application/atom+xml", + "text/javascript", + "application/javascript", + "application/ecmascript", + "text/javascript1.5", + "application/x-ecmascript", + "text/jscript", + "text/livescript", + "text/css", + "application/wasm", + "TEXT/HTML"}) { + then(type, " is a download announced as octet-stream", [&] { + const auto reply = present(type); + require(header(reply, "Content-Type") == "application/octet-stream"); + require(header(reply, "Content-Disposition")->starts_with("attachment; filename=\"file.bin\"")); + }); + } }); - }); - given("passive types", [&] { - for (const auto* type : {"image/png", "image/jpeg", "image/gif", "image/webp", "audio/mpeg", "video/mp4", "text/plain", "text/plain; charset=utf-8", "VIDEO/WEBM"}) { - then(type, " is shown inline with its type", [&] { - const auto reply = present(type); - require(header(reply, "Content-Type") == type); - require(!header(reply, "Content-Disposition")); - }); - } - }); - given("active types", [&] { - for (const auto* type : {"text/html", "text/html; charset=utf-8", "application/xhtml+xml", "text/xml", "application/xml", "application/atom+xml", - "text/javascript", "application/javascript", "application/ecmascript", "text/javascript1.5", "application/x-ecmascript", "text/jscript", "text/livescript", "text/css", "application/wasm", "TEXT/HTML"}) { - then(type, " is a download announced as octet-stream", [&] { - const auto reply = present(type); - require(header(reply, "Content-Type") == "application/octet-stream"); - require(header(reply, "Content-Disposition")->starts_with("attachment; filename=\"file.bin\"")); + given("an SVG", [&] { + const auto reply = present("image/svg+xml", "logo.svg"); + then("it keeps its type, for , and a navigation downloads it", [&] { + require(header(reply, "Content-Type") == "image/svg+xml"); + require(header(reply, "Content-Disposition")->starts_with("attachment; filename=\"logo.svg\"")); }); - } - }); - given("an SVG", [&] { - const auto reply = present("image/svg+xml", "logo.svg"); - then("it keeps its type, for , and a navigation downloads it", [&] { - require(header(reply, "Content-Type") == "image/svg+xml"); - require(header(reply, "Content-Disposition")->starts_with("attachment; filename=\"logo.svg\"")); }); - }); - given("a type outside the closed list, or none", [&] { - then("it is a download", [&] { - require(header(present("application/pdf"), "Content-Disposition")->starts_with("attachment")); - require(header(present("application/pdf"), "Content-Type") == "application/pdf"); - require(header(present("text/css"), "Content-Disposition")->starts_with("attachment")); - require(header(present(""), "Content-Type") == "application/octet-stream"); - require(header(present(""), "Content-Disposition")->starts_with("attachment")); + given("a type outside the closed list, or none", [&] { + then("it is a download", [&] { + require(header(present("application/pdf"), "Content-Disposition")->starts_with("attachment")); + require(header(present("application/pdf"), "Content-Type") == "application/pdf"); + require(header(present("text/css"), "Content-Disposition")->starts_with("attachment")); + require(header(present(""), "Content-Type") == "application/octet-stream"); + require(header(present(""), "Content-Disposition")->starts_with("attachment")); + }); }); - }); - given("a hostile file name", [&] { - const auto reply = present("text/html", "a\"b\r\nSet-Cookie: x;\\c/é.html"); - then("the header stays one well-formed line", [&] { - const auto disposition = *header(reply, "Content-Disposition"); - require(disposition.find('\r') == std::string::npos); - require(disposition.find('\n') == std::string::npos); - require(disposition.starts_with("attachment; filename=\"")); - require(disposition.contains("filename*=UTF-8''")); - require(disposition.contains("%C3%A9.html")); + given("a hostile file name", [&] { + const auto reply = present("text/html", "a\"b\r\nSet-Cookie: x;\\c/é.html"); + then("the header stays one well-formed line", [&] { + const auto disposition = *header(reply, "Content-Disposition"); + require(disposition.find('\r') == std::string::npos); + require(disposition.find('\n') == std::string::npos); + require(disposition.starts_with("attachment; filename=\"")); + require(disposition.contains("filename*=UTF-8''")); + require(disposition.contains("%C3%A9.html")); + }); }); - }); - given("a response a handler built with headers of its own", [&] { - http::RouteReply reply; - reply.headers.emplace_back("Content-Type", "text/plain"); - reply.headers.emplace_back("cache-control", "public, max-age=3600"); - reply.headers.emplace_back("Content-Security-Policy", "default-src *"); - detail::hardenRead(reply, "a.txt"); - then("its caching and policy are replaced, not duplicated", [&] { - require(headers(reply, "Cache-Control") == std::vector{"no-store"}); - require(headers(reply, "Content-Security-Policy") == std::vector{"sandbox; default-src 'none'"}); + given("a response a handler built with headers of its own", [&] { + http::RouteReply reply; + reply.headers.emplace_back("Content-Type", "text/plain"); + reply.headers.emplace_back("cache-control", "public, max-age=3600"); + reply.headers.emplace_back("Content-Security-Policy", "default-src *"); + detail::hardenRead(reply, "a.txt"); + then("its caching and policy are replaced, not duplicated", [&] { + require(headers(reply, "Cache-Control") == std::vector{"no-store"}); + require(headers(reply, "Content-Security-Policy") == std::vector{"sandbox; default-src 'none'"}); + }); }); - }); - given("a refusal", [&] { - Fixture fixture; - const auto denied = call(fixture.read, std::string(readPrefix) + "nothing.here/x"); - then("it is neutralized too, and tells nothing", [&] { - require(denied.status == http::Response::forbidden); - require(header(denied, "Cache-Control") == "no-store"); - require(header(denied, "Referrer-Policy") == "no-referrer"); + given("a refusal", [&] { + Fixture fixture; + const auto denied = call(fixture.read, std::string(readPrefix) + "nothing.here/x"); + then("it is neutralized too, and tells nothing", [&] { + require(denied.status == http::Response::forbidden); + require(header(denied, "Cache-Control") == "no-store"); + require(header(denied, "Referrer-Policy") == "no-referrer"); + }); }); - }); -}}; + }}; namespace { @@ -502,7 +594,9 @@ class LogCapture { logged += std::string(line) + "\n"; })); } - ~LogCapture() { stop(); } + ~LogCapture() { + stop(); + } void stop() { if (std::exchange(active, false)) { webfront::log::removeSinks(sink); @@ -515,10 +609,10 @@ class LogCapture { } private: - std::mutex mutex; - std::string logged; + std::mutex mutex; + std::string logged; decltype(webfront::log::addSinks(std::function{})) sink{}; - bool active = true; + bool active = true; }; struct NoFiles { @@ -528,7 +622,9 @@ struct NoFiles { /// A file provider whose failure quotes the path it was asked for. struct ThrowingFileSystem { ThrowingFileSystem(std::filesystem::path) {} - std::optional open(std::filesystem::path file) { throw std::runtime_error("cannot open " + file.string()); } + std::optional open(std::filesystem::path file) { + throw std::runtime_error("cannot open " + file.string()); + } }; /// One connection, accepted at once. @@ -549,7 +645,9 @@ struct CleanSocket { testing::InjectableSocket::reset(); ReadNet::accepts = 0; } - ~CleanSocket() { testing::InjectableSocket::reset(); } + ~CleanSocket() { + testing::InjectableSocket::reset(); + } }; /// A server whose single connection receives one request: answer() returns what was logged meanwhile, and response() what @@ -574,95 +672,115 @@ struct OneRequest : CleanSocket { log.stop(); return log.text(); } - static std::string response() { return testing::InjectableSocket::writtenText(); } + static std::string response() { + return testing::InjectableSocket::writtenText(); + } }; } // namespace const Scenario serverNever{"The server never writes a read token to its logs", {"read-binding"}, [] { - OneRequest<> request; - Fixture fixture; - const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); - const auto url = fixture.url(1, "secret-name.txt"); - auto route = request.server.addRoute(std::string(readPrefix), fixture.read, true); - const auto logged = request.answer("GET " + url, "Cookie: " + cookie + "\r\n"); - - then("the response is the neutralized read, and no log line holds the token", [&] { - const auto response = request.response(); - require(response.starts_with("HTTP/1.1 200 OK\r\n")); - require(response.contains("Content-Security-Policy: sandbox; default-src 'none'\r\n")); - const auto token = url.substr(readPrefix.size(), 16 + 1 + 64); - require(logged.contains("Received request GET on /webfront/services/files/...")); - require(!logged.contains(token)); - require(!logged.contains(token.substr(0, 16))); - require(!logged.contains("secret-name")); - }); -}}; + OneRequest<> request; + Fixture fixture; + const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); + const auto url = fixture.url(1, "secret-name.txt"); + auto route = request.server.addRoute(std::string(readPrefix), fixture.read, true); + const auto logged = request.answer("GET " + url, "Cookie: " + cookie + "\r\n"); + + then("the response is the neutralized read, and no log line holds the token", [&] { + const auto response = request.response(); + require(response.starts_with("HTTP/1.1 200 OK\r\n")); + require(response.contains("Content-Security-Policy: sandbox; default-src 'none'\r\n")); + const auto token = url.substr(readPrefix.size(), 16 + 1 + 64); + require(logged.contains("Received request GET on /webfront/services/files/...")); + require(!logged.contains(token)); + require(!logged.contains(token.substr(0, 16))); + require(!logged.contains("secret-name")); + }); + }}; const Scenario noLog{"No log line holds the token of a services target, whatever answers it", {"read-binding"}, [] { - const std::string target = std::string(readPrefix) + "0123456789abcdef.TOKENSECRET/a.txt"; - then("a target unfit for route dispatch, plain or spelled with an encoded letter and doubled separators, falls to the " - "file providers without being logged", [&] { - // "report..txt" makes the target unfit for route dispatch. - for (const auto* unfit : {"/webfront/services/files/0123456789abcdef.TOKENSECRET/report..txt", - "/%77ebfront//services/./files/0123456789abcdef.TOKENSECRET/report..txt"}) { - OneRequest<> request; - const auto logged = request.answer(std::string("GET ") + unfit); - require(logged.contains("Received request GET")); - require(!logged.contains("TOKENSECRET")); - require(!logged.contains("report")); - } - }); - then("the error of a failing secret route is not logged", [&] { - OneRequest<> request; - auto route = request.server.addRoute(std::string(readPrefix), [](const http::RouteRequest& failed) -> http::RouteReply { - throw std::runtime_error("cannot open " + std::string(failed.path)); - }, true); - const auto logged = request.answer("GET " + target); - require(logged.contains("failed")); - require(!logged.contains("TOKENSECRET")); - }); - then("a file provider that fails on the target, with no route registered, does not log it", [&] { - OneRequest request; - const auto logged = request.answer("GET " + target); - require(logged.contains("failed")); - require(!logged.contains("TOKENSECRET")); - }); - then("a secret route lives under the services space, and the query of a request is never logged", [&] { - OneRequest<> request; - requireThrows([&] { (void)request.server.addRoute("/files/", [](const http::RouteRequest&) { return http::RouteReply{}; }, true); }); - const auto logged = request.answer("GET /viewer?file=%2Fwebfront%2Fservices%2Ffiles%2FQUERYSECRET%2Fdoc"); - require(logged.contains("Received request GET on /viewer")); - require(!logged.contains("QUERYSECRET")); - }); -}}; + const std::string target = std::string(readPrefix) + "0123456789abcdef.TOKENSECRET/a.txt"; + then("a target unfit for route dispatch, plain or spelled with an encoded letter and doubled separators, falls to the " + "file providers without being logged", + [&] { + // "report..txt" makes the target unfit for route dispatch. + for (const auto* unfit : {"/webfront/services/files/0123456789abcdef.TOKENSECRET/report..txt", + "/%77ebfront//services/./files/0123456789abcdef.TOKENSECRET/report..txt"}) { + OneRequest<> request; + const auto logged = request.answer(std::string("GET ") + unfit); + require(logged.contains("Received request GET")); + require(!logged.contains("TOKENSECRET")); + require(!logged.contains("report")); + } + }); + then("the error of a failing secret route is not logged", [&] { + OneRequest<> request; + auto route = request.server.addRoute( + std::string(readPrefix), + [](const http::RouteRequest& failed) -> http::RouteReply { + throw std::runtime_error("cannot open " + std::string(failed.path)); + }, + true); + const auto logged = request.answer("GET " + target); + require(logged.contains("failed")); + require(!logged.contains("TOKENSECRET")); + }); + then("a file provider that fails on the target, with no route registered, does not log it", [&] { + OneRequest request; + const auto logged = request.answer("GET " + target); + require(logged.contains("failed")); + require(!logged.contains("TOKENSECRET")); + }); + then("a secret route lives under the services space, and the query of a request is never logged", [&] { + OneRequest<> request; + requireThrows([&] { + (void)request.server.addRoute( + "/files/", + [](const http::RouteRequest&) { + return http::RouteReply{}; + }, + true); + }); + const auto logged = request.answer("GET /viewer?file=%2Fwebfront%2Fservices%2Ffiles%2FQUERYSECRET%2Fdoc"); + require(logged.contains("Received request GET on /viewer")); + require(!logged.contains("QUERYSECRET")); + }); + }}; const Scenario answersServer{"The answers the server writes for a read route are hardened too", {"read-binding"}, [] { - for (const auto* method : {"GET", "POST"}) { - OneRequest<> request; - auto route = request.server.addRoute(std::string(readPrefix), [](const http::RouteRequest&) -> http::RouteReply { throw std::runtime_error("boom"); }, true, - [](http::RouteReply& reply) { detail::hardenRead(reply, {}); }); - request.answer(std::string(method) + " " + std::string(readPrefix) + "0123456789abcdef.SECRET/a.txt"); - const auto response = request.response(); - then(std::string(method) + " is refused with the hardening headers", [&] { - require(response.starts_with(std::string_view(method) == "GET" ? "HTTP/1.1 500" : "HTTP/1.1 405")); - require(response.contains("Cache-Control: no-store\r\n")); - require(response.contains("Referrer-Policy: no-referrer\r\n")); - require(response.contains("Content-Security-Policy: sandbox; default-src 'none'\r\n")); - require(response.contains("X-Content-Type-Options: nosniff\r\n")); - }); - } -}}; + for (const auto* method : {"GET", "POST"}) { + OneRequest<> request; + auto route = request.server.addRoute( + std::string(readPrefix), + [](const http::RouteRequest&) -> http::RouteReply { + throw std::runtime_error("boom"); + }, + true, + [](http::RouteReply& reply) { + detail::hardenRead(reply, {}); + }); + request.answer(std::string(method) + " " + std::string(readPrefix) + "0123456789abcdef.SECRET/a.txt"); + const auto response = request.response(); + then(std::string(method) + " is refused with the hardening headers", [&] { + require(response.starts_with(std::string_view(method) == "GET" ? "HTTP/1.1 500" : "HTTP/1.1 405")); + require(response.contains("Cache-Control: no-store\r\n")); + require(response.contains("Referrer-Policy: no-referrer\r\n")); + require(response.contains("Content-Security-Policy: sandbox; default-src 'none'\r\n")); + require(response.contains("X-Content-Type-Options: nosniff\r\n")); + }); + } + }}; const Scenario frameNever{"A frame never logs the bytes of its payload", {"read-binding"}, [] { - LogCapture log; - std::vector bytes(64, static_cast('q')); - websocket::Frame frame{std::string_view{}}; - frame.addBuffer(bytes); - log.stop(); - require(!log.text().contains("qqqq")); - require(!log.text().contains("71 71")); -}}; + LogCapture log; + std::vector bytes(64, static_cast('q')); + websocket::Frame frame{std::string_view{}}; + frame.addBuffer(bytes); + log.stop(); + require(!log.text().contains("qqqq")); + require(!log.text().contains("71 71")); + }}; namespace { @@ -671,154 +789,192 @@ using ReadApp = BasicWF; } // namespace const Scenario applicationRegisters{"An application registers read routes under the services path only", {"read-binding"}, [] { - testing::InjectableSocket::reset(); - ReadNet::accepts = 100; - ReadApp app{WebFrontConfig{.port = "0"}}; - const auto handler = [](const http::RouteRequest&, const ReadGrant&) { return http::RouteReply{}; }; - then("a readPrefix outside the cookie's path, the path itself and the exchange route are refused", [&] { - requireThrows([&] { static_cast(app.addReadRoute("/files/", handler)); }); - requireThrows([&] { static_cast(app.addReadRoute("/webfront/services/", handler)); }); - requireThrows([&] { static_cast(app.addReadRoute("/webfront/services/bind/", handler)); }); - requireThrows([&] { static_cast(app.addReadRoute("/webfront/services/bind/more/", handler)); }); - requireThrows([&] { static_cast(app.addReadRoute("/webfront/services/files/", nullptr)); }); - }); - then("a readPrefix under it is accepted once, then free again when the route is dropped", [&] { - { - auto route = app.addReadRoute("/webfront/services/files/", handler); - require(route); - requireThrows([&] { static_cast(app.addReadRoute("/webfront/services/files/", handler)); }); - } - requireNothrow([&] { static_cast(app.addReadRoute("/webfront/services/files/", handler)); }); - }); - then("a route of another application grants nothing to this one's browser", [&] { - ReadApp other{WebFrontConfig{.port = "0"}}; - auto foreign = other.addReadRoute("/webfront/services/files/", handler); - ReadApp::UI ui{app, 0, 1}; - requireThrows([&] { (void)ui.grantRead(foreign, "a.txt"); }, contains("another application")); - }); - then("a loopback declaration is refused for an application that listens on all interfaces", [&] { - requireThrows([&] { ReadApp(WebFrontConfig{.address = "0.0.0.0", .port = "0", .remoteFileTransport = RemoteFileTransport::loopbackAttested}); }); - }); - testing::InjectableSocket::reset(); -}}; + testing::InjectableSocket::reset(); + ReadNet::accepts = 100; + ReadApp app{WebFrontConfig{.port = "0"}}; + const auto handler = [](const http::RouteRequest&, const ReadGrant&) { + return http::RouteReply{}; + }; + then("a readPrefix outside the cookie's path, the path itself and the exchange route are refused", [&] { + requireThrows([&] { + static_cast(app.addReadRoute("/files/", handler)); + }); + requireThrows([&] { + static_cast(app.addReadRoute("/webfront/services/", handler)); + }); + requireThrows([&] { + static_cast(app.addReadRoute("/webfront/services/bind/", handler)); + }); + requireThrows([&] { + static_cast(app.addReadRoute("/webfront/services/bind/more/", handler)); + }); + requireThrows([&] { + static_cast(app.addReadRoute("/webfront/services/files/", nullptr)); + }); + }); + then("a readPrefix under it is accepted once, then free again when the route is dropped", [&] { + { + auto route = app.addReadRoute("/webfront/services/files/", handler); + require(route); + requireThrows([&] { + static_cast(app.addReadRoute("/webfront/services/files/", handler)); + }); + } + requireNothrow([&] { + static_cast(app.addReadRoute("/webfront/services/files/", handler)); + }); + }); + then("a route of another application grants nothing to this one's browser", [&] { + ReadApp other{WebFrontConfig{.port = "0"}}; + auto foreign = other.addReadRoute("/webfront/services/files/", handler); + ReadApp::UI ui{app, 0, 1}; + requireThrows( + [&] { + (void)ui.grantRead(foreign, "a.txt"); + }, + contains("another application")); + }); + then("a loopback declaration is refused for an application that listens on all interfaces", [&] { + requireThrows([&] { + ReadApp(WebFrontConfig{.address = "0.0.0.0", + .port = "0", + .remoteFileTransport = RemoteFileTransport::loopbackAttested}); + }); + }); + testing::InjectableSocket::reset(); + }}; const Scenario eachApplication{"Each application names its own cookies, and a namespace named after the port survives a restart", {"read-binding"}, [] { - given("a client bound to each of two applications on one host, whose cookies the browser shares", [&] { - Fixture first, second; - const auto cookieA = cookiePair(headers(first.bind(1, true), "Set-Cookie").front()); - const auto both = cookieA + "; " + cookiePair(headers(second.bind(1, true), "Set-Cookie").front()); - require(cookieA.starts_with("wf-client-")); - require(first.binding.clientCookiePrefix() != second.binding.clientCookiePrefix()); - - then("binding the second one erases nothing of the first, and the reads still pass", [&] { - const auto again = second.bind(2, true, both); - for (const auto& setCookie : headers(again, "Set-Cookie")) - require(!setCookie.contains("Max-Age=0")); - const auto url = first.url(1); - require(call(first.read, url, both).status == http::Response::ok); - }); - }); - given("an application restarted on the same port", [&] { - Fixture before, after; - before.binding.useNamespace("9002"); - after.binding.useNamespace("9002"); - const auto cookie = cookiePair(headers(before.bind(1, true), "Set-Cookie").front()); - then("it recognizes the cookie of its previous run and erases it", [&] { - require(cookie.starts_with("wf-client-9002-")); - bool erased = false; - for (const auto& line : headers(after.bind(1, true, cookie), "Set-Cookie")) - erased = erased || (line.starts_with(cookie.substr(0, cookie.find('=')) + "=;") && line.contains("Max-Age=0")); - require(erased); - }); - }); -}}; + given("a client bound to each of two applications on one host, whose cookies the browser shares", [&] { + Fixture first, second; + const auto cookieA = cookiePair(headers(first.bind(1, true), "Set-Cookie").front()); + const auto both = cookieA + "; " + cookiePair(headers(second.bind(1, true), "Set-Cookie").front()); + require(cookieA.starts_with("wf-client-")); + require(first.binding.clientCookiePrefix() != second.binding.clientCookiePrefix()); + + then("binding the second one erases nothing of the first, and the reads still pass", [&] { + const auto again = second.bind(2, true, both); + for (const auto& setCookie : headers(again, "Set-Cookie")) + require(!setCookie.contains("Max-Age=0")); + const auto url = first.url(1); + require(call(first.read, url, both).status == http::Response::ok); + }); + }); + given("an application restarted on the same port", [&] { + Fixture before, after; + before.binding.useNamespace("9002"); + after.binding.useNamespace("9002"); + const auto cookie = cookiePair(headers(before.bind(1, true), "Set-Cookie").front()); + then("it recognizes the cookie of its previous run and erases it", [&] { + require(cookie.starts_with("wf-client-9002-")); + bool erased = false; + for (const auto& line : headers(after.bind(1, true, cookie), "Set-Cookie")) + erased = erased || (line.starts_with(cookie.substr(0, cookie.find('=')) + "=;") && line.contains("Max-Age=0")); + require(erased); + }); + }); + }}; const Scenario tokenOpens{"A token opens only the path it was issued for, and only a path the server would route", {"read-binding"}, [] { - Fixture fixture; - const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); - const auto url = fixture.url(1, "public.txt"); - require(call(fixture.read, url, cookie).status == http::Response::ok); - const auto other = url.substr(0, url.rfind('/')) + "/private.txt"; - require(call(fixture.read, other, cookie).status == http::Response::forbidden); - require(fixture.lastRest == "public.txt"); - const auto transferable = fixture.url(1, "public.txt", {.lifetime = 60s, .transferable = true}); - require(call(fixture.read, transferable).status == http::Response::ok); - require(call(fixture.read, transferable.substr(0, transferable.rfind('/')) + "/private.txt").status == http::Response::forbidden); - for (const std::string_view path : {"a//b", "report..txt", "../up.txt", "a/../b", "tab\there.txt", "line\nbreak"}) - requireThrows([&] { fixture.url(1, path); }); - requireNothrow([&] { fixture.url(1, "dir/report.v2.txt"); }); -}}; + Fixture fixture; + const auto cookie = cookiePair(headers(fixture.bind(1, true), "Set-Cookie").front()); + const auto url = fixture.url(1, "public.txt"); + require(call(fixture.read, url, cookie).status == http::Response::ok); + const auto other = url.substr(0, url.rfind('/')) + "/private.txt"; + require(call(fixture.read, other, cookie).status == http::Response::forbidden); + require(fixture.lastRest == "public.txt"); + const auto transferable = fixture.url(1, "public.txt", {.lifetime = 60s, .transferable = true}); + require(call(fixture.read, transferable).status == http::Response::ok); + require(call(fixture.read, transferable.substr(0, transferable.rfind('/')) + "/private.txt").status == http::Response::forbidden); + for (const std::string_view path : {"a//b", "report..txt", "../up.txt", "a/../b", "tab\there.txt", "line\nbreak"}) + requireThrows([&] { + fixture.url(1, path); + }); + requireNothrow([&] { + fixture.url(1, "dir/report.v2.txt"); + }); + }}; const Scenario grantContext{"A grant's context is released when the grant expires or the binding shuts down", {"read-binding"}, [] { - Fixture fixture; - fixture.bind(1, true); - auto held = std::make_shared(7); - std::weak_ptr watch = held; - when("the grant expires", [&] { - (void)fixture.url(1, "a", {.lifetime = 60s, .context = held}); - held.reset(); - require(!watch.expired()); - fixture.time += 61s; - (void)fixture.url(1, "b"); // issuing another grant sweeps the expired ones - then("its context is released without the grant being requested again", [&] { require(watch.expired()); }); - }); - when("the binding shuts down", [&] { - const auto url = fixture.url(1, "a", {.context = held}); - held.reset(); - require(!watch.expired()); - fixture.binding.shutdown(); - then("it holds nothing and grants nothing", [&] { - require(watch.expired()); - requireThrows([&] { fixture.url(1, "b"); }); - require(call(fixture.read, url).status == http::Response::forbidden); - }); - }); -}}; + Fixture fixture; + fixture.bind(1, true); + auto held = std::make_shared(7); + std::weak_ptr watch = held; + when("the grant expires", [&] { + (void)fixture.url(1, "a", {.lifetime = 60s, .context = held}); + held.reset(); + require(!watch.expired()); + fixture.time += 61s; + (void)fixture.url(1, "b"); // issuing another grant sweeps the expired ones + then("its context is released without the grant being requested again", [&] { + require(watch.expired()); + }); + }); + when("the binding shuts down", [&] { + const auto url = fixture.url(1, "a", {.context = held}); + held.reset(); + require(!watch.expired()); + fixture.binding.shutdown(); + then("it holds nothing and grants nothing", [&] { + require(watch.expired()); + requireThrows([&] { + fixture.url(1, "b"); + }); + require(call(fixture.read, url).status == http::Response::forbidden); + }); + }); + }}; const Scenario droppingGrant{"Dropping a grant never runs its context's destructor under the lock", {"read-binding"}, [] { - Fixture fixture; - fixture.bind(1, true); - // A context whose deleter calls back into the binding would deadlock if it ran while the binding is locked. - const auto reentrant = [&fixture] { - return std::shared_ptr(new int(1), [&fixture](int* value) { - delete value; - (void)fixture.binding.accepts("route-a", "none", "x", {}); - }); - }; - when("the grant expires", [&] { - (void)fixture.url(1, "a", {.lifetime = 1s, .context = reentrant()}); - fixture.time += 2s; - then("the next grant sweeps it", [&] { requireNothrow([&] { fixture.url(1, "b"); }); }); - }); - when("the grant is revoked", [&] { - fixture.binding.revoke(fixture.url(1, "a", {.context = reentrant()})); - }); - when("its connection closes", [&] { - (void)fixture.url(1, "a", {.context = reentrant()}); - fixture.binding.close(1); - }); - when("the application shuts down", [&] { - (void)fixture.url(1, "a", {.context = reentrant()}); - fixture.binding.shutdown(); - }); -}}; + Fixture fixture; + fixture.bind(1, true); + // A context whose deleter calls back into the binding would deadlock if it ran while the binding is locked. + const auto reentrant = [&fixture] { + return std::shared_ptr(new int(1), [&fixture](int* value) { + delete value; + (void)fixture.binding.accepts("route-a", "none", "x", {}); + }); + }; + when("the grant expires", [&] { + (void)fixture.url(1, "a", {.lifetime = 1s, .context = reentrant()}); + fixture.time += 2s; + then("the next grant sweeps it", [&] { + requireNothrow([&] { + fixture.url(1, "b"); + }); + }); + }); + when("the grant is revoked", [&] { + fixture.binding.revoke(fixture.url(1, "a", {.context = reentrant()})); + }); + when("its connection closes", [&] { + (void)fixture.url(1, "a", {.context = reentrant()}); + fixture.binding.close(1); + }); + when("the application shuts down", [&] { + (void)fixture.url(1, "a", {.context = reentrant()}); + fixture.binding.shutdown(); + }); + }}; const Scenario secureListenerWarning{"An integrated TLS listener outside loopback warns without a log sink", [] { - std::ostringstream output; - struct Restore { - std::streambuf* previous; - ~Restore() { std::cerr.rdbuf(previous); } - } restore{std::cerr.rdbuf(output.rdbuf())}; - then("loopback and the TCP provider stay quiet", [&] { - detail::makeReadBinding(WebFrontConfig{}, true); - detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, false); - require(output.str().empty()); - }); - then("wildcard TLS reports the synchronous work on standard error", [&] { - detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, true); - require(output.str().contains("TLS listener outside loopback")); - require(output.str().contains("bursts can delay established connections")); - require(output.str().contains("denial of service")); - }); -}}; + std::ostringstream output; + struct Restore { + std::streambuf* previous; + ~Restore() { + std::cerr.rdbuf(previous); + } + } restore{std::cerr.rdbuf(output.rdbuf())}; + then("loopback and the TCP provider stay quiet", [&] { + detail::makeReadBinding(WebFrontConfig{}, true); + detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, false); + require(output.str().empty()); + }); + then("wildcard TLS reports the synchronous work on standard error", [&] { + detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, true); + require(output.str().contains("TLS listener outside loopback")); + require(output.str().contains("bursts can delay established connections")); + require(output.str().contains("denial of service")); + }); + }}; diff --git a/test/unit/SafePathTests.cpp b/test/unit/SafePathTests.cpp index d73fdd3e..b0b5bc44 100644 --- a/test/unit/SafePathTests.cpp +++ b/test/unit/SafePathTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -12,20 +12,24 @@ using namespace std; using namespace webfront; const Scenario pathsBrowser{"Paths from the browser stay inside their directory", [] { - given("a relative path of plain components", [&] { - then("it is accepted, component by component", [&] { - require(fs::safeRelativePath("dist/assets/app.js") == filesystem::path("dist") / "assets" / "app.js"); - require(fs::safeRelativePath("ui/main.tsx") == filesystem::path("ui") / "main.tsx"); - }); - }); - given("unsafe paths", [&] { - then("they are rejected", [&] { - const vector paths{"", "/etc/passwd", "../x", "a/../../x", "a/./b", "a//b", "a/", "..", "...", "C:/x", "c:x", - "a\\..\\b", "a?.js", "a*.js", "ab", "a|b", "a\"b", "main..html", "a/b..c/d", string("a\0b", 3), string(4097, 'a')}; - for (const auto& path : paths) { - auto scope = info(path); - requireThrows([&] { fs::safeRelativePath(path); }); - } - }); - }); -}}; + given("a relative path of plain components", [&] { + then("it is accepted, component by component", [&] { + require(fs::safeRelativePath("dist/assets/app.js") == filesystem::path("dist") / "assets" / "app.js"); + require(fs::safeRelativePath("ui/main.tsx") == filesystem::path("ui") / "main.tsx"); + }); + }); + given("unsafe paths", [&] { + then("they are rejected", [&] { + const vector paths{ + "", "/etc/passwd", "../x", "a/../../x", "a/./b", "a//b", "a/", "..", + "...", "C:/x", "c:x", "a\\..\\b", "a?.js", "a*.js", "ab", + "a|b", "a\"b", "main..html", "a/b..c/d", string("a\0b", 3), string(4097, 'a')}; + for (const auto& path : paths) { + auto scope = info(path); + requireThrows([&] { + fs::safeRelativePath(path); + }); + } + }); + }); + }}; diff --git a/test/unit/StdnetShutdownTests.cpp b/test/unit/StdnetShutdownTests.cpp index bb1c38ab..fd5e584c 100644 --- a/test/unit/StdnetShutdownTests.cpp +++ b/test/unit/StdnetShutdownTests.cpp @@ -1,10 +1,10 @@ +#include "../../examples/PortOption.hpp" #include "InjectableNetworking.hpp" -#include #include #include #include +#include #include -#include "../../examples/PortOption.hpp" #ifdef _WIN32 #include @@ -13,17 +13,17 @@ #endif #include -#include #include -#include #include +#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include #include using namespace webfront::bdd; @@ -40,13 +40,21 @@ struct CountingNet : Stdnet { static inline std::atomic liveSockets{0}; struct Socket : Stdnet::Socket { - Socket(Stdnet::Socket&& accepted) noexcept : Stdnet::Socket(std::move(accepted)) { ++liveSockets; } - Socket(Socket&& other) noexcept : Stdnet::Socket(std::move(other)) { ++liveSockets; } - ~Socket() { --liveSockets; } + Socket(Stdnet::Socket&& accepted) noexcept : Stdnet::Socket(std::move(accepted)) { + ++liveSockets; + } + Socket(Socket&& other) noexcept : Stdnet::Socket(std::move(other)) { + ++liveSockets; + } + ~Socket() { + --liveSockets; + } }; static auto Accept(Acceptor& acceptor) { - return ex::then(Stdnet::Accept(acceptor), [](Stdnet::Socket accepted) { return Socket(std::move(accepted)); }); + return ex::then(Stdnet::Accept(acceptor), [](Stdnet::Socket accepted) { + return Socket(std::move(accepted)); + }); } }; @@ -59,7 +67,9 @@ std::string freePort() { return std::to_string(acceptor.local_endpoint().port()); } -void connect(Stdnet::Socket& client, const std::string& port) { client.connect(Stdnet::Resolve("127.0.0.1", port)); } +void connect(Stdnet::Socket& client, const std::string& port) { + client.connect(Stdnet::Resolve("127.0.0.1", port)); +} void waitForHeaderData(Stdnet::Socket& socket, std::chrono::steady_clock::time_point deadline) { const auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()).count(); @@ -87,7 +97,8 @@ std::string readHeaders(Stdnet::Socket& socket, std::chrono::milliseconds timeou while (received.find("\r\n\r\n") == std::string::npos) { waitForHeaderData(socket, deadline); const auto size = socket.receive(Stdnet::Buffer(buffer)); - if (size == 0) break; + if (size == 0) + break; received.append(buffer.data(), size); } return received; @@ -98,113 +109,131 @@ webfront::Task cleanupReleasesHandler(http::Server& serve co_await server.resumeAfter(1h); } -const std::string upgradeRequest = - "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; +const std::string upgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; } // namespace const Scenario hTTPListener{"The HTTP listener is ready before its event loop starts", [] { - const auto port = freePort(); - http::Server server("127.0.0.1", port); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - // No server thread and no run()/runOne(): a synchronous connection must already succeed. - requireNothrow([&] { connect(client, port); }); - require(client.is_open()); -}}; + const auto port = freePort(); + http::Server server("127.0.0.1", port); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + // No server thread and no run()/runOne(): a synchronous connection must already succeed. + requireNothrow([&] { + connect(client, port); + }); + require(client.is_open()); + }}; const Scenario acceptedConnections{"Accepted connections retain TCP_NODELAY through WebSocket upgrade", [] { - given("A real stdnet HTTP server and a loopback client", [&] { - const auto port = freePort(); - http::Server server("127.0.0.1", port); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - bool upgraded = false; - bool noDelay = false; - server.onUpgrade([&](Stdnet::Socket&& socket) { - ::stdnet::ip::tcp_no_delay option; - socket.get_option(option); - noDelay = option.value(); - upgraded = true; - server.stop(); - }); - connect(client, port); - client.send(std::as_bytes(std::span(upgradeRequest))); - server.run(); - then("the socket passed to the bridge has Nagle disabled", [&] { - require(upgraded); - require(noDelay); - }); - }); -}}; + given("A real stdnet HTTP server and a loopback client", [&] { + const auto port = freePort(); + http::Server server("127.0.0.1", port); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + bool upgraded = false; + bool noDelay = false; + server.onUpgrade([&](Stdnet::Socket&& socket) { + ::stdnet::ip::tcp_no_delay option; + socket.get_option(option); + noDelay = option.value(); + upgraded = true; + server.stop(); + }); + connect(client, port); + client.send(std::as_bytes(std::span(upgradeRequest))); + server.run(); + then("the socket passed to the bridge has Nagle disabled", [&] { + require(upgraded); + require(noDelay); + }); + }); + }}; const Scenario stoppingRunning{"Stopping a running server releases its connections", [] { - given("A running server with an idle client connection", [&] { - const auto port = freePort(); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - { - http::Server server("127.0.0.1", port); - std::thread serverThread([&server] { server.run(); }); - connect(client, port); - checkEventually([] { return CountingNet::liveSockets.load() > 0; }, 5s); - - server.stop(); // from another thread than the one running the server - serverThread.join(); - } - then("no socket is left once the server is destroyed", [&] { require(CountingNet::liveSockets.load() == 0); }); - }); -}}; + given("A running server with an idle client connection", [&] { + const auto port = freePort(); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + { + http::Server server("127.0.0.1", port); + std::thread serverThread([&server] { + server.run(); + }); + connect(client, port); + checkEventually( + [] { + return CountingNet::liveSockets.load() > 0; + }, + 5s); + + server.stop(); // from another thread than the one running the server + serverThread.join(); + } + then("no socket is left once the server is destroyed", [&] { + require(CountingNet::liveSockets.load() == 0); + }); + }); + }}; const Scenario destroyingServer{"Destroying a server which is not running releases its connections", [] { - given("A server which accepted a client connection", [&] { - const auto port = freePort(); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - { - http::Server server("127.0.0.1", port); - connect(client, port); - for (int i = 0; i < 10 && CountingNet::liveSockets.load() == 0; ++i) server.runOne(); - check(CountingNet::liveSockets.load() > 0); - } - then("no socket is left", [&] { require(CountingNet::liveSockets.load() == 0); }); - }); -}}; + given("A server which accepted a client connection", [&] { + const auto port = freePort(); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + { + http::Server server("127.0.0.1", port); + connect(client, port); + for (int i = 0; i < 10 && CountingNet::liveSockets.load() == 0; ++i) + server.runOne(); + check(CountingNet::liveSockets.load() > 0); + } + then("no socket is left", [&] { + require(CountingNet::liveSockets.load() == 0); + }); + }); + }}; const Scenario destroyingWebFront{"Destroying WebFront closes its established WebSockets", [] { - given("A WebFront with an established WebSocket", [&] { - const auto port = freePort(); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - { - BasicWF webFront(WebFrontConfig{.address = "127.0.0.1", .port = port}); - std::atomic linked = false; - webFront.onUIStarted([&](auto) { - linked = true; - }); - std::thread serverThread(&decltype(webFront)::run, &webFront); - connect(client, port); - client.send(std::as_bytes(std::span(upgradeRequest))); - check(readHeaders(client).starts_with("HTTP/1.1 101")); - // The HTTP response can arrive before onUpgrade creates the WebLink. Complete the - // masked bridge handshake before stopping, so this tests an established connection. - const std::array - handshake{0x82, 0x82, 0, 0, 0, 0, static_cast(msg::Command::handshake), static_cast(msg::JSEndian::little)}; - client.send(Stdnet::ConstBuffer(handshake.data(), handshake.size())); - checkEventually( - [&] { - return linked.load(); - }, - 5s); - webFront.stop(); - serverThread.join(); - } - then("no socket is left", [&] { - require(CountingNet::liveSockets.load() == 0); - }); - }); -}}; + given("A WebFront with an established WebSocket", [&] { + const auto port = freePort(); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + { + BasicWF webFront(WebFrontConfig{.address = "127.0.0.1", .port = port}); + std::atomic linked = false; + webFront.onUIStarted([&](auto) { + linked = true; + }); + std::thread serverThread(&decltype(webFront)::run, &webFront); + connect(client, port); + client.send(std::as_bytes(std::span(upgradeRequest))); + check(readHeaders(client).starts_with("HTTP/1.1 101")); + // The HTTP response can arrive before onUpgrade creates the WebLink. Complete the + // masked bridge handshake before stopping, so this tests an established connection. + const std::array handshake{0x82, + 0x82, + 0, + 0, + 0, + 0, + static_cast(msg::Command::handshake), + static_cast(msg::JSEndian::little)}; + client.send(Stdnet::ConstBuffer(handshake.data(), handshake.size())); + checkEventually( + [&] { + return linked.load(); + }, + 5s); + webFront.stop(); + serverThread.join(); + } + then("no socket is left", [&] { + require(CountingNet::liveSockets.load() == 0); + }); + }); + }}; namespace { struct TaskThreadState { @@ -230,149 +259,174 @@ Task applicationTaskOnServer(TaskThreadState& state) { } // namespace const Scenario applicationTask{"Application task cancellation returns to the server context", [] { - given("an application task running on a real stdnet context", [&] { - TaskThreadState state; - BasicWF app(WebFrontConfig{.port = "0"}); - auto handle = app.spawn(applicationTaskOnServer(state)); - std::thread serverThread([&] { - app.run(); - }); - const auto serverId = serverThread.get_id(); - checkEventually( - [&] { - return state.started.load(std::memory_order_acquire); - }, - 5s); - when("another thread requests cancellation", [&] { - handle.requestStop(); - checkEventually( - [&] { - return state.destroyed.load(std::memory_order_acquire); - }, - 5s); - app.stop(); - serverThread.join(); - app.shutdown(); - then("the coroutine starts and unwinds on the server context thread", [&] { - check(state.destroyed.load(std::memory_order_acquire)); - check(state.startedOn == serverId); - check(state.destroyedOn == serverId); - }); - }); - }); -}}; + given("an application task running on a real stdnet context", [&] { + TaskThreadState state; + BasicWF app(WebFrontConfig{.port = "0"}); + auto handle = app.spawn(applicationTaskOnServer(state)); + std::thread serverThread([&] { + app.run(); + }); + const auto serverId = serverThread.get_id(); + checkEventually( + [&] { + return state.started.load(std::memory_order_acquire); + }, + 5s); + when("another thread requests cancellation", [&] { + handle.requestStop(); + checkEventually( + [&] { + return state.destroyed.load(std::memory_order_acquire); + }, + 5s); + app.stop(); + serverThread.join(); + app.shutdown(); + then("the coroutine starts and unwinds on the server context thread", [&] { + check(state.destroyed.load(std::memory_order_acquire)); + check(state.startedOn == serverId); + check(state.destroyedOn == serverId); + }); + }); + }); + }}; const Scenario rejectedWebSocket{"A rejected WebSocket Origin never reaches the server upgrade callback", [] { - const auto port = freePort(); - http::Server server("127.0.0.1", port); - std::atomic upgrades = 0; - server.onUpgrade([&](Stdnet::Socket&&) { - ++upgrades; - }); - std::jthread serverThread([&](std::stop_token token) { - std::stop_callback stop(token, [&] { - server.stop(); - }); - server.run(); - }); - Stdnet::IoContext context; - Stdnet::Socket client(context); - connect(client, port); - const auto request = upgradeRequest.substr(0, upgradeRequest.size() - 2) + "Origin: https://untrusted.example\r\n\r\n"; - client.send(std::as_bytes(std::span(request))); - const auto response = readHeaders(client); - then("a foreign origin gets 403 without reaching the upgrade callback", [&] { - check(response.starts_with("HTTP/1.1 403 Forbidden\r\n")); - check(response.find("Sec-WebSocket-Accept:") == std::string::npos); - require(upgrades == 0); - }); - then("the same listener accepts the configured origin and invokes that callback", [&] { - Stdnet::Socket authorized(context); - connect(authorized, port); - const auto allowedRequest = upgradeRequest.substr(0, upgradeRequest.size() - 2) + "Origin: http://127.0.0.1:" + port + "\r\n\r\n"; - authorized.send(std::as_bytes(std::span(allowedRequest))); - check(readHeaders(authorized).starts_with("HTTP/1.1 101 Switching Protocols\r\n")); - checkEventually( - [&] { - return upgrades.load() != 0; - }, - 5s); - require(upgrades == 1); - }); - then("an idle peer cannot block the header reader indefinitely", [&] { - Stdnet::Socket idle(context); - connect(idle, port); - requireThrows([&] { readHeaders(idle, 0ms); }, equals("Timed out waiting for HTTP response headers")); - requireThrows([&] { readHeaders(idle, 10ms); }, equals("Timed out waiting for HTTP response headers")); - }); - serverThread.request_stop(); - serverThread.join(); -}}; + const auto port = freePort(); + http::Server server("127.0.0.1", port); + std::atomic upgrades = 0; + server.onUpgrade([&](Stdnet::Socket&&) { + ++upgrades; + }); + std::jthread serverThread([&](std::stop_token token) { + std::stop_callback stop(token, [&] { + server.stop(); + }); + server.run(); + }); + Stdnet::IoContext context; + Stdnet::Socket client(context); + connect(client, port); + const auto request = upgradeRequest.substr(0, upgradeRequest.size() - 2) + "Origin: https://untrusted.example\r\n\r\n"; + client.send(std::as_bytes(std::span(request))); + const auto response = readHeaders(client); + then("a foreign origin gets 403 without reaching the upgrade callback", [&] { + check(response.starts_with("HTTP/1.1 403 Forbidden\r\n")); + check(response.find("Sec-WebSocket-Accept:") == std::string::npos); + require(upgrades == 0); + }); + then("the same listener accepts the configured origin and invokes that callback", [&] { + Stdnet::Socket authorized(context); + connect(authorized, port); + const auto allowedRequest = upgradeRequest.substr(0, upgradeRequest.size() - 2) + "Origin: http://127.0.0.1:" + port + + "\r\n\r\n"; + authorized.send(std::as_bytes(std::span(allowedRequest))); + check(readHeaders(authorized).starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + checkEventually( + [&] { + return upgrades.load() != 0; + }, + 5s); + require(upgrades == 1); + }); + then("an idle peer cannot block the header reader indefinitely", [&] { + Stdnet::Socket idle(context); + connect(idle, port); + requireThrows( + [&] { + readHeaders(idle, 0ms); + }, + equals("Timed out waiting for HTTP response headers")); + requireThrows( + [&] { + readHeaders(idle, 10ms); + }, + equals("Timed out waiting for HTTP response headers")); + }); + serverThread.request_stop(); + serverThread.join(); + }}; const Scenario drainingPumps{"Draining pumps cancelled tasks while a route handler waits for their cleanup", [] { - const auto port = freePort(); - http::Server server("127.0.0.1", port); - std::promise released, entered; - std::atomic done{false}; - const auto release = [&] { - if (!done.exchange(true)) released.set_value(); - }; - auto route = server.addRoute("/webfront/services/wait/", [&, wait = released.get_future().share()](const http::RouteRequest&) { - entered.set_value(); - wait.wait(); - return http::RouteReply{}; - }); - { - std::shared_ptr guard(nullptr, [&](void*) { release(); }); - static_cast(server.startTask(cleanupReleasesHandler(server, std::move(guard)))); - } - std::thread serverThread([&server] { server.run(); }); - Stdnet::IoContext clientContext; - Stdnet::Socket client(clientContext); - connect(client, port); - const std::string request = "GET /webfront/services/wait/x HTTP/1.1\r\nHost: localhost\r\n\r\n"; - client.send(std::as_bytes(std::span(request))); - auto enteredFuture = entered.get_future(); - const bool handlerEntered = waitReady(enteredFuture, 5s); - server.stop(); - serverThread.join(); // before any assertion: a joinable thread would terminate the process - require(handlerEntered); - when("the server is drained", [&] { - auto drained = std::async(std::launch::async, [&server] { server.drain(); }); - const bool finished = waitReady(drained, 5s); - release(); // never leave the test hanging if the drain waited for the cleanup it was to run - drained.wait(); - then("the drain ran the cleanup which released the handler", [&] { require(finished); }); - }); -}}; + const auto port = freePort(); + http::Server server("127.0.0.1", port); + std::promise released, entered; + std::atomic done{false}; + const auto release = [&] { + if (!done.exchange(true)) + released.set_value(); + }; + auto route = server.addRoute("/webfront/services/wait/", [&, wait = released.get_future().share()](const http::RouteRequest&) { + entered.set_value(); + wait.wait(); + return http::RouteReply{}; + }); + { + std::shared_ptr guard(nullptr, [&](void*) { + release(); + }); + static_cast(server.startTask(cleanupReleasesHandler(server, std::move(guard)))); + } + std::thread serverThread([&server] { + server.run(); + }); + Stdnet::IoContext clientContext; + Stdnet::Socket client(clientContext); + connect(client, port); + const std::string request = "GET /webfront/services/wait/x HTTP/1.1\r\nHost: localhost\r\n\r\n"; + client.send(std::as_bytes(std::span(request))); + auto enteredFuture = entered.get_future(); + const bool handlerEntered = waitReady(enteredFuture, 5s); + server.stop(); + serverThread.join(); // before any assertion: a joinable thread would terminate the process + require(handlerEntered); + when("the server is drained", [&] { + auto drained = std::async(std::launch::async, [&server] { + server.drain(); + }); + const bool finished = waitReady(drained, 5s); + release(); // never leave the test hanging if the drain waited for the cleanup it was to run + drained.wait(); + then("the drain ran the cleanup which released the handler", [&] { + require(finished); + }); + }); + }}; const Scenario simultaneousInstances{"Servers side by side on ephemeral ports", [] { - given("a server that holds a port", [&] { - http::Server first("127.0.0.1", "0"); - then("a second server on port \"0\" gets another port", [&] { - http::Server second("127.0.0.1", "0"); - require(first.port() != second.port()); - require(second.port() != "0"); - }); - then("a server asking for the same port reports the address, the port and the cause", [&] { - const std::string port{first.port()}; - requireThrows([&] { http::Server clash("127.0.0.1", port); }, - contains("127.0.0.1:" + port)); - requireThrows([&] { http::Server clash("127.0.0.1", port); }, contains("WEBFRONT_PORT=0")); - }); - }); - given("many servers without a configured port", [&] { - std::vector>> servers; - for (int i = 0; i < 40; ++i) - servers.push_back(std::make_unique>("127.0.0.1", "0")); - then("each one listens on its own port", [&] { - std::set ports; - for (const auto& server : servers) - ports.insert(std::string(server->port())); - require(ports.size() == servers.size()); - }); - }); -}}; + given("a server that holds a port", [&] { + http::Server first("127.0.0.1", "0"); + then("a second server on port \"0\" gets another port", [&] { + http::Server second("127.0.0.1", "0"); + require(first.port() != second.port()); + require(second.port() != "0"); + }); + then("a server asking for the same port reports the address, the port and the cause", [&] { + const std::string port{first.port()}; + requireThrows( + [&] { + http::Server clash("127.0.0.1", port); + }, + contains("127.0.0.1:" + port)); + requireThrows( + [&] { + http::Server clash("127.0.0.1", port); + }, + contains("WEBFRONT_PORT=0")); + }); + }); + given("many servers without a configured port", [&] { + std::vector>> servers; + for (int i = 0; i < 40; ++i) + servers.push_back(std::make_unique>("127.0.0.1", "0")); + then("each one listens on its own port", [&] { + std::set ports; + for (const auto& server : servers) + ports.insert(std::string(server->port())); + require(ports.size() == servers.size()); + }); + }); + }}; void setPortVariable(const char* value) { #ifdef _WIN32 @@ -411,86 +465,106 @@ struct PortVariableGuard { }; const Scenario defaultPortFromEnvironment{"The default port follows WEBFRONT_PORT", [] { - const PortVariableGuard portGuard; - given("WEBFRONT_PORT set to 0", [&] { - setPortVariable("0"); - then("a configuration asks for an ephemeral port and two applications coexist", [&] { - require(WebFrontConfig{}.port.empty() && defaultPort() == "0"); - BasicWF a{WebFrontConfig{}}, b{WebFrontConfig{}}; - require(a.port() != b.port()); - }); - setPortVariable(""); - }); - given("WEBFRONT_PORT unset or empty", [&] { - setPortVariable(""); - then("the historical 9002 remains", [&] { require(defaultPort() == "9002"); }); - setPortVariable(""); - }); -}}; + const PortVariableGuard portGuard; + given("WEBFRONT_PORT set to 0", [&] { + setPortVariable("0"); + then("a configuration asks for an ephemeral port and two applications coexist", [&] { + require(WebFrontConfig{}.port.empty() && defaultPort() == "0"); + BasicWF a{WebFrontConfig{}}, b{WebFrontConfig{}}; + require(a.port() != b.port()); + }); + setPortVariable(""); + }); + given("WEBFRONT_PORT unset or empty", [&] { + setPortVariable(""); + then("the historical 9002 remains", [&] { + require(defaultPort() == "9002"); + }); + setPortVariable(""); + }); + }}; const Scenario portValidation{"A port is a number from 0 to 65535", [] { - const PortVariableGuard portGuard; - given("values the resolver would accept", [&] { - then("only canonical port numbers pass", [&] { - require(validatedPort("0", "t") == "0"); - require(validatedPort("9002", "t") == "9002"); - require(validatedPort("65535", "t") == "65535"); - for (const char* bad : {"", "00", "65536", "http", "-1", "+80", "80 ", "080", "123456"}) - requireThrows([&] { (void)validatedPort(bad, "WEBFRONT_PORT"); }, contains("WEBFRONT_PORT")); - }); - then("an invalid WEBFRONT_PORT makes the default configuration fail", [&] { - setPortVariable("http"); - requireThrows([&] { (void)defaultPort(); }, contains("'http'")); - setPortVariable(""); - }); - }); - given("a server asked for port 00", [&] { - http::Server server("127.0.0.1", "00"); - then("it announces the port really bound", [&] { require(server.port() != "00" && server.port() != "0"); }); - }); -}}; + const PortVariableGuard portGuard; + given("values the resolver would accept", [&] { + then("only canonical port numbers pass", [&] { + require(validatedPort("0", "t") == "0"); + require(validatedPort("9002", "t") == "9002"); + require(validatedPort("65535", "t") == "65535"); + for (const char* bad : {"", "00", "65536", "http", "-1", "+80", "80 ", "080", "123456"}) + requireThrows( + [&] { + (void)validatedPort(bad, "WEBFRONT_PORT"); + }, + contains("WEBFRONT_PORT")); + }); + then("an invalid WEBFRONT_PORT makes the default configuration fail", [&] { + setPortVariable("http"); + requireThrows( + [&] { + (void)defaultPort(); + }, + contains("'http'")); + setPortVariable(""); + }); + }); + given("a server asked for port 00", [&] { + http::Server server("127.0.0.1", "00"); + then("it announces the port really bound", [&] { + require(server.port() != "00" && server.port() != "0"); + }); + }); + }}; const Scenario portOption{"The examples take --port", [] { - const PortVariableGuard portGuard; - given("--port and --port= among other arguments", [&] { - setPortVariable(""); - char program[] = "app", flag[] = "--port", value[] = "0", other[] = "project", joined[] = "--port=0"; - char* argv[] = {program, other, flag, value, joined, nullptr}; - int argc = 5; - then("they set the default port and leave the other arguments", [&] { - require(demo::applyPortOption(argc, argv)); - require(argc == 2 && std::string(argv[1]) == "project" && argv[2] == nullptr); - require(defaultPort() == "0"); - setPortVariable(""); - }); - }); - given("an invalid or missing value", [&] { - char program[] = "app", flag[] = "--port", bad[] = "65536"; - char* withBad[] = {program, flag, bad, nullptr}; - char* missing[] = {program, flag, nullptr}; - int badCount = 3, missingCount = 2; - then("the option is refused", [&] { - require(!demo::applyPortOption(badCount, withBad)); - require(!demo::applyPortOption(missingCount, missing)); - }); - }); -}}; + const PortVariableGuard portGuard; + given("--port and --port= among other arguments", [&] { + setPortVariable(""); + char program[] = "app", flag[] = "--port", value[] = "0", other[] = "project", joined[] = "--port=0"; + char* argv[] = {program, other, flag, value, joined, nullptr}; + int argc = 5; + then("they set the default port and leave the other arguments", [&] { + require(demo::applyPortOption(argc, argv)); + require(argc == 2 && std::string(argv[1]) == "project" && argv[2] == nullptr); + require(defaultPort() == "0"); + setPortVariable(""); + }); + }); + given("an invalid or missing value", [&] { + char program[] = "app", flag[] = "--port", bad[] = "65536"; + char* withBad[] = {program, flag, bad, nullptr}; + char* missing[] = {program, flag, nullptr}; + int badCount = 3, missingCount = 2; + then("the option is refused", [&] { + require(!demo::applyPortOption(badCount, withBad)); + require(!demo::applyPortOption(missingCount, missing)); + }); + }); + }}; const Scenario defaultPortFallback{"A configuration without a port falls back to a free port when its default is taken", [] { - const PortVariableGuard portGuard; - given("the preferred port held by another server", [&] { - setPortVariable(""); - http::Server holder("127.0.0.1", "0"); - const std::string taken{holder.port()}; - using Server = http::Server; - then("an empty port binds another port", [&] { - const auto server = detail::makeHttpServer(WebFrontConfig{}, taken); - require(server.port() != taken && server.port() != "0"); - }); - then("a chosen port in use is refused, not replaced", [&] { - requireThrows([&] { (void)detail::makeHttpServer(WebFrontConfig{.port = taken}, "0"); }, contains(taken)); - setPortVariable(taken.c_str()); - requireThrows([&] { (void)detail::makeHttpServer(WebFrontConfig{}, "0"); }, contains(taken)); - }); - }); -}}; + const PortVariableGuard portGuard; + given("the preferred port held by another server", [&] { + setPortVariable(""); + http::Server holder("127.0.0.1", "0"); + const std::string taken{holder.port()}; + using Server = http::Server; + then("an empty port binds another port", [&] { + const auto server = detail::makeHttpServer(WebFrontConfig{}, taken); + require(server.port() != taken && server.port() != "0"); + }); + then("a chosen port in use is refused, not replaced", [&] { + requireThrows( + [&] { + (void)detail::makeHttpServer(WebFrontConfig{.port = taken}, "0"); + }, + contains(taken)); + setPortVariable(taken.c_str()); + requireThrows( + [&] { + (void)detail::makeHttpServer(WebFrontConfig{}, "0"); + }, + contains(taken)); + }); + }); + }}; diff --git a/test/unit/StorageTests.cpp b/test/unit/StorageTests.cpp index 3dbf96fb..9b55ce33 100644 --- a/test/unit/StorageTests.cpp +++ b/test/unit/StorageTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -63,347 +63,371 @@ vector allNames(S& storage, string_view directory, size_t pageSize) { } // namespace const Scenario safePathRefuses{"SafePath refuses the names Windows reserves, on every platform", [] { - given("a reserved device name, whatever its case and extension, or a name Windows would alter", [&] { - then("safeRelativePath, safePathComponents and isSafeFileName reject it", [&] { - for (string name : {"con", "CON", "Con.txt", "nul", "nul.tar.gz", "aux", "prn", "com1", "COM9.log", - "lpt1", "LPT9", "com\xC2\xB9", "conin$", "CONOUT$", "con .txt", "a.", "a ", "dir/nul/x"}) { - auto scope = info(name); - requireThrows([&] { fs::safeRelativePath(name); }); - requireThrows([&] { fs::safePathComponents(name); }); - require(!fs::isSafeFileName(name)); - } - }); - }); - given("names that only resemble them", [&] { - then("they are accepted", [&] { - for (string name : {"console", "com10", "lpt0", "com", "nullable.txt", "a.b", "auxiliary", ".hidden"}) { - auto scope = info(name); - require(fs::isSafeFileName(name)); - require(fs::safePathComponents("dir/" + name) == vector{"dir", name}); - } - }); - }); - given("the empty path", [&] { - then("it names the root of a storage", [&] { - require(fs::safePathComponents("").empty()); - }); - }); -}}; + given("a reserved device name, whatever its case and extension, or a name Windows would alter", [&] { + then("safeRelativePath, safePathComponents and isSafeFileName reject it", [&] { + for (string name : {"con", + "CON", + "Con.txt", + "nul", + "nul.tar.gz", + "aux", + "prn", + "com1", + "COM9.log", + "lpt1", + "LPT9", + "com\xC2\xB9", + "conin$", + "CONOUT$", + "con .txt", + "a.", + "a ", + "dir/nul/x"}) { + auto scope = info(name); + requireThrows([&] { + fs::safeRelativePath(name); + }); + requireThrows([&] { + fs::safePathComponents(name); + }); + require(!fs::isSafeFileName(name)); + } + }); + }); + given("names that only resemble them", [&] { + then("they are accepted", [&] { + for (string name : {"console", "com10", "lpt0", "com", "nullable.txt", "a.b", "auxiliary", ".hidden"}) { + auto scope = info(name); + require(fs::isSafeFileName(name)); + require(fs::safePathComponents("dir/" + name) == vector{"dir", name}); + } + }); + }); + given("the empty path", [&] { + then("it names the root of a storage", [&] { + require(fs::safePathComponents("").empty()); + }); + }); + }}; const Scenario storageError{"A storage error is a bridge error with a storage code", [] { - const fs::StorageError error(fs::StorageErrc::rootMoved, "moved"); - const BridgeError& bridge = error; - require(bridge.code() == "storage.rootMoved"); - require(string(bridge.what()) == "moved"); - require(fs::storageErrorCode(fs::StorageErrc::confinementViolated) == "storage.confinementViolated"); - for (auto errc : {fs::StorageErrc::notFound, - fs::StorageErrc::alreadyExists, - fs::StorageErrc::notDirectory, - fs::StorageErrc::isDirectory, - fs::StorageErrc::notEmpty, - fs::StorageErrc::accessDenied, - fs::StorageErrc::invalidPath, - fs::StorageErrc::linkRefused, - fs::StorageErrc::unsafeDirectory, - fs::StorageErrc::rootMoved, - fs::StorageErrc::confinementViolated, - fs::StorageErrc::busy, - fs::StorageErrc::ioError}) - require(BridgeError::isValidCode(fs::storageErrorCode(errc))); -}}; + const fs::StorageError error(fs::StorageErrc::rootMoved, "moved"); + const BridgeError& bridge = error; + require(bridge.code() == "storage.rootMoved"); + require(string(bridge.what()) == "moved"); + require(fs::storageErrorCode(fs::StorageErrc::confinementViolated) == "storage.confinementViolated"); + for (auto errc : {fs::StorageErrc::notFound, + fs::StorageErrc::alreadyExists, + fs::StorageErrc::notDirectory, + fs::StorageErrc::isDirectory, + fs::StorageErrc::notEmpty, + fs::StorageErrc::accessDenied, + fs::StorageErrc::invalidPath, + fs::StorageErrc::linkRefused, + fs::StorageErrc::unsafeDirectory, + fs::StorageErrc::rootMoved, + fs::StorageErrc::confinementViolated, + fs::StorageErrc::busy, + fs::StorageErrc::ioError}) + require(BridgeError::isValidCode(fs::storageErrorCode(errc))); + }}; const Scenario fileReads{"A file reads its bytes through a provider's byte source", [] { - struct Source : fs::ByteSource { - string bytes{"0123456789"}; - size_t position{}; - size_t read(span buffer) override { - const auto count = min(buffer.size(), bytes.size() - position); - copy_n(bytes.data() + position, count, buffer.data()); - position += count; - return count; - } - [[nodiscard]] optional size() const override { - return bytes.size(); - } - [[nodiscard]] bool seek(uint64_t offset) override { - position = static_cast(min(offset, bytes.size())); - return true; - } - }; - fs::File file{make_unique()}; - require(file.knownSize() == 10u); - require(readAll(std::move(file)) == "0123456789"); + struct Source : fs::ByteSource { + string bytes{"0123456789"}; + size_t position{}; + size_t read(span buffer) override { + const auto count = min(buffer.size(), bytes.size() - position); + copy_n(bytes.data() + position, count, buffer.data()); + position += count; + return count; + } + [[nodiscard]] optional size() const override { + return bytes.size(); + } + [[nodiscard]] bool seek(uint64_t offset) override { + position = static_cast(min(offset, bytes.size())); + return true; + } + }; + fs::File file{make_unique()}; + require(file.knownSize() == 10u); + require(readAll(std::move(file)) == "0123456789"); - fs::File again{make_unique()}; - require(again.seek(7)); - array buffer{}; - require(again.read(buffer) == 3); - require(again.eof()); - require(again.seek(2)); - require(!again.eof()); - requireThrows([&] { fs::File{unique_ptr{}}; }); -}}; + fs::File again{make_unique()}; + require(again.seek(7)); + array buffer{}; + require(again.read(buffer) == 3); + require(again.eof()); + require(again.seek(2)); + require(!again.eof()); + requireThrows([&] { + fs::File{unique_ptr{}}; + }); + }}; const Scenario simulatedStorage{"The simulated storage follows the storage contract", [] { - fs::MemoryStorage storage; + fs::MemoryStorage storage; - given("files and directories created through it", [&] { - storage.createDirectory("docs"); - writeFile(storage, "docs/a.txt", "alpha"); - writeFile(storage, "b.txt", "beta"); + given("files and directories created through it", [&] { + storage.createDirectory("docs"); + writeFile(storage, "docs/a.txt", "alpha"); + writeFile(storage, "b.txt", "beta"); - then("they are listed, inspected and read", [&] { - auto page = storage.list("", {}, 10); - require(page.entries.size() == 2); - require(page.entries[0].name == "b.txt"); - require(page.entries[0].type == fs::EntryType::file); - require(page.entries[0].size == 4); - require(page.entries[1].name == "docs"); - require(page.entries[1].type == fs::EntryType::directory); - require(!page.next); - require(storage.status("docs/a.txt").size == 5); - require(storage.status("").type == fs::EntryType::directory); - require(readAll(storage.openRead("docs/a.txt")) == "alpha"); - }); - then("a write creating a name that exists is refused, a replacing one replaces it", [&] { - require(errorOf([&] { - writeFile(storage, "b.txt", "other"); - }) - == fs::StorageErrc::alreadyExists); - writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); - require(readAll(storage.openRead("b.txt")) == "gamma"); - require(errorOf([&] { - writeFile(storage, "docs", "x", fs::WriteMode::replace); - }) - == fs::StorageErrc::isDirectory); - }); - then("an opened file keeps its bytes when the file is replaced", [&] { - auto file = storage.openRead("b.txt"); - writeFile(storage, "b.txt", "replaced", fs::WriteMode::replace); - require(readAll(std::move(file)) == "beta"); - }); - then("removing and renaming follow the contract", [&] { - require(errorOf([&] { - storage.remove("docs"); - }) - == fs::StorageErrc::notEmpty); - require(errorOf([&] { - storage.rename("docs", "docs/inner"); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.rename("b.txt", "docs/a.txt"); - }) - == fs::StorageErrc::alreadyExists); - storage.rename("b.txt", "docs/b.txt"); - require(errorOf([&] { - storage.status("b.txt"); - }) - == fs::StorageErrc::notFound); - storage.remove("docs/a.txt"); - storage.remove("docs/b.txt"); - storage.remove("docs"); - require(storage.list("").entries.empty()); - }); - then("operations through a file or a missing directory fail with their reason", [&] { - require(errorOf([&] { - storage.list("b.txt"); - }) - == fs::StorageErrc::notDirectory); - require(errorOf([&] { - storage.openRead("missing/x"); - }) - == fs::StorageErrc::notFound); - require(errorOf([&] { - storage.openRead("docs"); - }) - == fs::StorageErrc::isDirectory); - require(errorOf([&] { - storage.createDirectory("docs"); - }) - == fs::StorageErrc::alreadyExists); - }); - }); + then("they are listed, inspected and read", [&] { + auto page = storage.list("", {}, 10); + require(page.entries.size() == 2); + require(page.entries[0].name == "b.txt"); + require(page.entries[0].type == fs::EntryType::file); + require(page.entries[0].size == 4); + require(page.entries[1].name == "docs"); + require(page.entries[1].type == fs::EntryType::directory); + require(!page.next); + require(storage.status("docs/a.txt").size == 5); + require(storage.status("").type == fs::EntryType::directory); + require(readAll(storage.openRead("docs/a.txt")) == "alpha"); + }); + then("a write creating a name that exists is refused, a replacing one replaces it", [&] { + require(errorOf([&] { + writeFile(storage, "b.txt", "other"); + }) + == fs::StorageErrc::alreadyExists); + writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); + require(readAll(storage.openRead("b.txt")) == "gamma"); + require(errorOf([&] { + writeFile(storage, "docs", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::isDirectory); + }); + then("an opened file keeps its bytes when the file is replaced", [&] { + auto file = storage.openRead("b.txt"); + writeFile(storage, "b.txt", "replaced", fs::WriteMode::replace); + require(readAll(std::move(file)) == "beta"); + }); + then("removing and renaming follow the contract", [&] { + require(errorOf([&] { + storage.remove("docs"); + }) + == fs::StorageErrc::notEmpty); + require(errorOf([&] { + storage.rename("docs", "docs/inner"); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.rename("b.txt", "docs/a.txt"); + }) + == fs::StorageErrc::alreadyExists); + storage.rename("b.txt", "docs/b.txt"); + require(errorOf([&] { + storage.status("b.txt"); + }) + == fs::StorageErrc::notFound); + storage.remove("docs/a.txt"); + storage.remove("docs/b.txt"); + storage.remove("docs"); + require(storage.list("").entries.empty()); + }); + then("operations through a file or a missing directory fail with their reason", [&] { + require(errorOf([&] { + storage.list("b.txt"); + }) + == fs::StorageErrc::notDirectory); + require(errorOf([&] { + storage.openRead("missing/x"); + }) + == fs::StorageErrc::notFound); + require(errorOf([&] { + storage.openRead("docs"); + }) + == fs::StorageErrc::isDirectory); + require(errorOf([&] { + storage.createDirectory("docs"); + }) + == fs::StorageErrc::alreadyExists); + }); + }); - given("a write in progress", [&] { - auto writer = make_unique(storage.beginWrite("draft.txt", fs::WriteMode::createNew)); - writer->write(span("partial", 7)); - then("nothing is visible before the commit", [&] { - require(errorOf([&] { - storage.status("draft.txt"); - }) - == fs::StorageErrc::notFound); - }); - when("the writer is destroyed without committing, as an interrupted write", [&] { - writer.reset(); - then("no partial file exists", [&] { - require(storage.list("").entries.empty()); - }); - }); - when("it commits", [&] { - writer->commit(); - then("the whole file appears at once", [&] { - require(readAll(storage.openRead("draft.txt")) == "partial"); - requireThrows([&] { writer->commit(); }); - }); - }); - }); + given("a write in progress", [&] { + auto writer = make_unique(storage.beginWrite("draft.txt", fs::WriteMode::createNew)); + writer->write(span("partial", 7)); + then("nothing is visible before the commit", [&] { + require(errorOf([&] { + storage.status("draft.txt"); + }) + == fs::StorageErrc::notFound); + }); + when("the writer is destroyed without committing, as an interrupted write", [&] { + writer.reset(); + then("no partial file exists", [&] { + require(storage.list("").entries.empty()); + }); + }); + when("it commits", [&] { + writer->commit(); + then("the whole file appears at once", [&] { + require(readAll(storage.openRead("draft.txt")) == "partial"); + requireThrows([&] { + writer->commit(); + }); + }); + }); + }); - given("rights refused by the simulated system", [&] { - storage.createDirectory("locked"); - writeFile(storage, "locked/secret.txt", "s"); - writeFile(storage, "readonly.txt", "r"); - storage.setAccess("locked", false, false); - storage.setAccess("readonly.txt", true, false); - then("operations needing them fail with accessDenied", [&] { - require(errorOf([&] { - storage.list("locked"); - }) - == fs::StorageErrc::accessDenied); - require(errorOf([&] { - storage.openRead("locked/secret.txt"); - }) - == fs::StorageErrc::accessDenied); - require(errorOf([&] { - writeFile(storage, "locked/new.txt", "n"); - }) - == fs::StorageErrc::accessDenied); - require(errorOf([&] { - writeFile(storage, "readonly.txt", "w", fs::WriteMode::replace); - }) - == fs::StorageErrc::accessDenied); - require(readAll(storage.openRead("readonly.txt")) == "r"); - auto info = storage.status("readonly.txt"); - require(info.readable); - require(!info.writable); - }); - }); + given("rights refused by the simulated system", [&] { + storage.createDirectory("locked"); + writeFile(storage, "locked/secret.txt", "s"); + writeFile(storage, "readonly.txt", "r"); + storage.setAccess("locked", false, false); + storage.setAccess("readonly.txt", true, false); + then("operations needing them fail with accessDenied", [&] { + require(errorOf([&] { + storage.list("locked"); + }) + == fs::StorageErrc::accessDenied); + require(errorOf([&] { + storage.openRead("locked/secret.txt"); + }) + == fs::StorageErrc::accessDenied); + require(errorOf([&] { + writeFile(storage, "locked/new.txt", "n"); + }) + == fs::StorageErrc::accessDenied); + require(errorOf([&] { + writeFile(storage, "readonly.txt", "w", fs::WriteMode::replace); + }) + == fs::StorageErrc::accessDenied); + require(readAll(storage.openRead("readonly.txt")) == "r"); + auto info = storage.status("readonly.txt"); + require(info.readable); + require(!info.writable); + }); + }); - given("paths that leave the root or that SafePath rejects", [&] { - then("every operation refuses them with invalidPath", [&] { - for (string path : {"../x", "/etc/passwd", "a/../b", "a//b", "C:/x", "a\\b", "nul.txt", "a/./b", ".."}) { - auto scope = info(path); - require(errorOf([&] { - storage.status(path); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.list(path); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.openRead(path); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - (void)storage.beginWrite(path, fs::WriteMode::replace); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.createDirectory(path); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.remove(path); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.rename("x", path); - }) - == fs::StorageErrc::invalidPath); - } - }); - }); - given("names starting with the prefix reserved to temporary files", [&] { - then("they are refused, so that a listing never hides a committed file", [&] { - require(errorOf([&] { - writeFile(storage, ".wf-tmp-report.txt", "report"); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.createDirectory("dir/.wf-tmp-x"); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.status(".wf-tmp-report.txt"); - }) - == fs::StorageErrc::invalidPath); - require(fs::isSafeFileName(".wf-tmp-report.txt")); // SafePath alone accepts it: the reservation is the storage's - for (auto name : {".WF-TMP-report.txt", ".Wf-Tmp-x", ".wF-tMp-"}) - require(errorOf([&] { - storage.status(name); - }) - == fs::StorageErrc::invalidPath); - require(fs::isTemporaryName(".WF-tmp-a")); - require(!fs::isTemporaryName(".wf-tmp")); - require(!fs::isTemporaryName("x.wf-tmp-a")); - }); - }); - given("operations that need an entry", [&] { - then("the root is refused", [&] { - require(errorOf([&] { - storage.remove(""); - }) - == fs::StorageErrc::invalidPath); - require(errorOf([&] { - storage.openRead(""); - }) - == fs::StorageErrc::invalidPath); - }); - }); -}}; + given("paths that leave the root or that SafePath rejects", [&] { + then("every operation refuses them with invalidPath", [&] { + for (string path : {"../x", "/etc/passwd", "a/../b", "a//b", "C:/x", "a\\b", "nul.txt", "a/./b", ".."}) { + auto scope = info(path); + require(errorOf([&] { + storage.status(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.list(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.openRead(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + (void)storage.beginWrite(path, fs::WriteMode::replace); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.createDirectory(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.remove(path); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.rename("x", path); + }) + == fs::StorageErrc::invalidPath); + } + }); + }); + given("names starting with the prefix reserved to temporary files", [&] { + then("they are refused, so that a listing never hides a committed file", [&] { + require(errorOf([&] { + writeFile(storage, ".wf-tmp-report.txt", "report"); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.createDirectory("dir/.wf-tmp-x"); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.status(".wf-tmp-report.txt"); + }) + == fs::StorageErrc::invalidPath); + require(fs::isSafeFileName(".wf-tmp-report.txt")); // SafePath alone accepts it: the reservation is the storage's + for (auto name : {".WF-TMP-report.txt", ".Wf-Tmp-x", ".wF-tMp-"}) + require(errorOf([&] { + storage.status(name); + }) + == fs::StorageErrc::invalidPath); + require(fs::isTemporaryName(".WF-tmp-a")); + require(!fs::isTemporaryName(".wf-tmp")); + require(!fs::isTemporaryName("x.wf-tmp-a")); + }); + }); + given("operations that need an entry", [&] { + then("the root is refused", [&] { + require(errorOf([&] { + storage.remove(""); + }) + == fs::StorageErrc::invalidPath); + require(errorOf([&] { + storage.openRead(""); + }) + == fs::StorageErrc::invalidPath); + }); + }); + }}; const Scenario listingPages{"Listing pages are stable while the directory changes", [] { - fs::MemoryStorage storage; - for (int index = 10; index < 40; ++index) - writeFile(storage, "f" + to_string(index), "x"); + fs::MemoryStorage storage; + for (int index = 10; index < 40; ++index) + writeFile(storage, "f" + to_string(index), "x"); - given("a listing read page by page", [&] { - auto first = storage.list("", {}, 10); - require(first.entries.size() == 10); - require(first.entries.front().name == "f10"); - require(first.next == "f19"); + given("a listing read page by page", [&] { + auto first = storage.list("", {}, 10); + require(first.entries.size() == 10); + require(first.entries.front().name == "f10"); + require(first.next == "f19"); - when("entries are added before and after the cursor and removed after it", [&] { - writeFile(storage, "f05", "x"); - writeFile(storage, "f195", "x"); - writeFile(storage, "f99", "x"); - storage.remove("f30"); - set seen; - for (auto& entry : first.entries) - seen.insert(entry.name); - string after = *first.next; - while (true) { - auto page = storage.list("", after, 10); - for (auto& entry : page.entries) - require(seen.insert(entry.name).second); - if (!page.next) - break; - after = *page.next; - } - then("every entry present during the whole listing appears exactly once", [&] { - for (int index = 10; index < 40; ++index) - if (index != 30) - require(seen.contains("f" + to_string(index))); - require(seen.contains("f195")); - require(seen.contains("f99")); - require(!seen.contains("f05")); - }); - }); - }); - given("a page size out of bounds", [&] { - then("it is brought back into [1, maxStoragePageSize]", [&] { - require(storage.list("", {}, 0).entries.size() == 1); - require(storage.list("", {}, 1'000'000).entries.size() == 30); - require(allNames(storage, "", 7).size() == 30); - }); - }); - given("an invalid cursor", [&] { - then("the listing is refused", [&] { - require(errorOf([&] { - storage.list("", "../f10"); - }) - == fs::StorageErrc::invalidPath); - }); - }); -}}; + when("entries are added before and after the cursor and removed after it", [&] { + writeFile(storage, "f05", "x"); + writeFile(storage, "f195", "x"); + writeFile(storage, "f99", "x"); + storage.remove("f30"); + set seen; + for (auto& entry : first.entries) + seen.insert(entry.name); + string after = *first.next; + while (true) { + auto page = storage.list("", after, 10); + for (auto& entry : page.entries) + require(seen.insert(entry.name).second); + if (!page.next) + break; + after = *page.next; + } + then("every entry present during the whole listing appears exactly once", [&] { + for (int index = 10; index < 40; ++index) + if (index != 30) + require(seen.contains("f" + to_string(index))); + require(seen.contains("f195")); + require(seen.contains("f99")); + require(!seen.contains("f05")); + }); + }); + }); + given("a page size out of bounds", [&] { + then("it is brought back into [1, maxStoragePageSize]", [&] { + require(storage.list("", {}, 0).entries.size() == 1); + require(storage.list("", {}, 1'000'000).entries.size() == 30); + require(allNames(storage, "", 7).size() == 30); + }); + }); + given("an invalid cursor", [&] { + then("the listing is refused", [&] { + require(errorOf([&] { + storage.list("", "../f10"); + }) + == fs::StorageErrc::invalidPath); + }); + }); + }}; diff --git a/test/unit/StructuredShutdownTests.cpp b/test/unit/StructuredShutdownTests.cpp index 6ab01739..d792d7cf 100644 --- a/test/unit/StructuredShutdownTests.cpp +++ b/test/unit/StructuredShutdownTests.cpp @@ -1,8 +1,8 @@ #include "InlineTaskScope.hpp" -#include #include #include #include +#include #include #include @@ -67,7 +67,7 @@ struct ShutdownSocket : webfront::networking::SocketMock { ShutdownSocket() : trace(ShutdownContext::current->trace) { ++trace->liveSockets; } - ShutdownSocket(ShutdownSocket&& other) noexcept : trace(std::move(other.trace)) { } + ShutdownSocket(ShutdownSocket&& other) noexcept : trace(std::move(other.trace)) {} ~ShutdownSocket() { if (trace) --trace->liveSockets; @@ -98,7 +98,7 @@ struct ShutdownSender { Receiver receiver; bool produce; std::optional> callback; - Operation(Receiver value, bool emit) : receiver(std::move(value)), produce(emit) { } + Operation(Receiver value, bool emit) : receiver(std::move(value)), produce(emit) {} void start() noexcept { if (produce) { ex::set_value(std::move(receiver), T{}); @@ -115,8 +115,8 @@ struct ShutdownSender { struct ShutdownAcceptor : webfront::networking::SocketBaseMock { bool accepted = false; - explicit ShutdownAcceptor(ShutdownContext&) { } - void open(auto) { } + explicit ShutdownAcceptor(ShutdownContext&) {} + void open(auto) {} bool is_open() const { return true; } @@ -139,27 +139,27 @@ struct ShutdownNet : webfront::networking::NetworkingMock { } // namespace const Scenario serverDrain{"Server drain joins its pending connection without draining unrelated work", [] { - std::shared_ptr trace; - given("a server with an accepted socket and a pending read", [&] { - { - webfront::http::Server server("127.0.0.1", "0"); - trace = ShutdownContext::current->trace; - require(trace->liveSockets == 1); - when("shutdown cancellation is queued on the context", [&] { - server.drain(); - then("the connection is destroyed before drain returns", [&] { - check(trace->liveSockets == 0); - }); - andThen("join does not require unrelated context work to finish", [&] { - check(trace->foreignCompletions == 0); - }); - }); - } - then("no connection outlives the server", [&] { - check(trace->liveSockets == 0); - }); - }); -}}; + std::shared_ptr trace; + given("a server with an accepted socket and a pending read", [&] { + { + webfront::http::Server server("127.0.0.1", "0"); + trace = ShutdownContext::current->trace; + require(trace->liveSockets == 1); + when("shutdown cancellation is queued on the context", [&] { + server.drain(); + then("the connection is destroyed before drain returns", [&] { + check(trace->liveSockets == 0); + }); + andThen("join does not require unrelated context work to finish", [&] { + check(trace->foreignCompletions == 0); + }); + }); + } + then("no connection outlives the server", [&] { + check(trace->liveSockets == 0); + }); + }); + }}; namespace { webfront::networking::Task failingTask(int failure) { @@ -171,28 +171,28 @@ webfront::networking::Task failingTask(int failure) { } } // namespace const Scenario trackedTask{"Tracked task errors are logged and do not prevent joining", [] { - namespace log = webfront::log; - std::vector lines; - log::setLogLevel(log::Error); - auto handle = log::addSinks([&](std::string_view text) { - lines.emplace_back(text); - }); - given("tasks that fail with standard and nonstandard exceptions", [&] { - webfront::testing::InlineTaskScope scope; - when("they are spawned into a scope", [&] { - webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(0)); - webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(1)); - webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(2)); - log::removeSinks(handle); - then("both errors are logged and the scope can be drained", [&] { - check(lines.size() == 2); - check(std::ranges::any_of(lines, [](const auto& line) { - return line.ends_with("Network task failed: tracked failure"); - })); - check(std::ranges::any_of(lines, [](const auto& line) { - return line.ends_with("Network task failed"); - })); - }); - }); - }); -}}; + namespace log = webfront::log; + std::vector lines; + log::setLogLevel(log::Error); + auto handle = log::addSinks([&](std::string_view text) { + lines.emplace_back(text); + }); + given("tasks that fail with standard and nonstandard exceptions", [&] { + webfront::testing::InlineTaskScope scope; + when("they are spawned into a scope", [&] { + webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(0)); + webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(1)); + webfront::networking::Spawn(scope, ex::inline_scheduler{}, failingTask(2)); + log::removeSinks(handle); + then("both errors are logged and the scope can be drained", [&] { + check(lines.size() == 2); + check(std::ranges::any_of(lines, [](const auto& line) { + return line.ends_with("Network task failed: tracked failure"); + })); + check(std::ranges::any_of(lines, [](const auto& line) { + return line.ends_with("Network task failed"); + })); + }); + }); + }); + }}; diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index d53e8a1f..c4c03446 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -1,6 +1,6 @@ -#include #include "TemporaryDirectory.hpp" #include +#include #include #include @@ -121,7 +121,7 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast }); }); then("a missing signature_algorithms extension elicits missing_extension", [] { - auto hello = traceHello(); + auto hello = traceHello(); const auto extension = std::ranges::search(hello, tlsHex("000d0020001e")); require(!extension.empty()); *extension.begin() = 0xfe; // Unknown extension of the same length. @@ -142,15 +142,23 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast tls::append(hello, tlsHex("002a00000029002c000700010100000000002120")); hello.resize(hello.size() + 32); const auto lengths = [&] { - hello[3] = static_cast(hello.size() - 4); + hello[3] = static_cast(hello.size() - 4); hello[50] = static_cast(hello.size() - 51); }; lengths(); - requireThrows([&] { tls::parseHello(hello, false); }, contains("missing psk_key_exchange_modes")); + requireThrows( + [&] { + tls::parseHello(hello, false); + }, + contains("missing psk_key_exchange_modes")); hello.insert(hello.begin() + 51, modes.begin(), modes.end()); lengths(); require(tls::parseHello(hello, false).earlyData); - requireThrows([&] { tls::parseHello(hello, true); }, contains("unexpected early_data")); + requireThrows( + [&] { + tls::parseHello(hello, true); + }, + contains("unexpected early_data")); }); then("oversized records and corrupted authentication tags are refused", [] { requireThrows([] { @@ -191,8 +199,16 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast require(payload.size() == tls::maxPlaintext); require(open(10, 200, payload) == tls::applicationData); require(payload.size() == 10); - requireThrows([&] { open(tls::maxPlaintext + 1, 0, payload); }, contains("oversized inner plaintext")); - requireThrows([&] { open(tls::maxPlaintext + 1, 1, payload); }, contains("oversized inner plaintext")); + requireThrows( + [&] { + open(tls::maxPlaintext + 1, 0, payload); + }, + contains("oversized inner plaintext")); + requireThrows( + [&] { + open(tls::maxPlaintext + 1, 1, payload); + }, + contains("oversized inner plaintext")); }); then("an exhausted record sequence fails as a transport error before wrapping", [] { require(tls::recordNonce({}, UINT64_MAX - 1).back() == 0xfe); @@ -374,10 +390,10 @@ const Scenario tlsCredentials("TLS loads matching PEM formats and preserves the tls::Reader input{leaf}; tls::Reader outer{input.der(0x30)}; outer.der(0x30); - const auto size = leaf.size() - outer.remaining.size(); + const auto size = leaf.size() - outer.remaining.size(); leaf.resize(size); - leaf[2] = static_cast((size - 4) >> 8); - leaf[3] = static_cast(size - 4); + leaf[2] = static_cast((size - 4) >> 8); + leaf[3] = static_cast(size - 4); const auto unsignedLeaf = temporary.path() / "unsigned.pem"; writePem(unsignedLeaf, "CERTIFICATE", std::move(leaf)); requireThrows([&] { diff --git a/test/unit/TypeErasedFunctionTests.cpp b/test/unit/TypeErasedFunctionTests.cpp index 237d69b3..f3754caa 100644 --- a/test/unit/TypeErasedFunctionTests.cpp +++ b/test/unit/TypeErasedFunctionTests.cpp @@ -1,20 +1,18 @@ -#include - #include +#include +#include #include #include -#include - using namespace webfront::bdd; using namespace std; using namespace webfront; -size_t testCounter {}; -std::string testString {}; +size_t testCounter{}; +std::string testString{}; void function4(const char* text, int plusValue, int minusValue) { testString.append(text); @@ -23,63 +21,63 @@ void function4(const char* text, int plusValue, int minusValue) { } const Scenario typeErasedFunctions{"TypeErasedFunctions", [] { - given("Different free functions, member functions and lambdas", [&] { - - auto function1 = [&](int value) { - testCounter += static_cast(value); - }; - - auto function2 = [&](int value, std::string text) { - testString += text; - function1(value); - }; - - class Test { - public: - Test(size_t& testC, std::string& testS) : tC(testC), tS(testS) {} - void function3(int value, std::string_view text) { - tC += static_cast(value); - tS += text; - } - private: - size_t& tC; - std::string& tS; - }; - - - when("Stored in a map", [&] { - std::map functions; - - functions.try_emplace("function1", function1); - functions.try_emplace("function2", function2); - - Test test(testCounter, testString); - functions.try_emplace("function3", [&](int value, std::string_view text){ - test.function3(value, text); - }); - - functions.try_emplace("function4", function4); - - then("They can be retrieved uniformly", [&] { - functions.at("function1")(5); - require(testCounter == 5); - - functions.at("function2")(8, std::string("Sponge")); - require(testCounter == 13); - require(testString == "Sponge"); - - requireThrows([&] { functions.at("function2")(8, "Bob"); }); - - functions.at("function3")(3, std::string_view("Bob")); - require(testCounter == 16); - require(testString == "SpongeBob"); - - functions.at("function4")(reinterpret_cast(" Square"), 100, 33); - require(testCounter == 83); - require(testString == "SpongeBob Square"); - - - }); - }); - }); -}}; \ No newline at end of file + given("Different free functions, member functions and lambdas", [&] { + auto function1 = [&](int value) { + testCounter += static_cast(value); + }; + + auto function2 = [&](int value, std::string text) { + testString += text; + function1(value); + }; + + class Test { + public: + Test(size_t& testC, std::string& testS) : tC(testC), tS(testS) {} + void function3(int value, std::string_view text) { + tC += static_cast(value); + tS += text; + } + + private: + size_t& tC; + std::string& tS; + }; + + + when("Stored in a map", [&] { + std::map functions; + + functions.try_emplace("function1", function1); + functions.try_emplace("function2", function2); + + Test test(testCounter, testString); + functions.try_emplace("function3", [&](int value, std::string_view text) { + test.function3(value, text); + }); + + functions.try_emplace("function4", function4); + + then("They can be retrieved uniformly", [&] { + functions.at("function1")(5); + require(testCounter == 5); + + functions.at("function2")(8, std::string("Sponge")); + require(testCounter == 13); + require(testString == "Sponge"); + + requireThrows([&] { + functions.at("function2")(8, "Bob"); + }); + + functions.at("function3")(3, std::string_view("Bob")); + require(testCounter == 16); + require(testString == "SpongeBob"); + + functions.at("function4")(reinterpret_cast(" Square"), 100, 33); + require(testCounter == 83); + require(testString == "SpongeBob Square"); + }); + }); + }); + }}; \ No newline at end of file diff --git a/test/unit/UIExecutorTests.cpp b/test/unit/UIExecutorTests.cpp index 8c5370b1..09525f68 100644 --- a/test/unit/UIExecutorTests.cpp +++ b/test/unit/UIExecutorTests.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -53,8 +53,7 @@ struct Receiver { std::rethrow_exception(e); } catch (const UIExecutorUnavailable&) { observed.unavailable = true; - } catch (...) { - } + } catch (...) {} observed.done(); } }; @@ -121,7 +120,7 @@ template struct Connected { using Op = decltype(ex::connect(std::declval(), std::declval())); Op op; - Connected(Sender sender, Receiver receiver) : op(ex::connect(std::move(sender), std::move(receiver))) { } + Connected(Sender sender, Receiver receiver) : op(ex::connect(std::move(sender), std::move(receiver))) {} void start() noexcept { ex::start(op); } @@ -130,221 +129,231 @@ struct Connected { } // namespace const Scenario interfaceThread{"The interface thread runs scheduled operations", [] { - given("a frontend loop attached to an executor", [&] { - FakeLoop loop; - loop.start(); - auto executor = loop.host.executor(); - require(executor.available()); - check(!executor.onUIThread()); - when("an operation is scheduled from another thread", [&] { - Observed observed; - ex::inplace_stop_source stop; - auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("it completes on the interface thread", [&] { - requireEventually([&] { return observed.completions == 1; }); - check(observed.valueThread == loop.uiThread); - check(!observed.stopped); - check(!observed.errored); - }); - }); - when("operations are scheduled by many threads", [&] { - static constexpr int threads = 4; - static constexpr int each = 50; - Observed observed; - std::mutex keep; - std::vector> workers; - ex::inplace_stop_source stop; - std::vector>> operations; - for (int t = 0; t < threads; ++t) - workers.push_back(std::make_unique([&] { - for (int i = 0; i < each; ++i) { - auto op = std::make_shared>(executor.schedule(), Receiver{observed, stop.get_token()}); - { - std::lock_guard lock(keep); - operations.push_back(op); - } - op->start(); - } - })); - for (auto& worker : workers) - worker->join(); - then("each one completes exactly once", [&] { - requireEventually([&] { return observed.completions == threads * each; }); - check(!observed.stopped); - }); - }); - }); -}}; + given("a frontend loop attached to an executor", [&] { + FakeLoop loop; + loop.start(); + auto executor = loop.host.executor(); + require(executor.available()); + check(!executor.onUIThread()); + when("an operation is scheduled from another thread", [&] { + Observed observed; + ex::inplace_stop_source stop; + auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("it completes on the interface thread", [&] { + requireEventually([&] { + return observed.completions == 1; + }); + check(observed.valueThread == loop.uiThread); + check(!observed.stopped); + check(!observed.errored); + }); + }); + when("operations are scheduled by many threads", [&] { + static constexpr int threads = 4; + static constexpr int each = 50; + Observed observed; + std::mutex keep; + std::vector> workers; + ex::inplace_stop_source stop; + std::vector>> operations; + for (int t = 0; t < threads; ++t) + workers.push_back(std::make_unique([&] { + for (int i = 0; i < each; ++i) { + auto op = std::make_shared>( + executor.schedule(), + Receiver{observed, stop.get_token()}); + { + std::lock_guard lock(keep); + operations.push_back(op); + } + op->start(); + } + })); + for (auto& worker : workers) + worker->join(); + then("each one completes exactly once", [&] { + requireEventually([&] { + return observed.completions == threads * each; + }); + check(!observed.stopped); + }); + }); + }); + }}; const Scenario operationStopped{"An operation is stopped by its token before it runs", [] { - given("an attached loop that is not draining", [&] { - UIExecutorHost host; - host.attach([] { }); - auto executor = host.executor(); - Observed observed; - ex::inplace_stop_source stop; - auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - require(observed.completions == 0); - when("the stop is requested", [&] { - stop.request_stop(); - then("it completes stopped and never runs", [&] { - check(observed.completions == 1); - check(observed.stopped); - host.drain(); - check(observed.completions == 1); - }); - }); - host.close(); - }); - given("a token already stopped", [&] { - UIExecutorHost host; - host.attach([] { }); - Observed observed; - ex::inplace_stop_source stop; - stop.request_stop(); - auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("it completes stopped without queuing", [&] { - check(observed.stopped); - check(observed.completions == 1); - host.drain(); - check(observed.completions == 1); - }); - host.close(); - }); -}}; + given("an attached loop that is not draining", [&] { + UIExecutorHost host; + host.attach([] {}); + auto executor = host.executor(); + Observed observed; + ex::inplace_stop_source stop; + auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + require(observed.completions == 0); + when("the stop is requested", [&] { + stop.request_stop(); + then("it completes stopped and never runs", [&] { + check(observed.completions == 1); + check(observed.stopped); + host.drain(); + check(observed.completions == 1); + }); + }); + host.close(); + }); + given("a token already stopped", [&] { + UIExecutorHost host; + host.attach([] {}); + Observed observed; + ex::inplace_stop_source stop; + stop.request_stop(); + auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("it completes stopped without queuing", [&] { + check(observed.stopped); + check(observed.completions == 1); + host.drain(); + check(observed.completions == 1); + }); + host.close(); + }); + }}; const Scenario closingLoop{"Closing the loop abandons pending operations", [] { - given("an operation pending in a loop that does not drain", [&] { - UIExecutorHost host; - host.attach([] { }); - auto executor = host.executor(); - Observed observed; - ex::inplace_stop_source stop; - auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - require(observed.completions == 0); - when("the loop closes", [&] { - host.close(); - then("the operation completes stopped, once", [&] { - check(observed.completions == 1); - check(observed.stopped); - check(!executor.available()); - host.close(); // idempotent - check(observed.completions == 1); - }); - }); - }); -}}; + given("an operation pending in a loop that does not drain", [&] { + UIExecutorHost host; + host.attach([] {}); + auto executor = host.executor(); + Observed observed; + ex::inplace_stop_source stop; + auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + require(observed.completions == 0); + when("the loop closes", [&] { + host.close(); + then("the operation completes stopped, once", [&] { + check(observed.completions == 1); + check(observed.stopped); + check(!executor.available()); + host.close(); // idempotent + check(observed.completions == 1); + }); + }); + }); + }}; const Scenario executorWithout{"An executor without a running loop is unavailable", [] { - Observed observed; - ex::inplace_stop_source stop; - given("a default handle", [&] { - UIExecutor executor; - check(!executor.available()); - auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("the operation fails as unavailable", [&] { - check(observed.unavailable); - check(observed.completions == 1); - }); - }); - given("a host not attached yet", [&] { - UIExecutorHost host; - check(!host.executor().available()); - auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("the operation fails as unavailable", [&] { - check(observed.unavailable); - }); - }); - given("a host closed", [&] { - UIExecutorHost host; - host.attach([] { }); - host.close(); - auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("the operation fails as unavailable, after closure", [&] { - check(observed.unavailable); - check(observed.completions == 1); - }); - }); - given("an executor whose host is destroyed", [&] { - UIExecutor executor; - { - UIExecutorHost host; - host.attach([] { }); - executor = host.executor(); - } - check(!executor.available()); - auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("the operation fails as unavailable", [&] { - check(observed.unavailable); - }); - }); -}}; + Observed observed; + ex::inplace_stop_source stop; + given("a default handle", [&] { + UIExecutor executor; + check(!executor.available()); + auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("the operation fails as unavailable", [&] { + check(observed.unavailable); + check(observed.completions == 1); + }); + }); + given("a host not attached yet", [&] { + UIExecutorHost host; + check(!host.executor().available()); + auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("the operation fails as unavailable", [&] { + check(observed.unavailable); + }); + }); + given("a host closed", [&] { + UIExecutorHost host; + host.attach([] {}); + host.close(); + auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("the operation fails as unavailable, after closure", [&] { + check(observed.unavailable); + check(observed.completions == 1); + }); + }); + given("an executor whose host is destroyed", [&] { + UIExecutor executor; + { + UIExecutorHost host; + host.attach([] {}); + executor = host.executor(); + } + check(!executor.available()); + auto op = ex::connect(executor.schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("the operation fails as unavailable", [&] { + check(observed.unavailable); + }); + }); + }}; const Scenario loopCannot{"The loop cannot be attached twice and a failing wake fails the operation", [] { - given("an attached host", [&] { - UIExecutorHost host; - host.attach([] { }); - checkThrows([&] { host.attach([] { }); }); - host.close(); - }); - given("a wake function that throws", [&] { - UIExecutorHost host; - host.attach([] { throw std::runtime_error("wake failed"); }); - Observed observed; - ex::inplace_stop_source stop; - auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); - ex::start(op); - then("the operation completes with the error and is not queued", [&] { - check(observed.errored); - check(observed.completions == 1); - host.drain(); - check(observed.completions == 1); - }); - host.close(); - }); -}}; + given("an attached host", [&] { + UIExecutorHost host; + host.attach([] {}); + checkThrows([&] { + host.attach([] {}); + }); + host.close(); + }); + given("a wake function that throws", [&] { + UIExecutorHost host; + host.attach([] { + throw std::runtime_error("wake failed"); + }); + Observed observed; + ex::inplace_stop_source stop; + auto op = ex::connect(host.executor().schedule(), Receiver{observed, stop.get_token()}); + ex::start(op); + then("the operation completes with the error and is not queued", [&] { + check(observed.errored); + check(observed.completions == 1); + host.drain(); + check(observed.completions == 1); + }); + host.close(); + }); + }}; const Scenario failingWake{"A failing wake fails the operations queued behind it", [] { - given("a wake function that queues a second operation, then throws", [&] { - UIExecutorHost host; - Observed first; - Observed second; - ex::inplace_stop_source stop; - using Op = Connected; - Op secondOp(host.executor().schedule(), Receiver{second, stop.get_token()}); - host.attach([&] { - secondOp.start(); // queued while the notification of the first is pending: it asks for none - throw std::runtime_error("wake failed"); - }); - Op firstOp(host.executor().schedule(), Receiver{first, stop.get_token()}); - firstOp.start(); - then("both complete with the error, and nothing is left to run", [&] { - check(first.errored); - check(second.errored); - check(first.completions == 1); - check(second.completions == 1); - host.drain(); - check(first.completions == 1); - check(second.completions == 1); - }); - host.close(); - }); -}}; + given("a wake function that queues a second operation, then throws", [&] { + UIExecutorHost host; + Observed first; + Observed second; + ex::inplace_stop_source stop; + using Op = Connected; + Op secondOp(host.executor().schedule(), Receiver{second, stop.get_token()}); + host.attach([&] { + secondOp.start(); // queued while the notification of the first is pending: it asks for none + throw std::runtime_error("wake failed"); + }); + Op firstOp(host.executor().schedule(), Receiver{first, stop.get_token()}); + firstOp.start(); + then("both complete with the error, and nothing is left to run", [&] { + check(first.errored); + check(second.errored); + check(first.completions == 1); + check(second.completions == 1); + host.drain(); + check(first.completions == 1); + check(second.completions == 1); + }); + host.close(); + }); + }}; namespace { // A wake function whose copy can be made to fail, as an allocation would. struct FragileWake { static inline std::atomic failCopy{false}; std::size_t* wakes; - explicit FragileWake(std::size_t* count) : wakes(count) { } + explicit FragileWake(std::size_t* count) : wakes(count) {} FragileWake(const FragileWake& other) : wakes(other.wakes) { if (failCopy) throw std::bad_alloc(); @@ -357,83 +366,87 @@ struct FragileWake { } // namespace const Scenario failureWhile{"A failure while queuing completes the operation and leaves the queue usable", [] { - given("a wake function that cannot be copied", [&] { - UIExecutorHost host; - std::size_t wakes{0}; - host.attach(FragileWake{&wakes}); - Observed failed; - Observed later; - ex::inplace_stop_source stop; - using Op = Connected; - FragileWake::failCopy = true; - Op failing(host.executor().schedule(), Receiver{failed, stop.get_token()}); - failing.start(); // start() is noexcept: the failure must not end the process - FragileWake::failCopy = false; - then("the operation completes with the error and nothing is queued", [&] { - check(failed.errored); - check(failed.completions == 1); - check(wakes == 0); - host.drain(); - check(failed.completions == 1); - }); - andThen("a later operation queues, wakes the loop and runs", [&] { - Op next(host.executor().schedule(), Receiver{later, stop.get_token()}); - next.start(); - check(wakes == 1); - host.drain(); - check(later.completions == 1); - check(!later.errored); - }); - host.close(); - }); -}}; + given("a wake function that cannot be copied", [&] { + UIExecutorHost host; + std::size_t wakes{0}; + host.attach(FragileWake{&wakes}); + Observed failed; + Observed later; + ex::inplace_stop_source stop; + using Op = Connected; + FragileWake::failCopy = true; + Op failing(host.executor().schedule(), Receiver{failed, stop.get_token()}); + failing.start(); // start() is noexcept: the failure must not end the process + FragileWake::failCopy = false; + then("the operation completes with the error and nothing is queued", [&] { + check(failed.errored); + check(failed.completions == 1); + check(wakes == 0); + host.drain(); + check(failed.completions == 1); + }); + andThen("a later operation queues, wakes the loop and runs", [&] { + Op next(host.executor().schedule(), Receiver{later, stop.get_token()}); + next.start(); + check(wakes == 1); + host.drain(); + check(later.completions == 1); + check(!later.errored); + }); + host.close(); + }); + }}; const Scenario shutdownWhile{"Shutdown while operations are racing stops or runs each exactly once", [] { - given("a loop that closes while operations are scheduled", [&] { - for (int round = 0; round < 20; ++round) { - FakeLoop loop; - loop.start(); - auto executor = loop.host.executor(); - Observed observed; - ex::inplace_stop_source stop; - static constexpr int count = 100; - using Op = Connected; - std::vector> ops; - for (int i = 0; i < count; ++i) - ops.push_back(std::make_unique(executor.schedule(), Receiver{observed, stop.get_token()})); - std::thread closer([&] { loop.stop(); }); - for (auto& op : ops) - op->start(); - closer.join(); - requireEventually([&] { return observed.completions == count; }); - } - }); -}}; + given("a loop that closes while operations are scheduled", [&] { + for (int round = 0; round < 20; ++round) { + FakeLoop loop; + loop.start(); + auto executor = loop.host.executor(); + Observed observed; + ex::inplace_stop_source stop; + static constexpr int count = 100; + using Op = Connected; + std::vector> ops; + for (int i = 0; i < count; ++i) + ops.push_back(std::make_unique(executor.schedule(), Receiver{observed, stop.get_token()})); + std::thread closer([&] { + loop.stop(); + }); + for (auto& op : ops) + op->start(); + closer.join(); + requireEventually([&] { + return observed.completions == count; + }); + } + }); + }}; #include #if defined(__linux__) const Scenario linuxInterface{"The Linux interface loop coalesces wake-ups without creating deferred sources", [] { - webfront::frontend::detail::uiloop::WakeEvent wake; - given("a wake event shared by several producers", [&] { - require(wake.consume() == 0); - static constexpr int producers = 4, signals = 10000; - std::vector threads; - for (int i = 0; i < producers; ++i) - threads.emplace_back([&] { - for (int n = 0; n < signals; ++n) - wake.signal(); - }); - for (auto& thread : threads) - thread.join(); - then("all signals occupy one bounded event and consumption resets it", [&] { - check(wake.consume() == producers * signals); - check(wake.consume() == 0); - wake.signal(); - check(wake.consume() == 1); - }); - }); -}}; + webfront::frontend::detail::uiloop::WakeEvent wake; + given("a wake event shared by several producers", [&] { + require(wake.consume() == 0); + static constexpr int producers = 4, signals = 10000; + std::vector threads; + for (int i = 0; i < producers; ++i) + threads.emplace_back([&] { + for (int n = 0; n < signals; ++n) + wake.signal(); + }); + for (auto& thread : threads) + thread.join(); + then("all signals occupy one bounded event and consumption resets it", [&] { + check(wake.consume() == producers * signals); + check(wake.consume() == 0); + wake.signal(); + check(wake.consume() == 1); + }); + }); + }}; namespace { std::atomic pagesOpened{0}; @@ -445,62 +458,62 @@ void countingLauncher(const std::string&) { } // namespace const Scenario linuxContextOwner{"The Linux interface loop refuses a default GLib context that another thread iterates", [] { - using namespace webfront::frontend; - const auto& glib = detail::uiloop::GLib::get(); - std::promise owned; - std::promise release; - auto ownedReady = owned.get_future(); - const auto released = release.get_future().share(); - given("another thread that owns the default context", [&] { - // Joined on every path, including a failed require: a joinable thread would end the process. - std::jthread owner([&] { - const auto context = glib.contextDefault(); - const bool taken = glib.contextAcquire(context) != 0; - owned.set_value(); - released.wait(); - if (taken) - glib.contextRelease(context); - }); - struct Free { - std::promise& release; - ~Free() { - release.set_value(); - } - } free{release}; - require(ownedReady.wait_for(std::chrono::seconds{30}) == std::future_status::ready); - when("the loop is run", [&] { - UIExecutorHost host; - UILoopStop stop; - // A stop already pending ends a loop that does start at its first check, before it iterates the context. Were the - // refusal lost, run() would return at once and the check below would fail, instead of the loop waiting for a - // context that the helper thread only gives up after run() returns. - stop.request(); - then("it throws before it attaches, instead of letting that thread run its wake callback", [&] { - bool refused = false; - try { - detail::uiloop::run(host, stop); - } catch (const std::runtime_error&) { - refused = true; - } - check(refused); - check(!host.executor().onUIThread()); - }); - }); - when("the frontend opens its page", [&] { - pagesOpened = 0; - then("the context is refused before the page is opened, so no tab is left without a server", [&] { - bool refused = false; - try { - BrowserWithUILoopFrontend::loop("127.0.0.1", "9002", "index.html", countingLauncher); - } catch (const std::runtime_error&) { - refused = true; - } - check(refused); - check(pagesOpened == 0); - }); - }); - }); -}}; + using namespace webfront::frontend; + const auto& glib = detail::uiloop::GLib::get(); + std::promise owned; + std::promise release; + auto ownedReady = owned.get_future(); + const auto released = release.get_future().share(); + given("another thread that owns the default context", [&] { + // Joined on every path, including a failed require: a joinable thread would end the process. + std::jthread owner([&] { + const auto context = glib.contextDefault(); + const bool taken = glib.contextAcquire(context) != 0; + owned.set_value(); + released.wait(); + if (taken) + glib.contextRelease(context); + }); + struct Free { + std::promise& release; + ~Free() { + release.set_value(); + } + } free{release}; + require(ownedReady.wait_for(std::chrono::seconds{30}) == std::future_status::ready); + when("the loop is run", [&] { + UIExecutorHost host; + UILoopStop stop; + // A stop already pending ends a loop that does start at its first check, before it iterates the context. Were the + // refusal lost, run() would return at once and the check below would fail, instead of the loop waiting for a + // context that the helper thread only gives up after run() returns. + stop.request(); + then("it throws before it attaches, instead of letting that thread run its wake callback", [&] { + bool refused = false; + try { + detail::uiloop::run(host, stop); + } catch (const std::runtime_error&) { + refused = true; + } + check(refused); + check(!host.executor().onUIThread()); + }); + }); + when("the frontend opens its page", [&] { + pagesOpened = 0; + then("the context is refused before the page is opened, so no tab is left without a server", [&] { + bool refused = false; + try { + BrowserWithUILoopFrontend::loop("127.0.0.1", "9002", "index.html", countingLauncher); + } catch (const std::runtime_error&) { + refused = true; + } + check(refused); + check(pagesOpened == 0); + }); + }); + }); + }}; #endif namespace { @@ -537,253 +550,273 @@ void fakeLaunch(const std::string& url) { } // namespace const Scenario systemBrowserCan{"The system browser can run an interface-thread loop on the calling thread", [] { - using Browser = BrowserWithUILoopFrontend; - given("the browser frontend with its loop", [&] { - check(!Browser::uiExecutor().available()); - launches = 0; - LoopOutcome outcome; - // No assertion off the main thread: the client records its result and always asks the loop to stop, - // so that a timeout fails the test instead of hanging or terminating the process. - std::atomic clientOk{false}; - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - if (waitUntil([&] { - return executor.available(); - })) { - // A function-local receiver type keeps the helper simple: schedule one operation and wait for it. - struct Holder { - decltype(ex::connect(std::declval(), std::declval())) op; - Holder(const UIExecutor& e, LoopOutcome& o) : op(ex::connect(e.schedule(), LoopReceiver{o})) { } - } holder(executor, outcome); - ex::start(holder.op); - clientOk = waitUntil([&] { - return outcome.completions == 1; - }); - } - Browser::requestStop(); - }); - when("open runs until the stop request", [&] { - const auto callingThread = std::this_thread::get_id(); - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - then("the page was launched, the operation ran on the calling thread and the executor is gone", [&] { - client.join(); - check(clientOk); - check(launches == 1); - check(outcome.valueThread == callingThread); - check(!outcome.stopped); - check(!Browser::uiExecutor().available()); - }); - }); - }); - given("a host's close request while no loop runs", [&] { - // The loop's stop state is process-wide and an earlier test may have left a request pending: spend it. - Browser::requestStop(); - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - then("it reaches nothing and is not remembered for the next loop (#567)", [&] { - check(!Browser::requestClose()); - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - // The loop of this test ends only because the client asks, after it has run: a remembered request would end it first. - checkEventually([&] { return executor.available(); }); - Browser::requestStop(); - }); - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - client.join(); - }); - then("a request made while it runs ends it, and one made after it is refused again", [&] { - std::atomic accepted{false}; - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - // The executor is available slightly before the loop can be stopped: repeat the request until accepted. - accepted = waitUntil([&] { - return executor.available() && Browser::requestClose(); - }); - if (!accepted) - Browser::requestStop(); // never leave the loop running if the request was not accepted in time - }); - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - client.join(); - check(accepted); - check(!Browser::requestClose()); - }); - }); - given("a stop requested before the loop starts", [&] { - Browser::requestStop(); - then("the loop ends at once", [&] { - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - check(!Browser::uiExecutor().available()); - }); - }); - given("an operation queued just before the stop request", [&] { - launches = 0; - LoopOutcome outcome; - std::atomic clientOk{false}; - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - if (waitUntil([&] { - return executor.available(); - })) { - struct Holder { - decltype(ex::connect(std::declval(), std::declval())) op; - Holder(const UIExecutor& e, LoopOutcome& o) : op(ex::connect(e.schedule(), LoopReceiver{o})) { } - } holder(executor, outcome); - ex::start(holder.op); - Browser::requestStop(); // the loop may run the job first or close with it still queued - clientOk = waitUntil([&] { - return outcome.completions >= 1; - }); - } else { - Browser::requestStop(); - } - }); - then("it completes exactly once, run or stopped, and is never left waiting", [&] { - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - client.join(); - check(clientOk); - check(outcome.completions == 1); - check(!outcome.unavailable); - check(!Browser::uiExecutor().available()); - }); - }); - given("several stop requests arriving while the loop exits", [&] { - launches = 0; - std::atomic finished{false}; - std::atomic clientOk{false}; - std::jthread client([&] { - const auto executor = Browser::uiExecutor(); - clientOk = waitUntil([&] { - return executor.available(); - }); - // Each request may queue a source in the platform loop: none may outlive it or touch what it freed. - do - Browser::requestStop(); - while (!finished); - }); - then("the loop ends", [&] { - Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); - finished = true; - client.join(); - check(clientOk); - check(!Browser::uiExecutor().available()); - }); - }); + using Browser = BrowserWithUILoopFrontend; + given("the browser frontend with its loop", [&] { + check(!Browser::uiExecutor().available()); + launches = 0; + LoopOutcome outcome; + // No assertion off the main thread: the client records its result and always asks the loop to stop, + // so that a timeout fails the test instead of hanging or terminating the process. + std::atomic clientOk{false}; + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + if (waitUntil([&] { + return executor.available(); + })) { + // A function-local receiver type keeps the helper simple: schedule one operation and wait for it. + struct Holder { + decltype(ex::connect(std::declval(), std::declval())) op; + Holder(const UIExecutor& e, LoopOutcome& o) : op(ex::connect(e.schedule(), LoopReceiver{o})) {} + } holder(executor, outcome); + ex::start(holder.op); + clientOk = waitUntil([&] { + return outcome.completions == 1; + }); + } + Browser::requestStop(); + }); + when("open runs until the stop request", [&] { + const auto callingThread = std::this_thread::get_id(); + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + then("the page was launched, the operation ran on the calling thread and the executor is gone", [&] { + client.join(); + check(clientOk); + check(launches == 1); + check(outcome.valueThread == callingThread); + check(!outcome.stopped); + check(!Browser::uiExecutor().available()); + }); + }); + }); + given("a host's close request while no loop runs", [&] { + // The loop's stop state is process-wide and an earlier test may have left a request pending: spend it. + Browser::requestStop(); + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + then("it reaches nothing and is not remembered for the next loop (#567)", [&] { + check(!Browser::requestClose()); + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + // The loop of this test ends only because the client asks, after it has run: a remembered request would end it + // first. + checkEventually([&] { + return executor.available(); + }); + Browser::requestStop(); + }); + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + client.join(); + }); + then("a request made while it runs ends it, and one made after it is refused again", [&] { + std::atomic accepted{false}; + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + // The executor is available slightly before the loop can be stopped: repeat the request until accepted. + accepted = waitUntil([&] { + return executor.available() && Browser::requestClose(); + }); + if (!accepted) + Browser::requestStop(); // never leave the loop running if the request was not accepted in time + }); + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + client.join(); + check(accepted); + check(!Browser::requestClose()); + }); + }); + given("a stop requested before the loop starts", [&] { + Browser::requestStop(); + then("the loop ends at once", [&] { + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + check(!Browser::uiExecutor().available()); + }); + }); + given("an operation queued just before the stop request", [&] { + launches = 0; + LoopOutcome outcome; + std::atomic clientOk{false}; + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + if (waitUntil([&] { + return executor.available(); + })) { + struct Holder { + decltype(ex::connect(std::declval(), + std::declval())) op; + Holder(const UIExecutor& e, LoopOutcome& o) : op(ex::connect(e.schedule(), LoopReceiver{o})) {} + } holder(executor, outcome); + ex::start(holder.op); + Browser::requestStop(); // the loop may run the job first or close with it still queued + clientOk = waitUntil([&] { + return outcome.completions >= 1; + }); + } else { + Browser::requestStop(); + } + }); + then("it completes exactly once, run or stopped, and is never left waiting", [&] { + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + client.join(); + check(clientOk); + check(outcome.completions == 1); + check(!outcome.unavailable); + check(!Browser::uiExecutor().available()); + }); + }); + given("several stop requests arriving while the loop exits", [&] { + launches = 0; + std::atomic finished{false}; + std::atomic clientOk{false}; + std::jthread client([&] { + const auto executor = Browser::uiExecutor(); + clientOk = waitUntil([&] { + return executor.available(); + }); + // Each request may queue a source in the platform loop: none may outlive it or touch what it freed. + do + Browser::requestStop(); + while (!finished); + }); + then("the loop ends", [&] { + Browser::loop("127.0.0.1", "9002", "index.html", fakeLaunch); + finished = true; + client.join(); + check(clientOk); + check(!Browser::uiExecutor().available()); + }); + }); #if defined(__APPLE__) - given("a thread that is not the main thread", [&] { - then("the loop fails before attaching anything", [&] { - bool threw{false}; - std::thread([&] { - try { - Browser::loop("127.0.0.1", "9002", "index.html", [](const std::string&) { }); - } catch (const std::runtime_error&) { - threw = true; - } - }).join(); - check(threw); - check(!Browser::uiExecutor().available()); - }); - }); + given("a thread that is not the main thread", [&] { + then("the loop fails before attaching anything", [&] { + bool threw{false}; + std::thread([&] { + try { + Browser::loop("127.0.0.1", "9002", "index.html", [](const std::string&) {}); + } catch (const std::runtime_error&) { + threw = true; + } + }).join(); + check(threw); + check(!Browser::uiExecutor().available()); + }); + }); #endif - given("a launcher that fails", [&] { - then("no executor is left attached", [&] { - checkThrows([&] { Browser::loop("127.0.0.1", "9002", "index.html", [](const std::string&) { throw std::runtime_error("no browser"); }); }); - check(!Browser::uiExecutor().available()); - }); - }); -}}; + given("a launcher that fails", [&] { + then("no executor is left attached", [&] { + checkThrows([&] { + Browser::loop("127.0.0.1", "9002", "index.html", [](const std::string&) { + throw std::runtime_error("no browser"); + }); + }); + check(!Browser::uiExecutor().available()); + }); + }); + }}; const Scenario closingWaits{"Closing waits for the wake-ups in flight, which may use what the loop frees", [] { - given("a wake function blocked inside an enqueue on another thread", [&] { - UIExecutorHost host; - std::mutex gate; - std::condition_variable changed; - bool inWake{false}; - bool release{false}; - host.attach([&] { - std::unique_lock lock(gate); - inWake = true; - changed.notify_all(); - changed.wait(lock, [&] { return release; }); - }); - Observed observed; - ex::inplace_stop_source stop; - using Op = Connected; - auto op = std::make_unique(host.executor().schedule(), Receiver{observed, stop.get_token()}); - std::thread scheduler([&] { op->start(); }); - { - std::unique_lock lock(gate); - require(changed.wait_for(lock, 30s, [&] { return inWake; })); - } - std::atomic closed{false}; - std::thread closer([&] { - host.close(); - closed = true; - }); - when("the loop closes meanwhile", [&] { - checkEventually([&] { - return !host.executor().available(); - }); - then("close() does not return before the wake-up is over", [&] { - check(!closed); - { - std::lock_guard lock(gate); - release = true; - changed.notify_all(); - } - scheduler.join(); - closer.join(); - check(closed); - check(observed.completions == 1); - check(observed.stopped); - }); - }); - if (scheduler.joinable()) { - { - std::lock_guard lock(gate); - release = true; - changed.notify_all(); - } - scheduler.join(); - closer.join(); - } - }); -}}; + given("a wake function blocked inside an enqueue on another thread", [&] { + UIExecutorHost host; + std::mutex gate; + std::condition_variable changed; + bool inWake{false}; + bool release{false}; + host.attach([&] { + std::unique_lock lock(gate); + inWake = true; + changed.notify_all(); + changed.wait(lock, [&] { + return release; + }); + }); + Observed observed; + ex::inplace_stop_source stop; + using Op = Connected; + auto op = std::make_unique(host.executor().schedule(), Receiver{observed, stop.get_token()}); + std::thread scheduler([&] { + op->start(); + }); + { + std::unique_lock lock(gate); + require(changed.wait_for(lock, 30s, [&] { + return inWake; + })); + } + std::atomic closed{false}; + std::thread closer([&] { + host.close(); + closed = true; + }); + when("the loop closes meanwhile", [&] { + checkEventually([&] { + return !host.executor().available(); + }); + then("close() does not return before the wake-up is over", [&] { + check(!closed); + { + std::lock_guard lock(gate); + release = true; + changed.notify_all(); + } + scheduler.join(); + closer.join(); + check(closed); + check(observed.completions == 1); + check(observed.stopped); + }); + }); + if (scheduler.joinable()) { + { + std::lock_guard lock(gate); + release = true; + changed.notify_all(); + } + scheduler.join(); + closer.join(); + } + }); + }}; const Scenario disarmingStop{"Disarming a stop waits for the request in flight", [] { - given("a quit function blocked inside request() on another thread", [&] { - UILoopStop stop; - std::mutex gate; - std::condition_variable changed; - bool inQuit{false}; - bool release{false}; - stop.arm([&] { - std::unique_lock lock(gate); - inQuit = true; - changed.notify_all(); - changed.wait(lock, [&] { return release; }); - }); - std::thread requester([&] { stop.request(); }); - { - std::unique_lock lock(gate); - require(changed.wait_for(lock, 30s, [&] { return inQuit; })); - } - std::atomic disarmed{false}; - std::thread loop([&] { - stop.disarm(); - disarmed = true; - }); - std::this_thread::sleep_for(50ms); - check(!disarmed); - { - std::lock_guard lock(gate); - release = true; - changed.notify_all(); - } - requester.join(); - loop.join(); - check(disarmed); - check(!stop.requestedStop()); - }); -}}; + given("a quit function blocked inside request() on another thread", [&] { + UILoopStop stop; + std::mutex gate; + std::condition_variable changed; + bool inQuit{false}; + bool release{false}; + stop.arm([&] { + std::unique_lock lock(gate); + inQuit = true; + changed.notify_all(); + changed.wait(lock, [&] { + return release; + }); + }); + std::thread requester([&] { + stop.request(); + }); + { + std::unique_lock lock(gate); + require(changed.wait_for(lock, 30s, [&] { + return inQuit; + })); + } + std::atomic disarmed{false}; + std::thread loop([&] { + stop.disarm(); + disarmed = true; + }); + std::this_thread::sleep_for(50ms); + check(!disarmed); + { + std::lock_guard lock(gate); + release = true; + changed.notify_all(); + } + requester.join(); + loop.join(); + check(disarmed); + check(!stop.requestedStop()); + }); + }}; namespace { // An operation that schedules its successor from the interface thread, `limit` times. @@ -806,12 +839,12 @@ struct ChainReceiver { if (chain->completed < chain->limit) chain->next(); } - void set_stopped() && noexcept { } - void set_error(std::exception_ptr) && noexcept { } + void set_stopped() && noexcept {} + void set_error(std::exception_ptr) && noexcept {} }; struct Chain::Link { decltype(ex::connect(std::declval().schedule())>(), std::declval())) op; - Link(UIExecutor e, Chain* c) : op(ex::connect(e.schedule(), ChainReceiver{c})) { } + Link(UIExecutor e, Chain* c) : op(ex::connect(e.schedule(), ChainReceiver{c})) {} }; void Chain::next() { links.push_back(std::make_unique(executor, this)); @@ -820,67 +853,81 @@ void Chain::next() { } // namespace const Scenario passInterface{"A pass of the interface thread runs a bounded batch", [] { - given("an operation that keeps rescheduling itself", [&] { - UIExecutorHost host; - std::size_t wakes{0}; - host.attach([&] { ++wakes; }); // called on this thread only: the chain starts and runs here - Chain chain; - chain.executor = host.executor(); - chain.limit = 10'000; - chain.next(); - require(wakes == 1); - when("the loop drains once", [&] { - host.drain(); - then("only the operations queued before the pass ran, and the loop is woken for the rest", [&] { - check(chain.completed == 1); - check(wakes == 2); - }); - }); - when("the loop keeps draining after each wake", [&] { - std::size_t passes{0}; - while (chain.completed < chain.limit && passes < 20'000) { - host.drain(); - ++passes; - } - then("every operation ran, one per pass, and the loop got the thread back in between", [&] { - check(chain.completed == chain.limit); - check(passes == chain.limit); - check(wakes <= passes + 1); // one notification per pass: they never pile up in the native queue - }); - }); - host.close(); - }); -}}; + given("an operation that keeps rescheduling itself", [&] { + UIExecutorHost host; + std::size_t wakes{0}; + host.attach([&] { + ++wakes; + }); // called on this thread only: the chain starts and runs here + Chain chain; + chain.executor = host.executor(); + chain.limit = 10'000; + chain.next(); + require(wakes == 1); + when("the loop drains once", [&] { + host.drain(); + then("only the operations queued before the pass ran, and the loop is woken for the rest", [&] { + check(chain.completed == 1); + check(wakes == 2); + }); + }); + when("the loop keeps draining after each wake", [&] { + std::size_t passes{0}; + while (chain.completed < chain.limit && passes < 20'000) { + host.drain(); + ++passes; + } + then("every operation ran, one per pass, and the loop got the thread back in between", [&] { + check(chain.completed == chain.limit); + check(passes == chain.limit); + check(wakes <= passes + 1); // one notification per pass: they never pile up in the native queue + }); + }); + host.close(); + }); + }}; const Scenario invokeBlocking{"invokeOnUIThread runs a function on the interface thread and waits for it", [] { - given("a frontend loop attached to an executor", [&] { - FakeLoop loop; - loop.start(); - const auto executor = loop.host.executor(); - when("another thread invokes a function", [&] { - std::thread::id ran; - invokeOnUIThread(executor, [&] { ran = std::this_thread::get_id(); }); - then("it ran on the interface thread, and had finished when the call returned", [&] { - check(ran == loop.uiThread); - }); - }); - when("the function throws", [&] { - then("the caller receives the exception", [&] { - requireThrows([&] { invokeOnUIThread(executor, [] { throw std::logic_error("refused"); }); }); - }); - }); - when("the interface thread itself invokes a function", [&] { - bool nested = false; - invokeOnUIThread(executor, [&] { invokeOnUIThread(executor, [&] { nested = true; }); }); - then("it runs at once instead of waiting for itself", [&] { - check(nested); - }); - }); - when("the loop has closed", [&] { - loop.stop(); - then("the call reports the missing interface thread", [&] { - requireThrows([&] { invokeOnUIThread(executor, [] { }); }); - }); - }); - }); -}}; + given("a frontend loop attached to an executor", [&] { + FakeLoop loop; + loop.start(); + const auto executor = loop.host.executor(); + when("another thread invokes a function", [&] { + std::thread::id ran; + invokeOnUIThread(executor, [&] { + ran = std::this_thread::get_id(); + }); + then("it ran on the interface thread, and had finished when the call returned", [&] { + check(ran == loop.uiThread); + }); + }); + when("the function throws", [&] { + then("the caller receives the exception", [&] { + requireThrows([&] { + invokeOnUIThread(executor, [] { + throw std::logic_error("refused"); + }); + }); + }); + }); + when("the interface thread itself invokes a function", [&] { + bool nested = false; + invokeOnUIThread(executor, [&] { + invokeOnUIThread(executor, [&] { + nested = true; + }); + }); + then("it runs at once instead of waiting for itself", [&] { + check(nested); + }); + }); + when("the loop has closed", [&] { + loop.stop(); + then("the call reports the missing interface thread", [&] { + requireThrows([&] { + invokeOnUIThread(executor, [] {}); + }); + }); + }); + }); + }}; diff --git a/test/unit/UISubscribersTests.cpp b/test/unit/UISubscribersTests.cpp index 41bc4123..ac3ac7d9 100644 --- a/test/unit/UISubscribersTests.cpp +++ b/test/unit/UISubscribersTests.cpp @@ -22,116 +22,118 @@ using Subscribers = detail::UISubscribers; } // namespace const Scenario severalHandlers{"Several handlers subscribe to connected browsers", [] { - given("two subscriptions", [&] { - auto subscribers = make_shared(); - vector calls; - auto first = subscribers->subscribe([&calls](FakeUI ui) { - calls.push_back("first " + to_string(ui.id)); - }); - auto second = subscribers->subscribe([&calls](FakeUI ui) { - calls.push_back("second " + to_string(ui.id)); - }); - - when("a browser connects", [&] { - subscribers->notify(FakeUI{7}); - then("every handler receives it, in subscription order", [&] { - require(calls == vector{"first 7", "second 7"}); - }); - }); - when("the first subscription is reset", [&] { - first.reset(); - subscribers->notify(FakeUI{8}); - then("only the remaining handler is called", [&] { - require(!first.active()); - require(calls == vector{"second 8"}); - }); - }); - when("a subscription is destroyed", [&] { - optional scoped{subscribers->subscribe([&calls](FakeUI) { - calls.push_back("scoped"); - })}; - scoped.reset(); - subscribers->notify(FakeUI{9}); - then("its handler is no longer called", [&] { - require(calls == vector{"first 9", "second 9"}); - }); - }); - }); -}}; + given("two subscriptions", [&] { + auto subscribers = make_shared(); + vector calls; + auto first = subscribers->subscribe([&calls](FakeUI ui) { + calls.push_back("first " + to_string(ui.id)); + }); + auto second = subscribers->subscribe([&calls](FakeUI ui) { + calls.push_back("second " + to_string(ui.id)); + }); + + when("a browser connects", [&] { + subscribers->notify(FakeUI{7}); + then("every handler receives it, in subscription order", [&] { + require(calls == vector{"first 7", "second 7"}); + }); + }); + when("the first subscription is reset", [&] { + first.reset(); + subscribers->notify(FakeUI{8}); + then("only the remaining handler is called", [&] { + require(!first.active()); + require(calls == vector{"second 8"}); + }); + }); + when("a subscription is destroyed", [&] { + optional scoped{subscribers->subscribe([&calls](FakeUI) { + calls.push_back("scoped"); + })}; + scoped.reset(); + subscribers->notify(FakeUI{9}); + then("its handler is no longer called", [&] { + require(calls == vector{"first 9", "second 9"}); + }); + }); + }); + }}; const Scenario subscriptionsMove{"Subscriptions are move-only handles", [] { - given("a subscription moved into another one", [&] { - auto subscribers = make_shared(); - int calls = 0; - auto original = subscribers->subscribe([&calls](FakeUI) { - ++calls; - }); - UISubscription moved{std::move(original)}; - - then("the handler stays subscribed and only the destination owns it", [&] { - subscribers->notify(FakeUI{1}); - require(calls == 1); - require(!original.active()); // NOLINT(bugprone-use-after-move): moved-from state is specified - require(moved.active()); - }); - when("a subscription is assigned over an active one", [&] { - moved = subscribers->subscribe([](FakeUI) {}); - then("the overwritten handler is unsubscribed", [&] { - require(subscribers->size() == 1); - }); - }); - }); -}}; + given("a subscription moved into another one", [&] { + auto subscribers = make_shared(); + int calls = 0; + auto original = subscribers->subscribe([&calls](FakeUI) { + ++calls; + }); + UISubscription moved{std::move(original)}; + + then("the handler stays subscribed and only the destination owns it", [&] { + subscribers->notify(FakeUI{1}); + require(calls == 1); + require(!original.active()); // NOLINT(bugprone-use-after-move): moved-from state is specified + require(moved.active()); + }); + when("a subscription is assigned over an active one", [&] { + moved = subscribers->subscribe([](FakeUI) {}); + then("the overwritten handler is unsubscribed", [&] { + require(subscribers->size() == 1); + }); + }); + }); + }}; const Scenario subscriptionMay{"A subscription may outlive its application", [] { - given("a subscription whose subscribers were destroyed", [&] { - auto subscribers = make_shared(); - auto subscription = subscribers->subscribe([](FakeUI) {}); - subscribers.reset(); - - then("resetting it is harmless", [&] { - requireNothrow([&] { subscription.reset(); }); - require(!subscription.active()); - }); - }); -}}; + given("a subscription whose subscribers were destroyed", [&] { + auto subscribers = make_shared(); + auto subscription = subscribers->subscribe([](FakeUI) {}); + subscribers.reset(); + + then("resetting it is harmless", [&] { + requireNothrow([&] { + subscription.reset(); + }); + require(!subscription.active()); + }); + }); + }}; const Scenario handlersMay{"Handlers may change the subscriptions while being notified", [] { - given("a handler that subscribes another handler and drops its own subscription", [&] { - auto subscribers = make_shared(); - vector calls; - UISubscription self; - UISubscription added; - self = subscribers->subscribe([&](FakeUI) { - calls.push_back("self"); - added = subscribers->subscribe([&calls](FakeUI) { - calls.push_back("added"); - }); - self.reset(); - }); - - when("two browsers connect", [&] { - subscribers->notify(FakeUI{1}); - subscribers->notify(FakeUI{2}); - then("the changes apply from the next browser, without deadlock", [&] { - require(calls == vector{"self", "added"}); - }); - }); - }); -}}; + given("a handler that subscribes another handler and drops its own subscription", [&] { + auto subscribers = make_shared(); + vector calls; + UISubscription self; + UISubscription added; + self = subscribers->subscribe([&](FakeUI) { + calls.push_back("self"); + added = subscribers->subscribe([&calls](FakeUI) { + calls.push_back("added"); + }); + self.reset(); + }); + + when("two browsers connect", [&] { + subscribers->notify(FakeUI{1}); + subscribers->notify(FakeUI{2}); + then("the changes apply from the next browser, without deadlock", [&] { + require(calls == vector{"self", "added"}); + }); + }); + }); + }}; const Scenario handlerMayOwn{"A handler may own another subscription to the same browsers", [] { - given("a handler whose capture owns a second subscription", [&] { - auto subscribers = make_shared(); - auto inner = make_shared(subscribers->subscribe([](FakeUI) {})); - auto outer = subscribers->subscribe([inner](FakeUI) {}); - inner.reset(); // the outer handler's capture is now the only owner of the inner subscription - - when("the outer subscription is reset", [&] { - outer.reset(); // destroying the outer handler unsubscribes the inner one - then("both are unsubscribed, without deadlock", [&] { - require(subscribers->size() == 0); - }); - }); - }); -}}; + given("a handler whose capture owns a second subscription", [&] { + auto subscribers = make_shared(); + auto inner = make_shared(subscribers->subscribe([](FakeUI) {})); + auto outer = subscribers->subscribe([inner](FakeUI) {}); + inner.reset(); // the outer handler's capture is now the only owner of the inner subscription + + when("the outer subscription is reset", [&] { + outer.reset(); // destroying the outer handler unsubscribes the inner one + then("both are unsubscribed, without deadlock", [&] { + require(subscribers->size() == 0); + }); + }); + }); + }}; diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index ccc68d99..3b3810c9 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief A connection proves it comes from the view of an embedded frontend by the secret of the launch (#453, ADR-020). #include "InjectableNetworking.hpp" -#include #include #include -#include +#include #include +#include #include #include @@ -21,13 +21,15 @@ using namespace webfront; namespace webfront::testing { template struct LaunchSecret { - static const std::string& of(const Application& app) { return app.viewSecret; } + static const std::string& of(const Application& app) { + return app.viewSecret; + } }; } // namespace webfront::testing namespace { const std::string viewUpgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; struct ViewOneBrowserNet : testing::InjectableNetworking { static inline bool accepted{}; @@ -41,7 +43,7 @@ struct ViewOneBrowserNet : testing::InjectableNetworking { }; using ViewSocket = testing::InjectableSocket; -using ViewApp = BasicWF; +using ViewApp = BasicWF; struct ViewVerdict { bool embedded = false; @@ -51,7 +53,7 @@ struct ViewVerdict { // Connects one browser whose handshake carries `proof` after its two header bytes, and reports what the UI says. ViewVerdict connect(ViewApp& app, const std::string& proof) { ViewVerdict verdict; - bool started = false; + bool started = false; app.onUIStarted([&](ViewApp::UI ui) { verdict.embedded = ui.isEmbeddedView(); verdict.local = ui.isLocalClient(); @@ -74,177 +76,192 @@ void freshNetwork() { } } // namespace -const Scenario connectionAssociated{"A connection is associated with the view of an embedded frontend only by the secret of the launch", {"view-association"}, [] { - freshNetwork(); - ViewApp app{WebFrontConfig{.port = "0"}}; - const std::string secret = testing::LaunchSecret::of(app); +const Scenario connectionAssociated{"A connection is associated with the view of an embedded frontend only by the secret of the launch", + {"view-association"}, + [] { + freshNetwork(); + ViewApp app{WebFrontConfig{.port = "0"}}; + const std::string secret = testing::LaunchSecret::of(app); - given("the secret of the launch", [&] { - then("it is 256 random bits in lowercase hexadecimal", [&] { - require(secret.size() == 64); - require(std::ranges::all_of(secret, [](char c) { return std::isxdigit(static_cast(c)) && !std::isupper(static_cast(c)); })); - }); - then("another application has another one", [&] { - ViewApp other{WebFrontConfig{.port = "0"}}; - require(testing::LaunchSecret::of(other) != secret); - }); - }); - when("the handshake presents the secret", [&] { - const auto verdict = connect(app, secret); - then("the connection is the embedded view and a local client", [&] { - require(verdict.embedded); - require(verdict.local); - }); - }); - when("the handshake presents a wrong secret of the right length", [&] { - auto wrong = secret; - wrong.back() = wrong.back() == '0' ? '1' : '0'; - const auto verdict = connect(app, wrong); - then("the connection is neither", [&] { - require(!verdict.embedded); - require(!verdict.local); - }); - }); - when("the handshake presents a prefix of the secret", [&] { - then("it is not accepted", [&] { - require(!connect(app, secret.substr(0, 63)).embedded); - }); - }); - when("the handshake presents no secret", [&] { - const auto verdict = connect(app, {}); - then("the connection is neither, whatever its address", [&] { - require(!verdict.embedded); - require(!verdict.local); - }); - }); - when("the handshake carries the secret of an earlier launch", [&] { - std::string earlier; - { - ViewApp previous{WebFrontConfig{.port = "0"}}; - earlier = testing::LaunchSecret::of(previous); - } - const auto verdict = connect(app, earlier); - then("it is rejected: the secret does not survive a restart", [&] { - require(!verdict.embedded); - }); - }); - when("the handshake carries the secret padded with extra bytes", [&] { - require(!connect(app, secret + "00").embedded); - }); - when("the handshake carries a proof longer than a secret", [&] { - require(!connect(app, std::string(100, 'a')).embedded); - }); - when("a second handshake without the secret follows the one that presented it", [&] { - std::optional browser; - app.onUIStarted([&](ViewApp::UI ui) { browser = ui; }); - ViewSocket::receive(std::as_bytes(std::span(viewUpgradeRequest))); - msg::Handshake handshake; - std::vector payload(handshake.header().begin(), handshake.header().end()); - for (const char c : secret) - payload.push_back(static_cast(c)); - ViewSocket::receive(testing::clientFrame(payload)); - require(browser); - require(browser->isEmbeddedView()); - ViewSocket::receive(testing::clientFrame(std::vector(handshake.header().begin(), handshake.header().end()))); - then("the connection stays the embedded view", [&] { - require(browser->isEmbeddedView()); - require(browser->isLocalClient()); - }); - }); -}}; + given("the secret of the launch", [&] { + then("it is 256 random bits in lowercase hexadecimal", [&] { + require(secret.size() == 64); + require(std::ranges::all_of(secret, [](char c) { + return std::isxdigit(static_cast(c)) && !std::isupper(static_cast(c)); + })); + }); + then("another application has another one", [&] { + ViewApp other{WebFrontConfig{.port = "0"}}; + require(testing::LaunchSecret::of(other) != secret); + }); + }); + when("the handshake presents the secret", [&] { + const auto verdict = connect(app, secret); + then("the connection is the embedded view and a local client", [&] { + require(verdict.embedded); + require(verdict.local); + }); + }); + when("the handshake presents a wrong secret of the right length", [&] { + auto wrong = secret; + wrong.back() = wrong.back() == '0' ? '1' : '0'; + const auto verdict = connect(app, wrong); + then("the connection is neither", [&] { + require(!verdict.embedded); + require(!verdict.local); + }); + }); + when("the handshake presents a prefix of the secret", [&] { + then("it is not accepted", [&] { + require(!connect(app, secret.substr(0, 63)).embedded); + }); + }); + when("the handshake presents no secret", [&] { + const auto verdict = connect(app, {}); + then("the connection is neither, whatever its address", [&] { + require(!verdict.embedded); + require(!verdict.local); + }); + }); + when("the handshake carries the secret of an earlier launch", [&] { + std::string earlier; + { + ViewApp previous{WebFrontConfig{.port = "0"}}; + earlier = testing::LaunchSecret::of(previous); + } + const auto verdict = connect(app, earlier); + then("it is rejected: the secret does not survive a restart", [&] { + require(!verdict.embedded); + }); + }); + when("the handshake carries the secret padded with extra bytes", [&] { + require(!connect(app, secret + "00").embedded); + }); + when("the handshake carries a proof longer than a secret", [&] { + require(!connect(app, std::string(100, 'a')).embedded); + }); + when("a second handshake without the secret follows the one that presented it", [&] { + std::optional browser; + app.onUIStarted([&](ViewApp::UI ui) { + browser = ui; + }); + ViewSocket::receive(std::as_bytes(std::span(viewUpgradeRequest))); + msg::Handshake handshake; + std::vector payload(handshake.header().begin(), handshake.header().end()); + for (const char c : secret) + payload.push_back(static_cast(c)); + ViewSocket::receive(testing::clientFrame(payload)); + require(browser); + require(browser->isEmbeddedView()); + ViewSocket::receive( + testing::clientFrame(std::vector(handshake.header().begin(), handshake.header().end()))); + then("the connection stays the embedded view", [&] { + require(browser->isEmbeddedView()); + require(browser->isLocalClient()); + }); + }); + }}; const Scenario scriptHands{"The script that hands the secret to a view refuses what it cannot write safely", {"view-association"}, [] { - const std::string secret(64, 'a'); - given("a hexadecimal secret and a plain origin", [&] { - const auto script = detail::viewSecretScript(secret, "http://127.0.0.1:9002"); - then("the script names the origin and the secret", [&] { - require(script.contains("location.origin === new URL('http://127.0.0.1:9002').origin")); - require(script.contains(secret)); - }); - }); - given("an origin or a secret that would need escaping", [&] { - then("there is no script, hence no association", [&] { - require(detail::viewSecretScript(secret, "http://x'; alert(1); '").empty()); - require(detail::viewSecretScript(secret, "http://x\\").empty()); - require(detail::viewSecretScript(secret, "http://x\n").empty()); - require(detail::viewSecretScript("a'b", "http://127.0.0.1:9002").empty()); - require(detail::viewSecretScript({}, "http://127.0.0.1:9002").empty()); - }); - }); -}}; + const std::string secret(64, 'a'); + given("a hexadecimal secret and a plain origin", [&] { + const auto script = detail::viewSecretScript(secret, "http://127.0.0.1:9002"); + then("the script names the origin and the secret", [&] { + require(script.contains("location.origin === new URL('http://127.0.0.1:9002').origin")); + require(script.contains(secret)); + }); + }); + given("an origin or a secret that would need escaping", [&] { + then("there is no script, hence no association", [&] { + require(detail::viewSecretScript(secret, "http://x'; alert(1); '").empty()); + require(detail::viewSecretScript(secret, "http://x\\").empty()); + require(detail::viewSecretScript(secret, "http://x\n").empty()); + require(detail::viewSecretScript("a'b", "http://127.0.0.1:9002").empty()); + require(detail::viewSecretScript({}, "http://127.0.0.1:9002").empty()); + }); + }); + }}; const Scenario originGiven{"The origin given to a view is written as the browser writes location.origin", {"view-association"}, [] { - then("the default port 80 is dropped and the host is lowercase", [&] { - require(detail::browserOrigin("127.0.0.1", "80") == "http://127.0.0.1"); - require(detail::browserOrigin("LocalHost", "9002") == "http://localhost:9002"); - require(detail::browserOrigin("127.0.0.1", "8080") == "http://127.0.0.1:8080"); - }); -}}; + then("the default port 80 is dropped and the host is lowercase", [&] { + require(detail::browserOrigin("127.0.0.1", "80") == "http://127.0.0.1"); + require(detail::browserOrigin("LocalHost", "9002") == "http://localhost:9002"); + require(detail::browserOrigin("127.0.0.1", "8080") == "http://127.0.0.1:8080"); + }); + }}; const Scenario iPv4Loopback{"An IPv4 loopback seen through a dual-stack socket is a loopback peer", {"view-association"}, [] { - then("the v4-mapped loopback is, another mapped address and a public one are not", [&] { - require(detail::isLoopbackAddress(stdnet::ip::address(stdnet::ip::address_v4::loopback()))); - require(detail::isLoopbackAddress(stdnet::ip::address(stdnet::ip::address_v6::loopback()))); - const auto mapped = [](unsigned char first) { - stdnet::ip::address_v6::bytes_type bytes{}; - bytes[10] = bytes[11] = 0xFF; - bytes[12] = first; - bytes[15] = 1; - return stdnet::ip::address(stdnet::ip::address_v6(bytes)); - }; - require(detail::isLoopbackAddress(mapped(127))); - require(!detail::isLoopbackAddress(mapped(10))); - }); -}}; + then("the v4-mapped loopback is, another mapped address and a public one are not", [&] { + require(detail::isLoopbackAddress(stdnet::ip::address(stdnet::ip::address_v4::loopback()))); + require(detail::isLoopbackAddress(stdnet::ip::address(stdnet::ip::address_v6::loopback()))); + const auto mapped = [](unsigned char first) { + stdnet::ip::address_v6::bytes_type bytes{}; + bytes[10] = bytes[11] = 0xFF; + bytes[12] = first; + bytes[15] = 1; + return stdnet::ip::address(stdnet::ip::address_v6(bytes)); + }; + require(detail::isLoopbackAddress(mapped(127))); + require(!detail::isLoopbackAddress(mapped(10))); + }); + }}; const Scenario loopbackPeerScenario{"A loopback peer is a local client only when the application trusts loopback clients", {"view-association"}, [] { - freshNetwork(); - ViewSocket::peerIsLoopback = true; - - given("the default configuration", [&] { - ViewApp app{WebFrontConfig{.port = "0"}}; - const auto verdict = connect(app, {}); - then("a loopback peer without the secret is not local", [&] { - require(!verdict.embedded); - require(!verdict.local); - }); - }); - given("trustLoopbackClients", [&] { - ViewApp app{WebFrontConfig{.port = "0", .trustLoopbackClients = true}}; - const auto verdict = connect(app, {}); - then("a loopback peer is local though it is not the embedded view", [&] { - require(!verdict.embedded); - require(verdict.local); - }); - }); - given("trustLoopbackClients and a peer that is not the loopback", [&] { - ViewSocket::peerIsLoopback = false; - ViewApp app{WebFrontConfig{.port = "0", .trustLoopbackClients = true}}; - const auto verdict = connect(app, {}); - then("the connection is not local", [&] { - require(!verdict.local); - }); - }); -}}; + freshNetwork(); + ViewSocket::peerIsLoopback = true; + + given("the default configuration", [&] { + ViewApp app{WebFrontConfig{.port = "0"}}; + const auto verdict = connect(app, {}); + then("a loopback peer without the secret is not local", [&] { + require(!verdict.embedded); + require(!verdict.local); + }); + }); + given("trustLoopbackClients", [&] { + ViewApp app{ + WebFrontConfig{.port = "0", .trustLoopbackClients = true} + }; + const auto verdict = connect(app, {}); + then("a loopback peer is local though it is not the embedded view", [&] { + require(!verdict.embedded); + require(verdict.local); + }); + }); + given("trustLoopbackClients and a peer that is not the loopback", [&] { + ViewSocket::peerIsLoopback = false; + ViewApp app{ + WebFrontConfig{.port = "0", .trustLoopbackClients = true} + }; + const auto verdict = connect(app, {}); + then("the connection is not local", [&] { + require(!verdict.local); + }); + }); + }}; const Scenario handshakeSecret{"The handshake's secret never reaches the diagnostics", {"view-association"}, [] { - freshNetwork(); - ViewApp app{WebFrontConfig{.port = "0"}}; - std::vector records; - log::setLogLevel(log::Debug); - const auto sink = log::addSinks([&records](std::string_view text) { records.emplace_back(text); }); - - when("a handshake carrying a recognizable proof is received", [&] { - connect(app, std::string(64, 'Q')); - log::removeSinks(sink); - then("the message is logged, but no record contains the proof in text or as a hexadecimal dump", [&] { - require(std::ranges::any_of(records, [](const std::string& record) { return record.contains("onMessage(binary)"); })); - for (const auto& record : records) { - require(!record.contains("QQQQ")); - require(!record.contains("51 51 51")); - require(!record.contains("515151")); - } - }); - }); - log::removeSinks(sink); -}}; + freshNetwork(); + ViewApp app{WebFrontConfig{.port = "0"}}; + std::vector records; + log::setLogLevel(log::Debug); + const auto sink = log::addSinks([&records](std::string_view text) { + records.emplace_back(text); + }); + + when("a handshake carrying a recognizable proof is received", [&] { + connect(app, std::string(64, 'Q')); + log::removeSinks(sink); + then("the message is logged, but no record contains the proof in text or as a hexadecimal dump", [&] { + require(std::ranges::any_of(records, [](const std::string& record) { + return record.contains("onMessage(binary)"); + })); + for (const auto& record : records) { + require(!record.contains("QQQQ")); + require(!record.contains("51 51 51")); + require(!record.contains("515151")); + } + }); + }); + log::removeSinks(sink); + }}; diff --git a/test/unit/WebFrontTests.cpp b/test/unit/WebFrontTests.cpp index c1ab42d9..ef78b976 100644 --- a/test/unit/WebFrontTests.cpp +++ b/test/unit/WebFrontTests.cpp @@ -1,12 +1,11 @@ #include "InjectableNetworking.hpp" #include "Mocks.hpp" #include "Version.hpp" -#include -#include #include +#include +#include #include #include -#include #include #include @@ -15,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -38,56 +38,64 @@ using namespace webfront::bdd; using namespace webfront; const Scenario publicVersion{"The public version matches the version detected by CMake", {"version"}, [] { - then("consumers and CMake observe the same version", [&] { - require(webfront::version == cmakeProjectVersion); - }); -}}; - -const Scenario ptyPageAuthorization{"PTY page requires explicit opt-in, a loopback bind and the application Origin", [] { - then("registration is refused by default and opt-in rejects wildcard and non-loopback binds", [] { - WebFront app{WebFrontConfig{.port = "0"}}; - requireThrows([&] { registerPtyPage(app, {}); }); - require(!app.hasCppFunction("webfront.pty.open")); - for (const auto* address : {"0.0.0.0", "::", "192.0.2.1", "localhost", "0:0:0:0:0:0:0:1"}) { - requireThrows([&] { - WebFront rejected{WebFrontConfig{.address = address, .port = "0", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true}}; + then("consumers and CMake observe the same version", [&] { + require(webfront::version == cmakeProjectVersion); + }); + }}; + +const Scenario ptyPageAuthorization{ + "PTY page requires explicit opt-in, a loopback bind and the application Origin", + [] { + then("registration is refused by default and opt-in rejects wildcard and non-loopback binds", [] { + WebFront app{WebFrontConfig{.port = "0"}}; + requireThrows([&] { + registerPtyPage(app, {}); }); - } - }); - then("configuration rejects a bridge policy that would allow missing or foreign origins", [] { - for (const auto& policy : {ContentPolicy{}, ContentPolicy{.allowAnyBridgeOrigin = true, .allowMissingOrigin = false}, - ContentPolicy{.bridgeAllowedOrigins = {"http://foreign.example"}, .allowMissingOrigin = false}}) { - requireThrows([&] { - WebFront app{WebFrontConfig{.port = "0", .contentPolicy = policy, .allowPtyPages = true}}; - }); - } - }); - then("the upgrade handler accepts the application's own Origin and refuses missing or foreign Origin", [] { - using namespace webfront::http; - const auto config = webfront::detail::checkedPtyPageConfig({ - .contentPolicy = {.allowMissingOrigin = false}, - .allowPtyPages = true + require(!app.hasCppFunction("webfront.pty.open")); + for (const auto* address : {"0.0.0.0", "::", "192.0.2.1", "localhost", "0:0:0:0:0:0:0:1"}) { + requireThrows([&] { + WebFront rejected{ + WebFrontConfig{.address = address, .port = "0", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true} + }; + }); + } }); - RequestHandler> handler{ - ".", webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002/", config.contentPolicy} - }; - const auto upgrade = [&](std::string_view origin) { - std::string input = "GET / HTTP/1.1\r\nHost: 127.0.0.1:9002\r\nUpgrade: websocket\r\n" - "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"; - input += origin; - input += "\r\n"; - Request request; - require(request.parseSomeData(input.begin(), input.end())); - return handler.handleRequest(request).statusCode; - }; - require(upgrade("") == Response::forbidden); - require(upgrade("Origin: http://foreign.example\r\n") == Response::forbidden); - require(upgrade("Origin: http://127.0.0.1:9002\r\n") == Response::switchingProtocols); - require(webfront::detail::checkedPtyPageConfig({ - .address = "::1", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true - }).address == "::1"); - }); -}}; + then("configuration rejects a bridge policy that would allow missing or foreign origins", [] { + for (const auto& policy : { + ContentPolicy{}, + ContentPolicy{.allowAnyBridgeOrigin = true, .allowMissingOrigin = false}, + ContentPolicy{.bridgeAllowedOrigins = {"http://foreign.example"}, .allowMissingOrigin = false} + }) { + requireThrows([&] { + WebFront app{ + WebFrontConfig{.port = "0", .contentPolicy = policy, .allowPtyPages = true} + }; + }); + } + }); + then("the upgrade handler accepts the application's own Origin and refuses missing or foreign Origin", [] { + using namespace webfront::http; + const auto config = webfront::detail::checkedPtyPageConfig({.contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true}); + RequestHandler> handler{ + ".", + webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002/", config.contentPolicy} + }; + const auto upgrade = [&](std::string_view origin) { + std::string input = "GET / HTTP/1.1\r\nHost: 127.0.0.1:9002\r\nUpgrade: websocket\r\n" + "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"; + input += origin; + input += "\r\n"; + Request request; + require(request.parseSomeData(input.begin(), input.end())); + return handler.handleRequest(request).statusCode; + }; + require(upgrade("") == Response::forbidden); + require(upgrade("Origin: http://foreign.example\r\n") == Response::forbidden); + require(upgrade("Origin: http://127.0.0.1:9002\r\n") == Response::switchingProtocols); + require(webfront::detail::checkedPtyPageConfig({.address = "::1", .contentPolicy = {.allowMissingOrigin = false}, .allowPtyPages = true}).address + == "::1"); + }); + }}; namespace { @@ -109,11 +117,13 @@ struct ResultLinkMock { class WebFrontIoContextMock { public: static inline std::atomic stopCalls{0}; - void run() {} + void run() {} std::size_t run_one() { return 0; } - void stop() { ++stopCalls; } + void stop() { + ++stopCalls; + } void restart() {} }; @@ -128,9 +138,13 @@ class WebFrontAcceptorMock : public networking::SocketBaseMock { openState = true; } - bool is_open() const { return openState; } + bool is_open() const { + return openState; + } - void close() { openState = false; } + void close() { + openState = false; + } }; class WebFrontNetworkingMock : public networking::NetworkingMock { @@ -140,7 +154,7 @@ class WebFrontNetworkingMock : public networking::NetworkingMock { }; struct InitializingFrontend { - static inline int initializeCalls = 0; + static inline int initializeCalls = 0; static constexpr frontend::Action action{frontend::Action::keepServerRunning}; static void initialize() { @@ -151,7 +165,7 @@ struct InitializingFrontend { }; struct RetryingFrontend { - static inline int initializeCalls = 0; + static inline int initializeCalls = 0; static constexpr frontend::Action action{frontend::Action::keepServerRunning}; static void initialize() { @@ -163,10 +177,10 @@ struct RetryingFrontend { }; struct OpeningFrontend { - static inline int initializeCalls = 0; - static inline int openCalls = 0; - static inline std::string lastPort; - static inline std::string lastFile; + static inline int initializeCalls = 0; + static inline int openCalls = 0; + static inline std::string lastPort; + static inline std::string lastFile; static constexpr frontend::Action action{frontend::Action::keepServerRunning}; static void initialize() { @@ -181,10 +195,10 @@ struct OpeningFrontend { }; struct ClosingFrontend { - static inline int initializeCalls = 0; - static inline int openCalls = 0; - static inline std::string lastPort; - static inline std::string lastFile; + static inline int initializeCalls = 0; + static inline int openCalls = 0; + static inline std::string lastPort; + static inline std::string lastFile; static constexpr frontend::Action action{frontend::Action::closeServerAfterOpen}; static void initialize() { @@ -200,21 +214,27 @@ struct ClosingFrontend { struct FailingFrontend { static constexpr frontend::Action action{frontend::Action::closeServerAfterOpen}; - static void initialize() {} - static void open(std::string_view, std::string_view) { throw std::runtime_error("frontend startup failed"); } + static void initialize() {} + static void open(std::string_view, std::string_view) { + throw std::runtime_error("frontend startup failed"); + } }; struct ThreadRecordingFrontend { - static inline std::thread::id openThread; + static inline std::thread::id openThread; static constexpr frontend::Action action{frontend::Action::closeServerAfterOpen}; - static void initialize() {} - static void open(std::string_view, std::string_view) { openThread = std::this_thread::get_id(); } + static void initialize() {} + static void open(std::string_view, std::string_view) { + openThread = std::this_thread::get_id(); + } }; struct FailingNonBlockingFrontend { static constexpr frontend::Action action{frontend::Action::keepServerRunning}; - static void initialize() {} - static void open(std::string_view, std::string_view) { throw std::runtime_error("launcher failed"); } + static void initialize() {} + static void open(std::string_view, std::string_view) { + throw std::runtime_error("launcher failed"); + } }; struct AddressFrontend { @@ -222,8 +242,8 @@ struct AddressFrontend { static inline std::string lastAddress; static inline std::string lastPort; static inline std::string lastFile; - static void initialize() { } - static void open(std::string_view, std::string_view) { } + static void initialize() {} + static void open(std::string_view, std::string_view) {} static void open(std::string_view address, std::string_view port, std::string_view file) { lastAddress = address; lastPort = port; @@ -237,251 +257,306 @@ int freeFunctionForDeductionTest(double value) { } // namespace -const Scenario frontendSelection{"Frontend selection aliases", [] { +const Scenario frontendSelection{ + "Frontend selection aliases", + [] { #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) - static_assert(frontend::FrontendType); - static_assert(std::is_same_v::FrontendProvider, frontend::NativeWebViewFrontend>); + static_assert(frontend::FrontendType); + static_assert(std::is_same_v::FrontendProvider, frontend::NativeWebViewFrontend>); #endif #if defined(_WIN32) - static_assert(std::is_same_v); + static_assert(std::is_same_v); #elif defined(__APPLE__) - static_assert(std::is_same_v); + static_assert(std::is_same_v); #elif defined(__linux__) - static_assert(std::is_same_v); + static_assert(std::is_same_v); #endif - static_assert(std::is_same_v); - static_assert(frontend::FrontendType); - static_assert(frontend::WKWebViewFrontend::action == frontend::Action::closeServerAfterOpen); - static_assert(frontend::FrontendType); - static_assert(frontend::FrontendType); - static_assert(frontend::WebView2Frontend::action == frontend::Action::closeServerAfterOpen); - then("the default frontend is always the system browser, regardless of CEF availability", [&] { - require(std::is_same_v); - }); + static_assert(std::is_same_v); + static_assert(frontend::FrontendType); + static_assert(frontend::WKWebViewFrontend::action == frontend::Action::closeServerAfterOpen); + static_assert(frontend::FrontendType); + static_assert(frontend::FrontendType); + static_assert(frontend::WebView2Frontend::action == frontend::Action::closeServerAfterOpen); + then("the default frontend is always the system browser, regardless of CEF availability", [&] { + require(std::is_same_v); + }); - then("the convenience alias keeps the selected frontend type", [&] { - using FrontendWF = BasicWFWithFrontend; - require(std::is_same_v); - }); -}}; + then("the convenience alias keeps the selected frontend type", [&] { + using FrontendWF = BasicWFWithFrontend; + require(std::is_same_v); + }); + }}; #if (defined(_WIN32) && !defined(WEBFRONT_EMBED_WEBVIEW2)) || (defined(__APPLE__) && !defined(WEBFRONT_EMBED_WKWEBVIEW)) \ || (defined(__linux__) && !defined(WEBFRONT_EMBED_WEBKITGTK)) const Scenario selectingNative{"Selecting the native web view without support preserves the platform diagnostic", [] { #if defined(_WIN32) - const auto diagnostic = "WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"; + const auto diagnostic = "WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"; #elif defined(__APPLE__) const auto diagnostic = "WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON"; #else const auto diagnostic = "WebKitGTKFrontend is unavailable. Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON"; #endif - then("opening names the platform adapter's enabling option", [&] { - requireThrows([&] { frontend::NativeWebViewFrontend::open("9200", "index.html"); }, equals(diagnostic)); - }); -}}; + then("opening names the platform adapter's enabling option", [&] { + requireThrows( + [&] { + frontend::NativeWebViewFrontend::open("9200", "index.html"); + }, + equals(diagnostic)); + }); + }}; #endif -const Scenario selectingFrontend{"Selecting a frontend the build does not support fails clearly", [] { +const Scenario selectingFrontend{ + "Selecting a frontend the build does not support fails clearly", + [] { #if !defined(WEBFRONT_EMBED_WKWEBVIEW) || !defined(__APPLE__) - then("WKWebView's initialization and opening name the enabling option", [&] { - requireThrows([&] { frontend::WKWebViewFrontend::initialize(); }, equals("WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON")); - requireThrows([&] { frontend::WKWebViewFrontend::open("9200", "index.html"); }, equals("WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON")); - requireThrows([&] { frontend::WKWebViewFrontend::open("127.0.0.1", "9200", "index.html", ContentPolicy{}); }); - }); + then("WKWebView's initialization and opening name the enabling option", [&] { + requireThrows( + [&] { + frontend::WKWebViewFrontend::initialize(); + }, + equals("WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON")); + requireThrows( + [&] { + frontend::WKWebViewFrontend::open("9200", "index.html"); + }, + equals("WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON")); + requireThrows([&] { + frontend::WKWebViewFrontend::open("127.0.0.1", "9200", "index.html", ContentPolicy{}); + }); + }); #endif #if !defined(WEBFRONT_EMBED_WEBVIEW2) || !defined(_WIN32) - then("opening WebView2 explains which option to enable", [&] { - using App = BasicWFWithFrontend; - App app("9200"); - requireThrows([&] { app.openWindow("index.html"); }, equals("WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON")); - }); + then("opening WebView2 explains which option to enable", [&] { + using App = BasicWFWithFrontend; + App app("9200"); + requireThrows( + [&] { + app.openWindow("index.html"); + }, + equals("WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON")); + }); #endif #ifndef WEBFRONT_EMBED_WEBKITGTK - then("WebKitGTK's initialization names the enabling option", [&] { - requireThrows([&] { frontend::WebKitGTKFrontend::initialize(); }, equals("WebKitGTKFrontend is unavailable. Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON")); - }); + then("WebKitGTK's initialization names the enabling option", [&] { + requireThrows( + [&] { + frontend::WebKitGTKFrontend::initialize(); + }, + equals("WebKitGTKFrontend is unavailable. Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON")); + }); #endif - if constexpr (!cef::webfrontEmbedCEF) { - then("constructing a CEF-fronted application throws instead of silently doing nothing, and opening CEF explains how to " - "enable it", [&] { - using CEFWF = BasicWFWithFrontend; - requireThrows([&] { CEFWF("9200"); }); - requireThrows([&] { frontend::CEFFrontend::open("9200", "index.html"); }, equals("webfront::frontend::CEFFrontend requires CEF support, but this build was configured with " + if constexpr (!cef::webfrontEmbedCEF) { + then("constructing a CEF-fronted application throws instead of silently doing nothing, and opening CEF explains how to " + "enable it", + [&] { + using CEFWF = BasicWFWithFrontend; + requireThrows([&] { + CEFWF("9200"); + }); + requireThrows( + [&] { + frontend::CEFFrontend::open("9200", "index.html"); + }, + equals("webfront::frontend::CEFFrontend requires CEF support, but this build was configured with " "WEBFRONT_EMBED_CEF=OFF. Reconfigure with -DWEBFRONT_EMBED_CEF=ON to use the embedded CEF frontend.")); - requireThrows([&] { frontend::CEFFrontend::open("127.0.0.1", "9200", "index.html", ContentPolicy{}); }); - }); - } -}}; + requireThrows([&] { + frontend::CEFFrontend::open("127.0.0.1", "9200", "index.html", ContentPolicy{}); + }); + }); + } + }}; const Scenario cEFSubprocess{"CEF subprocess exits preserve their status and diagnostic", [] { - then("a subprocess that completed successfully propagates its status, and a failed one its status and the exit request", [&] { - require(cef::CEFSubprocessExit{0}.exit_code() == 0); - const cef::CEFSubprocessExit failed{7}; - require(failed.exit_code() == 7); - require(std::string_view(failed.what()) == "CEF subprocess should exit"); - }); -}}; + then("a subprocess that completed successfully propagates its status, and a failed one its status and the exit request", [&] { + require(cef::CEFSubprocessExit{0}.exit_code() == 0); + const cef::CEFSubprocessExit failed{7}; + require(failed.exit_code() == 7); + require(std::string_view(failed.what()) == "CEF subprocess should exit"); + }); + }}; const Scenario frontendInitialized{"A frontend is initialized once per process, and a failed initialization is retried", [] { - given("two BasicWF instances sharing the same frontend type", [&] { - using FrontendWF = BasicWFWithFrontend; - FrontendWF first("8080"); - FrontendWF second("8081"); - then("the frontend initialization runs only once", [&] { - require(InitializingFrontend::initializeCalls == 1); - }); - }); - given("a frontend whose first initialization fails", [&] { - using App = BasicWFWithFrontend; - using OtherApp = BasicWFWithFrontend; - when("construction is retried and another application type uses the frontend", [&] { - then("construction propagates the error, retries once, and reuses successful initialization", [&] { - requireThrows([&] { App("9200"); }, equals("frontend initialization failed")); - require(RetryingFrontend::initializeCalls == 1); - App retry("9201"); - require(RetryingFrontend::initializeCalls == 2); - OtherApp other("9202"); - require(RetryingFrontend::initializeCalls == 2); - }); - }); - }); -}}; + given("two BasicWF instances sharing the same frontend type", [&] { + using FrontendWF = BasicWFWithFrontend; + FrontendWF first("8080"); + FrontendWF second("8081"); + then("the frontend initialization runs only once", [&] { + require(InitializingFrontend::initializeCalls == 1); + }); + }); + given("a frontend whose first initialization fails", [&] { + using App = BasicWFWithFrontend; + using OtherApp = BasicWFWithFrontend; + when("construction is retried and another application type uses the frontend", [&] { + then("construction propagates the error, retries once, and reuses successful initialization", [&] { + requireThrows( + [&] { + App("9200"); + }, + equals("frontend initialization failed")); + require(RetryingFrontend::initializeCalls == 1); + App retry("9201"); + require(RetryingFrontend::initializeCalls == 2); + OtherApp other("9202"); + require(RetryingFrontend::initializeCalls == 2); + }); + }); + }); + }}; const Scenario frontendContract{"The frontend contract: a failing open() stops the server before propagating, whatever its action", [] { - given("an embedded frontend that fails to open", [&] { - using App = BasicWFWithFrontend; - App app("9200"); - const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); - then("show requests server shutdown before propagating the diagnostic", [&] { - requireThrows([&] { app.show(); }, equals("frontend startup failed")); - require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); - }); - }); - given("a frontend that only launches an external program and fails to do so", [&] { - using App = BasicWFWithFrontend; - App app("9202"); - const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); - then("the exception propagates and the server is stopped", [&] { - requireThrows([&] { app.show(); }, equals("launcher failed")); - require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); - }); - }); -}}; + given("an embedded frontend that fails to open", [&] { + using App = BasicWFWithFrontend; + App app("9200"); + const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); + then("show requests server shutdown before propagating the diagnostic", [&] { + requireThrows( + [&] { + app.show(); + }, + equals("frontend startup failed")); + require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); + }); + }); + given("a frontend that only launches an external program and fails to do so", [&] { + using App = BasicWFWithFrontend; + App app("9202"); + const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); + then("the exception propagates and the server is stopped", [&] { + requireThrows( + [&] { + app.show(); + }, + equals("launcher failed")); + require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); + }); + }); + }}; const Scenario frontendContractThread{"The frontend contract: open() runs on the calling thread and a closing frontend stops the server", [] { - given("an embedded frontend that records the thread it is opened on", [&] { - using App = BasicWFWithFrontend; - App app("9201"); - const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); - when("the application shows the interface", [&] { - app.show(); - then("open() ran on the thread that called show(), not on the server thread", [&] { - require(ThreadRecordingFrontend::openThread == std::this_thread::get_id()); - }); - then("show() returned after the server was asked to stop", [&] { - require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); - }); - }); - }); -}}; + given("an embedded frontend that records the thread it is opened on", [&] { + using App = BasicWFWithFrontend; + App app("9201"); + const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); + when("the application shows the interface", [&] { + app.show(); + then("open() ran on the thread that called show(), not on the server thread", [&] { + require(ThreadRecordingFrontend::openThread == std::this_thread::get_id()); + }); + then("show() returned after the server was asked to stop", [&] { + require(WebFrontIoContextMock::stopCalls.load() > previousStopCalls); + }); + }); + }); + }}; struct FallbackNativeWindow { - static inline bool displayAvailable = true; - static inline int openCalls = 0; + static inline bool displayAvailable = true; + static inline int openCalls = 0; static constexpr frontend::Action action{frontend::Action::closeServerAfterOpen}; - static void initialize() { + static void initialize() { if (!displayAvailable) throw std::runtime_error("cannot open a display; set DISPLAY or WAYLAND_DISPLAY"); } - static void open(std::string_view, std::string_view) { ++openCalls; } + static void open(std::string_view, std::string_view) { + ++openCalls; + } }; struct FallbackBrowser { - static inline int initializeCalls = 0; - static inline int openCalls = 0; + static inline int initializeCalls = 0; + static inline int openCalls = 0; static constexpr frontend::Action action{frontend::Action::keepServerRunning}; - static void initialize() { ++initializeCalls; } - static void open(std::string_view, std::string_view) { ++openCalls; } + static void initialize() { + ++initializeCalls; + } + static void open(std::string_view, std::string_view) { + ++openCalls; + } }; -const Scenario nativeWindowBrowser{"Native window or browser, decided at run time", [] { - using Fallback = frontend::NativeOrBrowserFrontendFor; - static_assert(frontend::FrontendType); - static_assert(frontend::FrontendType); - static_assert(std::is_same_v::FrontendProvider, frontend::NativeOrBrowserFrontend>); - - given("a native window that can open", [&] { - FallbackNativeWindow::displayAvailable = true; - FallbackNativeWindow::openCalls = 0; - FallbackBrowser::openCalls = 0; - FallbackBrowser::initializeCalls = 0; - Fallback::initialize(); - then("the native window is used and closing it stops the server", [&] { - require(FallbackBrowser::initializeCalls == 0); - require(Fallback::usesNativeWindow()); - require(!Fallback::fallbackReason().has_value()); - require(Fallback::closeServerAfterOpen()); - Fallback::open("127.0.0.1", "9200", "index.html"); - require(FallbackNativeWindow::openCalls == 1); - require(FallbackBrowser::openCalls == 0); - }); - }); - given("a session without a display", [&] { - FallbackNativeWindow::displayAvailable = false; - FallbackNativeWindow::openCalls = 0; - FallbackBrowser::openCalls = 0; - FallbackBrowser::initializeCalls = 0; - std::ostringstream captured; - auto* const previous = std::cerr.rdbuf(captured.rdbuf()); - Fallback::initialize(); - std::cerr.rdbuf(previous); - then("the browser is used, the reason is kept and printed, and the server keeps running", [&] { - require(!Fallback::usesNativeWindow()); - require(FallbackBrowser::initializeCalls == 1); - require(Fallback::fallbackReason().value_or("").find("display") != std::string::npos); - require(captured.str().find("opening the system browser instead of a native window") != std::string::npos); - require(!Fallback::closeServerAfterOpen()); - Fallback::open("127.0.0.1", "9200", "index.html"); - require(FallbackNativeWindow::openCalls == 0); - require(FallbackBrowser::openCalls == 1); +const Scenario nativeWindowBrowser{ + "Native window or browser, decided at run time", + [] { + using Fallback = frontend::NativeOrBrowserFrontendFor; + static_assert(frontend::FrontendType); + static_assert(frontend::FrontendType); + static_assert(std::is_same_v::FrontendProvider, frontend::NativeOrBrowserFrontend>); + + given("a native window that can open", [&] { + FallbackNativeWindow::displayAvailable = true; + FallbackNativeWindow::openCalls = 0; + FallbackBrowser::openCalls = 0; + FallbackBrowser::initializeCalls = 0; + Fallback::initialize(); + then("the native window is used and closing it stops the server", [&] { + require(FallbackBrowser::initializeCalls == 0); + require(Fallback::usesNativeWindow()); + require(!Fallback::fallbackReason().has_value()); + require(Fallback::closeServerAfterOpen()); + Fallback::open("127.0.0.1", "9200", "index.html"); + require(FallbackNativeWindow::openCalls == 1); + require(FallbackBrowser::openCalls == 0); + }); }); - then("an application falling back does not stop the server after open()", [&] { - using App = BasicWFWithFrontend; - App app("9203"); - const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); - app.show(); - require(FallbackBrowser::openCalls == 1); - require(WebFrontIoContextMock::stopCalls.load() == previousStopCalls); + given("a session without a display", [&] { + FallbackNativeWindow::displayAvailable = false; + FallbackNativeWindow::openCalls = 0; + FallbackBrowser::openCalls = 0; + FallbackBrowser::initializeCalls = 0; + std::ostringstream captured; + auto* const previous = std::cerr.rdbuf(captured.rdbuf()); + Fallback::initialize(); + std::cerr.rdbuf(previous); + then("the browser is used, the reason is kept and printed, and the server keeps running", [&] { + require(!Fallback::usesNativeWindow()); + require(FallbackBrowser::initializeCalls == 1); + require(Fallback::fallbackReason().value_or("").find("display") != std::string::npos); + require(captured.str().find("opening the system browser instead of a native window") != std::string::npos); + require(!Fallback::closeServerAfterOpen()); + Fallback::open("127.0.0.1", "9200", "index.html"); + require(FallbackNativeWindow::openCalls == 0); + require(FallbackBrowser::openCalls == 1); + }); + then("an application falling back does not stop the server after open()", [&] { + using App = BasicWFWithFrontend; + App app("9203"); + const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); + app.show(); + require(FallbackBrowser::openCalls == 1); + require(WebFrontIoContextMock::stopCalls.load() == previousStopCalls); + }); }); - }); #if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) - given("the real WebKitGTK engine and no DISPLAY or WAYLAND_DISPLAY", [&] { - // A child process: GTK may already be initialized in this one, and the environment must stay untouched. - const pid_t child = fork(); - require(child >= 0); - if (child == 0) { - unsetenv("DISPLAY"); - unsetenv("WAYLAND_DISPLAY"); - std::cerr.rdbuf(nullptr); - frontend::NativeOrBrowserFrontend::initialize(); - const bool fellBack = !frontend::NativeOrBrowserFrontend::usesNativeWindow() - && frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("display") != std::string::npos; - _exit(fellBack ? 0 : 1); - } - int status = 0; - require(waitpid(child, &status, 0) == child); - then("the frontend falls back to the browser and names the missing display", [&] { - require(WIFEXITED(status)); - require(WEXITSTATUS(status) == 0); + given("the real WebKitGTK engine and no DISPLAY or WAYLAND_DISPLAY", [&] { + // A child process: GTK may already be initialized in this one, and the environment must stay untouched. + const pid_t child = fork(); + require(child >= 0); + if (child == 0) { + unsetenv("DISPLAY"); + unsetenv("WAYLAND_DISPLAY"); + std::cerr.rdbuf(nullptr); + frontend::NativeOrBrowserFrontend::initialize(); + const bool fellBack = !frontend::NativeOrBrowserFrontend::usesNativeWindow() + && frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("display") != std::string::npos; + _exit(fellBack ? 0 : 1); + } + int status = 0; + require(waitpid(child, &status, 0) == child); + then("the frontend falls back to the browser and names the missing display", [&] { + require(WIFEXITED(status)); + require(WEXITSTATUS(status) == 0); + }); }); - }); #endif -}}; + }}; const Scenario nativeEngine{"The native engine availability is a constant", [] { - static_assert(std::is_same_v); + static_assert(std::is_same_v); #if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) - static_assert(frontend::nativeWebViewAvailable); + static_assert(frontend::nativeWebViewAvailable); #elif defined(__linux__) static_assert(!(frontend::nativeWebViewAvailable)); then("without an engine the fallback frontend always uses the browser", [&] { @@ -493,298 +568,331 @@ const Scenario nativeEngine{"The native engine availability is a constant", [] { require(frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("WEBFRONT_EMBED_WEBKITGTK") != std::string::npos); }); #endif -}}; + }}; -const Scenario embeddedFrontendDeclared{"The embedded frontend is declared in every configuration", [] { - static_assert(std::is_same_v); +const Scenario embeddedFrontendDeclared{ + "The embedded frontend is declared in every configuration", + [] { + static_assert(std::is_same_v); #ifdef WEBFRONT_EMBED_CEF - static_assert(embeddedFrontendAvailable); - static_assert(std::is_same_v>); + static_assert(embeddedFrontendAvailable); + static_assert(std::is_same_v>); #else - static_assert(embeddedFrontendAvailable == frontend::nativeWebViewAvailable); + static_assert(embeddedFrontendAvailable == frontend::nativeWebViewAvailable); #endif - static_assert(std::is_class_v); - static_assert(std::is_same_v>); - static_assert(frontend::FrontendType); + static_assert(std::is_class_v); + static_assert(std::is_same_v>); + static_assert(frontend::FrontendType); #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) -#ifndef WEBFRONT_EMBED_CEF - static_assert(std::is_same_v == embeddedFrontendAvailable); -#endif + #ifndef WEBFRONT_EMBED_CEF + static_assert(std::is_same_v == embeddedFrontendAvailable); + #endif #endif - if constexpr (!embeddedFrontendAvailable) { - then("constructing it throws std::runtime_error naming the missing engine", [&] { - requireThrows([&] { EmbeddedWebFront{}; }, contains("no embedded web view engine")); - requireThrows([&] { EmbeddedWebFront{}; }); - }); - } -}}; - -const Scenario basicWFDelegates{"BasicWF delegates window opening to the selected frontend", [] { - given("a frontend that keeps the server running after open", [&] { - using FrontendWF = BasicWFWithFrontend; - FrontendWF webFront("8123"); - - when("openWindow is called", [&] { - auto action = webFront.openWindow("index.html"); - - then("the frontend receives the request and keeps the server alive", [&] { - require(action == FrontendWF::WindowAction::none); - require(OpeningFrontend::initializeCalls == 1); - require(OpeningFrontend::openCalls == 1); - require(OpeningFrontend::lastPort == "8123"); - require(OpeningFrontend::lastFile == "index.html"); - }); - }); - }); - - given("a frontend that completes when the window session ends", [&] { - using FrontendWF = BasicWFWithFrontend; - const int previousOpenCalls = ClosingFrontend::openCalls; // other scenarios share this frontend - FrontendWF webFront("9000"); - - when("openWindow is called", [&] { - auto action = webFront.openWindow("react.html"); - - then("BasicWF requests server shutdown after the frontend returns", [&] { - require(action == FrontendWF::WindowAction::closeWindow); - require(ClosingFrontend::initializeCalls == 1); - require(ClosingFrontend::openCalls == previousOpenCalls + 1); - require(ClosingFrontend::lastPort == "9000"); - require(ClosingFrontend::lastFile == "react.html"); + if constexpr (!embeddedFrontendAvailable) { + then("constructing it throws std::runtime_error naming the missing engine", [&] { + requireThrows( + [&] { + EmbeddedWebFront{}; + }, + contains("no embedded web view engine")); + requireThrows([&] { + EmbeddedWebFront{}; + }); }); - }); - }); + } + }}; - given("a frontend that takes the configured address", [&] { - using App = BasicWFWithFrontend; - App app{WebFrontConfig{.address = "127.0.0.2", .port = "9010"}}; - app.openWindow("index.html?x=1#result"); - then("it receives the address, the port and the page with its query and fragment", [&] { - require(AddressFrontend::lastAddress == "127.0.0.2"); - require(AddressFrontend::lastPort == "9010"); - require(AddressFrontend::lastFile == "index.html?x=1#result"); - }); - }); -}}; +const Scenario basicWFDelegates{"BasicWF delegates window opening to the selected frontend", [] { + given("a frontend that keeps the server running after open", [&] { + using FrontendWF = BasicWFWithFrontend; + FrontendWF webFront("8123"); + + when("openWindow is called", [&] { + auto action = webFront.openWindow("index.html"); + + then("the frontend receives the request and keeps the server alive", [&] { + require(action == FrontendWF::WindowAction::none); + require(OpeningFrontend::initializeCalls == 1); + require(OpeningFrontend::openCalls == 1); + require(OpeningFrontend::lastPort == "8123"); + require(OpeningFrontend::lastFile == "index.html"); + }); + }); + }); + + given("a frontend that completes when the window session ends", [&] { + using FrontendWF = BasicWFWithFrontend; + const int previousOpenCalls = ClosingFrontend::openCalls; // other scenarios share this frontend + FrontendWF webFront("9000"); + + when("openWindow is called", [&] { + auto action = webFront.openWindow("react.html"); + + then("BasicWF requests server shutdown after the frontend returns", [&] { + require(action == FrontendWF::WindowAction::closeWindow); + require(ClosingFrontend::initializeCalls == 1); + require(ClosingFrontend::openCalls == previousOpenCalls + 1); + require(ClosingFrontend::lastPort == "9000"); + require(ClosingFrontend::lastFile == "react.html"); + }); + }); + }); + + given("a frontend that takes the configured address", [&] { + using App = BasicWFWithFrontend; + App app{ + WebFrontConfig{.address = "127.0.0.2", .port = "9010"} + }; + app.openWindow("index.html?x=1#result"); + then("it receives the address, the port and the page with its query and fragment", [&] { + require(AddressFrontend::lastAddress == "127.0.0.2"); + require(AddressFrontend::lastPort == "9010"); + require(AddressFrontend::lastFile == "index.html?x=1#result"); + }); + }); + }}; const Scenario registeredC{"Registered C++ function handlers own and invoke their callable", [] { - given("handlers created from temporary callables", [&] { - int decodedValue = 0; - using FrontendWF = BasicWFWithFrontend; - FrontendWF webFront("9100"); - auto registeredFunction = [] {}; - webFront.cppFunction("temporary", registeredFunction); - registeredFunction(); - - auto voidHandler = detail::makeCppFunctionHandler( - [&decodedValue](int value) { decodedValue = value; }); - auto returningHandler = detail::makeCppFunctionHandler([] { return 42; }); - - std::array encodedNumber{}; - encodedNumber.front() = static_cast(msg::CodedType::number); - double value = 42.0; - std::memcpy(encodedNumber.data() + 1, &value, sizeof(value)); - - when("the handlers are invoked after registration", [&] { - voidHandler(encodedNumber); - returningHandler(std::span{}); - - then("the stored callables remain valid", [&] { - require(decodedValue == 42); - }); - }); - }); -}}; + given("handlers created from temporary callables", [&] { + int decodedValue = 0; + using FrontendWF = BasicWFWithFrontend; + FrontendWF webFront("9100"); + auto registeredFunction = [] {}; + webFront.cppFunction("temporary", registeredFunction); + registeredFunction(); + + auto voidHandler = detail::makeCppFunctionHandler([&decodedValue](int value) { + decodedValue = value; + }); + auto returningHandler = detail::makeCppFunctionHandler([] { + return 42; + }); + + std::array encodedNumber{}; + encodedNumber.front() = static_cast(msg::CodedType::number); + double value = 42.0; + std::memcpy(encodedNumber.data() + 1, &value, sizeof(value)); + + when("the handlers are invoked after registration", [&] { + voidHandler(encodedNumber); + returningHandler(std::span{}); + + then("the stored callables remain valid", [&] { + require(decodedValue == 42); + }); + }); + }); + }}; const Scenario applicationServes{"An application that serves a document root is told the development path once", [] { - using FrontendWF = BasicWFWithFrontend; - std::ostringstream captured; - struct Redirect { - explicit Redirect(std::ostream& out) { - detail::developmentPathOutput = &out; - detail::developmentPathNoted.clear(); - } - ~Redirect() { detail::developmentPathOutput = nullptr; } - } const redirect{captured}; - const auto notes = [&captured] { - std::size_t count = 0; - const auto text = captured.str(); - for (auto at = text.find(detail::developmentPathNote); at != std::string::npos; at = text.find(detail::developmentPathNote, at + 1)) - ++count; - return count; - }; - given("an application without a document root", [&] { - FrontendWF webFront; - when("it is shown", [&] { - webFront.show(); - then("nothing is said", [&] { - require(captured.str().empty()); - }); - }); - }); - given("two applications that serve a document root", [&] { - FrontendWF first(WebFrontConfig{.documentRoot = "web"}); - FrontendWF second(WebFrontConfig{.port = "9003", .documentRoot = "web"}); - when("both are shown, one of them twice", [&] { - first.show(); - first.show(); - second.show(); - then("the process names ui/, wf dev and the agent guide exactly once", [&] { - require(notes() == 1); - require(captured.str(), contains("TypeScript/TSX interface in ui/")); - require(captured.str(), contains("`wf dev`")); - require(captured.str(), contains("docs/DEVELOPING_WITH_AGENTS.md")); - }); - }); - }); -}}; + using FrontendWF = BasicWFWithFrontend; + std::ostringstream captured; + struct Redirect { + explicit Redirect(std::ostream& out) { + detail::developmentPathOutput = &out; + detail::developmentPathNoted.clear(); + } + ~Redirect() { + detail::developmentPathOutput = nullptr; + } + } const redirect{captured}; + const auto notes = [&captured] { + std::size_t count = 0; + const auto text = captured.str(); + for (auto at = text.find(detail::developmentPathNote); at != std::string::npos; + at = text.find(detail::developmentPathNote, at + 1)) + ++count; + return count; + }; + given("an application without a document root", [&] { + FrontendWF webFront; + when("it is shown", [&] { + webFront.show(); + then("nothing is said", [&] { + require(captured.str().empty()); + }); + }); + }); + given("two applications that serve a document root", [&] { + FrontendWF first(WebFrontConfig{.documentRoot = "web"}); + FrontendWF second(WebFrontConfig{.port = "9003", .documentRoot = "web"}); + when("both are shown, one of them twice", [&] { + first.show(); + first.show(); + second.show(); + then("the process names ui/, wf dev and the agent guide exactly once", [&] { + require(notes() == 1); + require(captured.str(), contains("TypeScript/TSX interface in ui/")); + require(captured.str(), contains("`wf dev`")); + require(captured.str(), contains("docs/DEVELOPING_WITH_AGENTS.md")); + }); + }); + }); + }}; const Scenario showOpens{"show opens the default page and returns when the window session ends", [] { - given("a default-constructed application whose frontend completes after open", [&] { - using FrontendWF = BasicWFWithFrontend; - FrontendWF webFront; - const int previousOpenCalls = ClosingFrontend::openCalls; - - when("show is called without arguments", [&] { - webFront.show(); - - then("the default page is opened on the default port", [&] { - require(ClosingFrontend::openCalls == previousOpenCalls + 1); - require(ClosingFrontend::lastPort == "9002"); - require(ClosingFrontend::lastFile == "index.html"); - }); - }); - - when("show is called with a page", [&] { - webFront.show("greeter.html"); + given("a default-constructed application whose frontend completes after open", [&] { + using FrontendWF = BasicWFWithFrontend; + FrontendWF webFront; + const int previousOpenCalls = ClosingFrontend::openCalls; + + when("show is called without arguments", [&] { + webFront.show(); + + then("the default page is opened on the default port", [&] { + require(ClosingFrontend::openCalls == previousOpenCalls + 1); + require(ClosingFrontend::lastPort == "9002"); + require(ClosingFrontend::lastFile == "index.html"); + }); + }); + + when("show is called with a page", [&] { + webFront.show("greeter.html"); + + then("that page is opened", [&] { + require(ClosingFrontend::lastFile == "greeter.html"); + }); + }); + }); + }}; + +const Scenario cppFunctionDeduces{ + "cppFunction deduces a callable's signature from itself", + [] { + then("callable_traits resolves the return type and decayed, owning parameter types", [&] { + auto voidLambda = [](int) {}; + require(std::is_same_v::Return, void>); + require(std::is_same_v::DecayedArgs, std::tuple>); + + auto valueLambda = [](const std::string& text) { + return text + "!"; + }; + require(std::is_same_v::Return, std::string>); + require(std::is_same_v::DecayedArgs, std::tuple>); + + auto mutableLambda = [count = 0](int add) mutable { + return count += add; + }; + require(std::is_same_v::Return, int>); + require(std::is_same_v::DecayedArgs, std::tuple>); + + require(std::is_same_v::Return, int>); + require(std::is_same_v::DecayedArgs, std::tuple>); - then("that page is opened", [&] { - require(ClosingFrontend::lastFile == "greeter.html"); - }); + std::function stdFunction = [](std::string) {}; + require(std::is_same_v::Return, void>); + require(std::is_same_v::DecayedArgs, std::tuple>); }); - }); -}}; - -const Scenario cppFunctionDeduces{"cppFunction deduces a callable's signature from itself", [] { - then("callable_traits resolves the return type and decayed, owning parameter types", [&] { - auto voidLambda = [](int) {}; - require(std::is_same_v::Return, void>); - require(std::is_same_v::DecayedArgs, std::tuple>); - - auto valueLambda = [](const std::string& text) { return text + "!"; }; - require(std::is_same_v::Return, std::string>); - require(std::is_same_v::DecayedArgs, std::tuple>); - - auto mutableLambda = [count = 0](int add) mutable { return count += add; }; - require(std::is_same_v::Return, int>); - require(std::is_same_v::DecayedArgs, std::tuple>); - - require(std::is_same_v::Return, int>); - require(std::is_same_v::DecayedArgs, std::tuple>); - - std::function stdFunction = [](std::string) {}; - require(std::is_same_v::Return, void>); - require(std::is_same_v::DecayedArgs, std::tuple>); - }); -}}; + }}; const Scenario deducedCppFunction{"Deduced cppFunction registration accepts common callable kinds", [] { - given("a WebFront instance", [&] { - using FrontendWF = BasicWFWithFrontend; - FrontendWF webFront("9150"); - - when("callables are registered without explicit template arguments", [&] { - int observed = 0; - auto voidLambda = [&observed](int value) { observed = value; }; - webFront.cppFunction("onVoid", voidLambda); - - auto valueLambda = [](const std::string& text) { return text + "!"; }; - webFront.cppFunction("onValue", valueLambda); - - auto mutableLambda = [count = 0](int add) mutable { return count += add; }; - webFront.cppFunction("onMutable", mutableLambda); - - webFront.cppFunction("onFreeFunction", &freeFunctionForDeductionTest); - - std::function stdFunction = [](std::string) {}; - webFront.cppFunction("onStdFunction", stdFunction); - - then("registration compiles and the original callables remain usable", [&] { - voidLambda(7); - require(observed == 7); - require(valueLambda("hi") == "hi!"); - }); - }); - }); -}}; + given("a WebFront instance", [&] { + using FrontendWF = BasicWFWithFrontend; + FrontendWF webFront("9150"); + + when("callables are registered without explicit template arguments", [&] { + int observed = 0; + auto voidLambda = [&observed](int value) { + observed = value; + }; + webFront.cppFunction("onVoid", voidLambda); + + auto valueLambda = [](const std::string& text) { + return text + "!"; + }; + webFront.cppFunction("onValue", valueLambda); + + auto mutableLambda = [count = 0](int add) mutable { + return count += add; + }; + webFront.cppFunction("onMutable", mutableLambda); + + webFront.cppFunction("onFreeFunction", &freeFunctionForDeductionTest); + + std::function stdFunction = [](std::string) {}; + webFront.cppFunction("onStdFunction", stdFunction); + + then("registration compiles and the original callables remain usable", [&] { + voidLambda(7); + require(observed == 7); + require(valueLambda("hi") == "hi!"); + }); + }); + }); + }}; const Scenario cFunction{"C++ function responders encode values and failures", [] { - using Policy = http::DefaultBuffersPolicy; - using Net = networking::NetworkingMock; - - given("a successful result", [&] { - ResultLinkMock link; - auto responder = detail::makeCppFunctionResponder( - [](std::span) { return std::string{"answer"}; }); - responder({}, link, 42); - - auto result = msg::FunctionReturn::castFromRawData(link.message); - auto payload = result->payload(); - std::string value; - result->decodeParameter(value, payload); - - then("the correlated value is returned", [&] { - require(result->getCallId() == 42); - require(value == "answer"); - require(payload.empty()); - }); - }); - - given("a standard exception", [&] { - ResultLinkMock link; - auto responder = detail::makeCppFunctionResponder( - [](std::span) { throw std::runtime_error("callback failed"); }); - responder({}, link, 7); - - auto result = msg::FunctionReturn::castFromRawData(link.message); - auto payload = result->payload(); - std::string message; - result->decodeParameter(message, payload); - - then("its useful message is encoded", [&] { - require(message == "callback failed"); - }); - }); - - given("a non-standard exception", [&] { - ResultLinkMock link; - auto responder = detail::makeCppFunctionResponder( - [](std::span) { throw 42; }); - responder({}, link, 8); - - auto result = msg::FunctionReturn::castFromRawData(link.message); - auto payload = result->payload(); - std::string message; - result->decodeParameter(message, payload); - - then("a stable fallback message is encoded", [&] { - require(message == "Unknown C++ exception"); - }); - }); - - given("a fire-and-forget call", [&] { - ResultLinkMock link; - bool called = false; - auto responder = detail::makeCppFunctionResponder( - [&called](std::span) { called = true; }); - responder({}, link, 0); - - then("the callback runs without sending a result", [&] { - require(called); - require(link.message.empty()); - }); - }); -}}; + using Policy = http::DefaultBuffersPolicy; + using Net = networking::NetworkingMock; + + given("a successful result", [&] { + ResultLinkMock link; + auto responder = detail::makeCppFunctionResponder([](std::span) { + return std::string{"answer"}; + }); + responder({}, link, 42); + + auto result = msg::FunctionReturn::castFromRawData(link.message); + auto payload = result->payload(); + std::string value; + result->decodeParameter(value, payload); + + then("the correlated value is returned", [&] { + require(result->getCallId() == 42); + require(value == "answer"); + require(payload.empty()); + }); + }); + + given("a standard exception", [&] { + ResultLinkMock link; + auto responder = detail::makeCppFunctionResponder([](std::span) { + throw std::runtime_error("callback failed"); + }); + responder({}, link, 7); + + auto result = msg::FunctionReturn::castFromRawData(link.message); + auto payload = result->payload(); + std::string message; + result->decodeParameter(message, payload); + + then("its useful message is encoded", [&] { + require(message == "callback failed"); + }); + }); + + given("a non-standard exception", [&] { + ResultLinkMock link; + auto responder = detail::makeCppFunctionResponder([](std::span) { + throw 42; + }); + responder({}, link, 8); + + auto result = msg::FunctionReturn::castFromRawData(link.message); + auto payload = result->payload(); + std::string message; + result->decodeParameter(message, payload); + + then("a stable fallback message is encoded", [&] { + require(message == "Unknown C++ exception"); + }); + }); + + given("a fire-and-forget call", [&] { + ResultLinkMock link; + bool called = false; + auto responder = detail::makeCppFunctionResponder([&called](std::span) { + called = true; + }); + responder({}, link, 0); + + then("the callback runs without sending a result", [&] { + require(called); + require(link.message.empty()); + }); + }); + }}; namespace { @@ -822,79 +930,92 @@ std::pair sentException(std::function thrower) return 0; }); responder({}, link, 9); - auto result = msg::FunctionReturn::castFromRawData(link.message); - auto payload = result->payload(); - std::string code, message; + auto result = msg::FunctionReturn::castFromRawData(link.message); + auto payload = result->payload(); + std::string code, message; msg::FunctionReturn::decodeException(code, message, payload); return {code, message}; } } // namespace const Scenario callbackFailure{"A callback failure is sent with its code", [] { - given("a callback throwing a BridgeError", [&] { - then("the rejection carries its code", [&] { - require(sentException([] { throw BridgeError("denied", "no"); }) == std::pair{"denied", "no"}); - }); - }); - given("a callback throwing an ordinary exception or something else", [&] { - then("the code is the generic one", [&] { - require(sentException([] { throw std::runtime_error("plain"); }) == std::pair{std::string(bridge_code::generic), "plain"}); - require(sentException([] { throw 42; }).first == bridge_code::generic); - }); - }); - given("a callback whose message exceeds what a small policy leaves", [&] { - using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 64>; - then("the rejection is still sent, with the message cut to fit", [&] { - const auto [code, message] = sentException([] { throw BridgeError("quota", std::string(1000, 'x')); }); - require(code == "quota"); - require(message == std::string(64 - 8 - 2 - 5 - 2, 'x')); - }); - then("a multi-byte character is never cut in two", [&] { - std::string text; - for (int i = 0; i < 500; ++i) - text += "\xc3\xa9"; - const auto message = sentException([text] { throw BridgeError("quota", text); }).second; - require(message.size() == 46); // 47 bytes fit, the 24th character would need the 48th - require(message == text.substr(0, 46)); - }); - }); - given("a callback whose argument cannot be decoded", [&] { - ResultLinkMock link; - auto handler = detail::makeCppFunctionHandler([](std::string) {}); - const std::array boolean{std::byte{static_cast(msg::CodedType::booleanTrue)}}; - then("the failure has the malformed code", [&] { - try { - handler(boolean); - fail("The call did not throw"); - } catch (const BridgeError& error) { - require(error.code() == bridge_code::malformed); - } - }); - }); -}}; + given("a callback throwing a BridgeError", [&] { + then("the rejection carries its code", [&] { + require(sentException([] { + throw BridgeError("denied", "no"); + }) + == std::pair{"denied", "no"}); + }); + }); + given("a callback throwing an ordinary exception or something else", [&] { + then("the code is the generic one", [&] { + require(sentException([] { + throw std::runtime_error("plain"); + }) + == std::pair{std::string(bridge_code::generic), "plain"}); + require(sentException([] { + throw 42; + }).first + == bridge_code::generic); + }); + }); + given("a callback whose message exceeds what a small policy leaves", [&] { + using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 64>; + then("the rejection is still sent, with the message cut to fit", [&] { + const auto [code, message] = sentException([] { + throw BridgeError("quota", std::string(1000, 'x')); + }); + require(code == "quota"); + require(message == std::string(64 - 8 - 2 - 5 - 2, 'x')); + }); + then("a multi-byte character is never cut in two", [&] { + std::string text; + for (int i = 0; i < 500; ++i) + text += "\xc3\xa9"; + const auto message = sentException([text] { + throw BridgeError("quota", text); + }).second; + require(message.size() == 46); // 47 bytes fit, the 24th character would need the 48th + require(message == text.substr(0, 46)); + }); + }); + given("a callback whose argument cannot be decoded", [&] { + ResultLinkMock link; + auto handler = detail::makeCppFunctionHandler([](std::string) {}); + const std::array boolean{std::byte{static_cast(msg::CodedType::booleanTrue)}}; + then("the failure has the malformed code", [&] { + try { + handler(boolean); + fail("The call did not throw"); + } catch (const BridgeError& error) { + require(error.code() == bridge_code::malformed); + } + }); + }); + }}; const Scenario cString{"C++ string results cross the bridge up to the message size of the policy", [] { - const std::string longText(100000, 'x'); - using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024 * 1024>; - const std::string overlong(1024 * 1024, 'x'); - const std::string tooLong = "WebFront message exceeds the maximum message size of the buffers policy"; - - given("a callback returning a string of more than 65535 bytes", [&] { - then("it is sent whole as a longString", [&] { - require(respondWith(longText) == longText); - }); - }); - given("a callback returning a string that does not fit the message size of the policy", [&] { - then("a single well-formed exception is sent", [&] { - require(respondWith(overlong) == tooLong); - }); - }); - given("a callback returning such a string inside a tuple", [&] { - then("the partly encoded result is replaced by a single well-formed exception", [&] { - require(respondWith, SmallPolicy>(std::tuple{1, overlong}) == tooLong); - }); - }); -}}; + const std::string longText(100000, 'x'); + using SmallPolicy = http::CustomBuffersPolicy<8192, 8192, 32768, 1024 * 1024>; + const std::string overlong(1024 * 1024, 'x'); + const std::string tooLong = "WebFront message exceeds the maximum message size of the buffers policy"; + + given("a callback returning a string of more than 65535 bytes", [&] { + then("it is sent whole as a longString", [&] { + require(respondWith(longText) == longText); + }); + }); + given("a callback returning a string that does not fit the message size of the policy", [&] { + then("a single well-formed exception is sent", [&] { + require(respondWith(overlong) == tooLong); + }); + }); + given("a callback returning such a string inside a tuple", [&] { + then("the partly encoded result is replaced by a single well-formed exception", [&] { + require(respondWith, SmallPolicy>(std::tuple{1, overlong}) == tooLong); + }); + }); + }}; namespace { @@ -913,45 +1034,46 @@ std::vector smallStringData(std::string_view text) { } // namespace const Scenario cCallback{"A C++ callback can receive the browser that called it", [] { - using Policy = http::DefaultBuffersPolicy; - - given("a handler whose callable takes the caller before its JavaScript parameters", [&] { - auto handler = detail::makeCppFunctionHandler([](const CallerMock& caller, const std::string& text) { - return std::to_string(caller.id) + ":" + text; - }); - const auto data = smallStringData("hi"); - - then("the caller is passed first and only the remaining parameters are decoded", [&] { - require(handler(data, CallerMock{3}) == "3:hi"); - }); - }); - given("a callable taking the caller by mutable reference, adapted to its declared type", [&] { - auto handler = detail::makeCppFunctionHandler( - detail::adaptCaller([](CallerMock& caller, const std::string& text) { - caller.id += 1; - return std::to_string(caller.id) + ":" + text; - })); - CallerMock caller{3}; - const auto data = smallStringData("hi"); - - then("it receives the caller itself", [&] { - require(handler(data, caller) == "4:hi"); - require(caller.id == 4); - }); - }); - given("a responder for such a handler", [&] { - ResultLinkMock link; - auto handler = detail::makeCppFunctionHandler([](CallerMock caller) { - return std::to_string(caller.id); - }); - auto responder = detail::makeCppFunctionResponder(std::move(handler)); - responder({}, link, 5, CallerMock{11}); - - then("the caller reaches the callable and the result is returned", [&] { - require(sentString(link) == "11"); - }); - }); -}}; + using Policy = http::DefaultBuffersPolicy; + + given("a handler whose callable takes the caller before its JavaScript parameters", [&] { + auto handler = detail::makeCppFunctionHandler( + [](const CallerMock& caller, const std::string& text) { + return std::to_string(caller.id) + ":" + text; + }); + const auto data = smallStringData("hi"); + + then("the caller is passed first and only the remaining parameters are decoded", [&] { + require(handler(data, CallerMock{3}) == "3:hi"); + }); + }); + given("a callable taking the caller by mutable reference, adapted to its declared type", [&] { + auto handler = detail::makeCppFunctionHandler( + detail::adaptCaller([](CallerMock& caller, const std::string& text) { + caller.id += 1; + return std::to_string(caller.id) + ":" + text; + })); + CallerMock caller{3}; + const auto data = smallStringData("hi"); + + then("it receives the caller itself", [&] { + require(handler(data, caller) == "4:hi"); + require(caller.id == 4); + }); + }); + given("a responder for such a handler", [&] { + ResultLinkMock link; + auto handler = detail::makeCppFunctionHandler([](CallerMock caller) { + return std::to_string(caller.id); + }); + auto responder = detail::makeCppFunctionResponder(std::move(handler)); + responder({}, link, 5, CallerMock{11}); + + then("the caller reaches the callable and the result is returned", [&] { + require(sentString(link) == "11"); + }); + }); + }}; // Only a first parameter of the application's UI type, with any reference or const, is the caller. using CallerTestUI = BasicWFWithFrontend::UI; @@ -961,76 +1083,94 @@ static_assert(!detail::takes_caller::va static_assert(!detail::takes_caller::value); const Scenario uIFirst{"A UI first parameter selects the caller form of cppFunction", [] { - using FrontendWF = BasicWFWithFrontend; - using AppUI = FrontendWF::UI; - - given("an application", [&] { - FrontendWF webFront("9161"); - then("the caller may be taken by value or by const reference", [&] { - requireNothrow([&] { webFront.cppFunction("byValue", [](AppUI) {}); }); - requireNothrow([&] { webFront.cppFunction("byConstReference", [](const AppUI&) {}); }); - }); - then("the caller may be taken by mutable or rvalue reference", [&] { - requireNothrow([&] { webFront.cppFunction("byReference", [](AppUI&) {}); }); - requireNothrow([&] { webFront.cppFunction("byRvalueReference", [](AppUI&&) {}); }); - }); - then("caller callbacks register through deduction and explicit types", [&] { - requireNothrow([&] { webFront.cppFunction("deduced", [](AppUI, std::string) {}); }); - requireNothrow([&] { webFront.template cppFunction("explicit", [](const AppUI&, double) { - return 1; - }); }); - }); - then("browser subscriptions can be taken, and released after the application", [&] { - UISubscription subscription; - { - FrontendWF scoped("9162"); - subscription = scoped.subscribeUIStarted([](AppUI) {}); - require(subscription.active()); - } - requireNothrow([&] { subscription.reset(); }); - }); - }); -}}; + using FrontendWF = BasicWFWithFrontend; + using AppUI = FrontendWF::UI; + + given("an application", [&] { + FrontendWF webFront("9161"); + then("the caller may be taken by value or by const reference", [&] { + requireNothrow([&] { + webFront.cppFunction("byValue", [](AppUI) {}); + }); + requireNothrow([&] { + webFront.cppFunction("byConstReference", [](const AppUI&) {}); + }); + }); + then("the caller may be taken by mutable or rvalue reference", [&] { + requireNothrow([&] { + webFront.cppFunction("byReference", [](AppUI&) {}); + }); + requireNothrow([&] { + webFront.cppFunction("byRvalueReference", [](AppUI&&) {}); + }); + }); + then("caller callbacks register through deduction and explicit types", [&] { + requireNothrow([&] { + webFront.cppFunction("deduced", [](AppUI, std::string) {}); + }); + requireNothrow([&] { + webFront.template cppFunction("explicit", [](const AppUI&, double) { + return 1; + }); + }); + }); + then("browser subscriptions can be taken, and released after the application", [&] { + UISubscription subscription; + { + FrontendWF scoped("9162"); + subscription = scoped.subscribeUIStarted([](AppUI) {}); + require(subscription.active()); + } + requireNothrow([&] { + subscription.reset(); + }); + }); + }); + }}; const Scenario webFrontConfigHas{"WebFrontConfig has newcomer-friendly defaults", [] { - then("the defaults are loopback binding, an empty port (9002, else a free one), and no local document root", [&] { - WebFrontConfig config; - require(config.address == "127.0.0.1"); - require(config.port.empty()); - require(config.documentRoot.empty()); - }); -}}; + then("the defaults are loopback binding, an empty port (9002, else a free one), and no local document root", [&] { + WebFrontConfig config; + require(config.address == "127.0.0.1"); + require(config.port.empty()); + require(config.documentRoot.empty()); + }); + }}; const Scenario basicWFSupports{"BasicWF supports default construction", [] { - given("a frontend and networking mock", [&] { - when("a BasicWF is default-constructed", [&] { - using DefaultCtorWF = BasicWFWithFrontend; - then("construction succeeds without specifying port, root, page, frontend, or callbacks", [&] { - requireNothrow([&] { DefaultCtorWF{}; }); - }); - }); - }); -}}; + given("a frontend and networking mock", [&] { + when("a BasicWF is default-constructed", [&] { + using DefaultCtorWF = BasicWFWithFrontend; + then("construction succeeds without specifying port, root, page, frontend, or callbacks", [&] { + requireNothrow([&] { + DefaultCtorWF{}; + }); + }); + }); + }); + }}; const Scenario basicWFDoes{"BasicWF does not require onUIStarted to be set", [] { - // Note: this exercises construction/registration/teardown without onUIStarted. The guarded - // dispatch itself - onEvent's `if (uiStartedHandler) uiStartedHandler(...)` for the `linked` - // event - would need a full HTTP-upgrade-then-WebSocket-handshake simulation through the mock - // networking stack to exercise end-to-end; that infrastructure doesn't exist yet in this test - // suite, so this guard is otherwise verified by inspection (a plain std::function truthiness - // check around the call). - given("a BasicWF that never registers onUIStarted", [&] { - using FrontendWF = BasicWFWithFrontend; - when("it is constructed and used", [&] { - then("nothing throws", [&] { - requireNothrow([&] { [] { - FrontendWF webFront("9160"); - webFront.cppFunction("noop", [] {}); - }(); }); - }); - }); - }); -}}; + // Note: this exercises construction/registration/teardown without onUIStarted. The guarded + // dispatch itself - onEvent's `if (uiStartedHandler) uiStartedHandler(...)` for the `linked` + // event - would need a full HTTP-upgrade-then-WebSocket-handshake simulation through the mock + // networking stack to exercise end-to-end; that infrastructure doesn't exist yet in this test + // suite, so this guard is otherwise verified by inspection (a plain std::function truthiness + // check around the call). + given("a BasicWF that never registers onUIStarted", [&] { + using FrontendWF = BasicWFWithFrontend; + when("it is constructed and used", [&] { + then("nothing throws", [&] { + requireNothrow([&] { + [] { + FrontendWF webFront("9160"); + webFront.cppFunction("noop", [] {}); + }(); + }); + }); + }); + }); + }}; namespace { // Preserve the legacy empty-options call despite the new ContentPolicy overload. @@ -1040,7 +1180,7 @@ struct PolicyFrontend { static constexpr frontend::Action action{frontend::Action::keepServerRunning}; static inline ContentPolicy received; static inline std::string receivedAddress; - static void initialize() { } + static void initialize() {} static void open(std::string_view, std::string_view) { throw std::runtime_error("Legacy overload selected"); } @@ -1051,107 +1191,128 @@ struct PolicyFrontend { }; } // namespace -const Scenario webFrontPasses{"WebFront passes per-application content rules to policy-aware frontends", [] { - using App = BasicWFWithFrontend; - App app(WebFrontConfig{ - .address = "127.0.0.2", - .contentPolicy = {.navigationAllowedOrigins = {"https://docs.example"}, .popups = PopupPolicy::systemBrowser, .devToolsEnabled = false} - }); - requireNothrow([&] { app.openWindow("index.html"); }); - then("the configured address reaches the preferred overload", [&] { - require(PolicyFrontend::receivedAddress == "127.0.0.2"); - }); - then("the navigation allow-list is preserved", [&] { - require(PolicyFrontend::received.navigationAllowedOrigins == std::vector{"https://docs.example"}); - }); - then("popup and DevTools settings are preserved independently", [&] { - require(PolicyFrontend::received.popups == PopupPolicy::systemBrowser); - require(!PolicyFrontend::received.devToolsEnabled); - }); -}}; +const Scenario webFrontPasses{ + "WebFront passes per-application content rules to policy-aware frontends", + [] { + using App = BasicWFWithFrontend; + App app(WebFrontConfig{ + .address = "127.0.0.2", + .contentPolicy = {.navigationAllowedOrigins = {"https://docs.example"}, .popups = PopupPolicy::systemBrowser, .devToolsEnabled = false} + }); + requireNothrow([&] { + app.openWindow("index.html"); + }); + then("the configured address reaches the preferred overload", [&] { + require(PolicyFrontend::receivedAddress == "127.0.0.2"); + }); + then("the navigation allow-list is preserved", [&] { + require(PolicyFrontend::received.navigationAllowedOrigins == std::vector{"https://docs.example"}); + }); + then("popup and DevTools settings are preserved independently", [&] { + require(PolicyFrontend::received.popups == PopupPolicy::systemBrowser); + require(!PolicyFrontend::received.devToolsEnabled); + }); + }}; const Scenario ephemeralPorts{"Ephemeral ports are bound atomically and forwarded to the frontend", [] { - using App = BasicWFWithFrontend; - App first{WebFrontConfig{.port = "0"}}; - App second{WebFrontConfig{.port = "0"}}; - first.openWindow("index.html"); - const auto firstPort = AddressFrontend::lastPort; - second.openWindow("index.html"); - require(firstPort != "0"); - require(AddressFrontend::lastPort != "0"); - require(firstPort != AddressFrontend::lastPort); - require(std::stoi(firstPort) > 0); - require(std::stoi(AddressFrontend::lastPort) > 0); - require(first.port() == firstPort); - require(second.port() == AddressFrontend::lastPort); - given("a legacy provider without a bound-endpoint query", [&] { - using MockApp = BasicWFWithFrontend; - MockApp mock{WebFrontConfig{.port = "0"}}; - require(mock.port() == "0"); - }); -}}; + using App = BasicWFWithFrontend; + App first{WebFrontConfig{.port = "0"}}; + App second{WebFrontConfig{.port = "0"}}; + first.openWindow("index.html"); + const auto firstPort = AddressFrontend::lastPort; + second.openWindow("index.html"); + require(firstPort != "0"); + require(AddressFrontend::lastPort != "0"); + require(firstPort != AddressFrontend::lastPort); + require(std::stoi(firstPort) > 0); + require(std::stoi(AddressFrontend::lastPort) > 0); + require(first.port() == firstPort); + require(second.port() == AddressFrontend::lastPort); + given("a legacy provider without a bound-endpoint query", [&] { + using MockApp = BasicWFWithFrontend; + MockApp mock{WebFrontConfig{.port = "0"}}; + require(mock.port() == "0"); + }); + }}; const Scenario sendingDOM{"Sending a DOM batch through a lost UI link throws ConnectionError", [] { - using App = BasicWFWithFrontend; - given("a UI handle whose connection is absent from the application", [&] { - App app("9161"); - App::UI ui(app, 42, 1); - msg::DomBatch batch(7); - batch.add({msg::DomOp::text, 1, 0, 0, "unreachable"}); - then("sending fails synchronously without queuing a frame", [&] { - requireThrows([&] { ui.sendDomBatch(batch); }); - require(ui.pendingWrites() == 0); - }); - }); -}}; + using App = BasicWFWithFrontend; + given("a UI handle whose connection is absent from the application", [&] { + App app("9161"); + App::UI ui(app, 42, 1); + msg::DomBatch batch(7); + batch.add({msg::DomOp::text, 1, 0, 0, "unreachable"}); + then("sending fails synchronously without queuing a frame", [&] { + requireThrows([&] { + ui.sendDomBatch(batch); + }); + require(ui.pendingWrites() == 0); + }); + }); + }}; const Scenario uIAssignable{"A UI is an assignable value identifying one browser of one application", [] { - using App = BasicWF; - given("an application over the networking mock", [&] { - App app(WebFrontConfig{.port = "0"}); - then("a UI is an assignable value usable in containers", [&] { - static_assert(std::is_copy_assignable_v); - static_assert(std::is_nothrow_move_assignable_v); - static_assert(std::equality_comparable); - static_assert(!std::is_copy_constructible_v && !std::is_move_constructible_v); - static_assert(!std::is_copy_assignable_v && !std::is_move_assignable_v); - std::vector clients{App::UI(app, 1, 1), App::UI(app, 2, 1), App::UI(app, 3, 1)}; - std::erase_if(clients, [](const App::UI& ui) { return ui.id() == 2; }); - require(clients.size() == 2); - check(clients[0] == App::UI(app, 1, 1)); - check(clients[0] != clients[1]); - check(clients[1].id() == 3); - std::optional current; - current = clients[1]; - check(current->id() == 3); - }); - then("a UI of another application is never equal, even with the same identifier", [&] { - struct Application { } first, second; - using StubUI = BasicUI; - check(StubUI(first, 1, 1) != StubUI(second, 1, 1)); - check(StubUI(first, 1, 1) != StubUI(first, 1, 2)); // same identifier, later connection - StubUI ui(first, 1, 1); - ui = StubUI(second, 1, 1); - check(ui == StubUI(second, 1, 1)); - }); - then("a UI has no default state and a reassigned one acts on its new value", [&] { - static_assert(!std::is_default_constructible_v); - App::UI ui(app, 1, 1); - const App::UI gone(app, 42, 1); - ui = gone; - check(ui == gone); - checkThrows([&] { ui.addScript("1"); }); - check(ui.pendingWrites() == 0); - checkNothrow([&] { ui.jsFunction("console.log")("dropped"); }); - auto result = ui.jsFunction("Math.abs")(-1); - checkThrows([&] { (void)result.get(); }, equals("Browser connection closed")); - checkNothrow([&] { (void)ui.writesAtMost(0); }); - App::UI moved(std::move(ui)); - check(moved.id() == 42); - checkThrows([&] { moved.addScript("1"); }); - }); - }); -}}; + using App = BasicWF; + given("an application over the networking mock", [&] { + App app(WebFrontConfig{.port = "0"}); + then("a UI is an assignable value usable in containers", [&] { + static_assert(std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_assignable_v); + static_assert(std::equality_comparable); + static_assert(!std::is_copy_constructible_v && !std::is_move_constructible_v); + static_assert(!std::is_copy_assignable_v && !std::is_move_assignable_v); + std::vector clients{App::UI(app, 1, 1), App::UI(app, 2, 1), App::UI(app, 3, 1)}; + std::erase_if(clients, [](const App::UI& ui) { + return ui.id() == 2; + }); + require(clients.size() == 2); + check(clients[0] == App::UI(app, 1, 1)); + check(clients[0] != clients[1]); + check(clients[1].id() == 3); + std::optional current; + current = clients[1]; + check(current->id() == 3); + }); + then("a UI of another application is never equal, even with the same identifier", [&] { + struct Application { + } first, second; + using StubUI = BasicUI; + check(StubUI(first, 1, 1) != StubUI(second, 1, 1)); + check(StubUI(first, 1, 1) != StubUI(first, 1, 2)); // same identifier, later connection + StubUI ui(first, 1, 1); + ui = StubUI(second, 1, 1); + check(ui == StubUI(second, 1, 1)); + }); + then("a UI has no default state and a reassigned one acts on its new value", [&] { + static_assert(!std::is_default_constructible_v); + App::UI ui(app, 1, 1); + const App::UI gone(app, 42, 1); + ui = gone; + check(ui == gone); + checkThrows([&] { + ui.addScript("1"); + }); + check(ui.pendingWrites() == 0); + checkNothrow([&] { + ui.jsFunction("console.log")("dropped"); + }); + auto result = ui.jsFunction("Math.abs")(-1); + checkThrows( + [&] { + (void)result.get(); + }, + equals("Browser connection closed")); + checkNothrow([&] { + (void)ui.writesAtMost(0); + }); + App::UI moved(std::move(ui)); + check(moved.id() == 42); + checkThrows([&] { + moved.addScript("1"); + }); + }); + }); + }}; namespace { struct DomNoTimerNet : testing::InjectableNetworking { @@ -1167,31 +1328,33 @@ struct DomNoTimerNet : testing::InjectableNetworking { } // namespace const Scenario dOMReadiness{"DOM readiness explains a missing network timer while the ordinary bridge remains usable", {"dom"}, [] { - using Socket = testing::InjectableSocket; - Socket::reset(); - DomNoTimerNet::accepted = false; - BasicWF app{WebFrontConfig{.port = "0"}}; - app.cppFunction("echo", [] { - return std::string{"bridge stays available"}; - }); - const std::string upgrade = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; - Socket::receive(std::as_bytes(std::span(upgrade))); - msg::Handshake handshake; - Socket::receive(testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); - require(app.connectedBrowsers() == 1); - auto call = [](std::string name, msg::CallId id) { - msg::FunctionCall<> message; - message.setCallId(id); - websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; - message.encodeParameter(name, frame); - frame.freeze(); - Socket::receive(testing::clientFrame(testing::messagePayload(frame))); - }; - call("wfDom.ready", 21); - require(Socket::wrote("DOM API requires Net::ResumeAfter")); - call("echo", 22); - require(Socket::wrote("bridge stays available")); - require(app.connectedBrowsers() == 1); - app.shutdown(); -}}; + using Socket = testing::InjectableSocket; + Socket::reset(); + DomNoTimerNet::accepted = false; + BasicWF app{WebFrontConfig{.port = "0"}}; + app.cppFunction("echo", [] { + return std::string{"bridge stays available"}; + }); + const std::string upgrade = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + Socket::receive(std::as_bytes(std::span(upgrade))); + msg::Handshake handshake; + Socket::receive( + testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + require(app.connectedBrowsers() == 1); + auto call = [](std::string name, msg::CallId id) { + msg::FunctionCall<> message; + message.setCallId(id); + websocket::Frame frame{ + std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + frame.freeze(); + Socket::receive(testing::clientFrame(testing::messagePayload(frame))); + }; + call("wfDom.ready", 21); + require(Socket::wrote("DOM API requires Net::ResumeAfter")); + call("echo", 22); + require(Socket::wrote("bridge stays available")); + require(app.connectedBrowsers() == 1); + app.shutdown(); + }}; diff --git a/test/unit/WebKitGTKPolicyTests.cpp b/test/unit/WebKitGTKPolicyTests.cpp index de0a1892..0da32799 100644 --- a/test/unit/WebKitGTKPolicyTests.cpp +++ b/test/unit/WebKitGTKPolicyTests.cpp @@ -1,6 +1,6 @@ -#include #include "TemporaryDirectory.hpp" #include +#include #include #include @@ -21,105 +21,121 @@ using namespace webfront::frontend::detail::webkitgtk; #if defined(__linux__) const Scenario webKitGTKSnapPaths{"WebKitGTK detects inherited Snap toolkit paths", [] { - then("recognizes path lists without mistaking unrelated paths for Snap", [] { - check(containsSnapPath("/snap/core20/current/lib")); - check(containsSnapPath("/usr/lib:/var/lib/snapd/snap/core/current/lib", ":;")); - check(containsSnapPath("/usr/lib;/snap/core/current/lib", ":;")); - check(containsSnapPath("/usr/lib/a.so /snap/core/current/lib/a.so", ": ")); - check(!containsSnapPath("/home/user/cache /snap/test/immodules.cache")); - check(!containsSnapPath("/home/user/cache /snap/test/modules", ":")); - check(!containsSnapPath("/usr/lib:/home/user/snap/app", ":")); - check(!containsSnapPath("/snapshots/lib:/snap", ":")); - check(!containsSnapPath("")); - }); -}}; + then("recognizes path lists without mistaking unrelated paths for Snap", [] { + check(containsSnapPath("/snap/core20/current/lib")); + check(containsSnapPath("/usr/lib:/var/lib/snapd/snap/core/current/lib", ":;")); + check(containsSnapPath("/usr/lib;/snap/core/current/lib", ":;")); + check(containsSnapPath("/usr/lib/a.so /snap/core/current/lib/a.so", ": ")); + check(!containsSnapPath("/home/user/cache /snap/test/immodules.cache")); + check(!containsSnapPath("/home/user/cache /snap/test/modules", ":")); + check(!containsSnapPath("/usr/lib:/home/user/snap/app", ":")); + check(!containsSnapPath("/snapshots/lib:/snap", ":")); + check(!containsSnapPath("")); + }); + }}; #endif const Scenario webKitGTKApplies{"WebKitGTK applies navigation policy without toolkit objects", [] { - const detail::BoundContentPolicy policy; - struct Case { - PolicyEvent event; - const char* uri; - bool mainResource; - unsigned status; - bool initial; - PolicyDecision expected; - }; - const auto cases = std::to_array({ - { PolicyEvent::navigation, "http://127.0.0.1:9002/page", false, 0, false, PolicyDecision::allow}, - { PolicyEvent::navigation, "https://other.example/page", false, 0, false, PolicyDecision::allow}, - { PolicyEvent::navigation, "about:blank", false, 0, false, PolicyDecision::allow}, - { PolicyEvent::navigation, "about:srcdoc", false, 0, false, PolicyDecision::allow}, - { PolicyEvent::navigation, "data:text/html,hello", false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::allow}, - { PolicyEvent::navigation, "blob:null/id", false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::navigation, "file:///etc/passwd", false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::navigation, nullptr, false, 0, false, PolicyDecision::cancel}, - { PolicyEvent::response, "https://other.example/page", false, 403, true, PolicyDecision::allow}, - { PolicyEvent::response, nullptr, false, 0, true, PolicyDecision::allow}, - { PolicyEvent::response, "https://other.example/page", true, 200, false, PolicyDecision::cancel}, - { PolicyEvent::response, nullptr, true, 200, false, PolicyDecision::cancel}, - { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 200, true, PolicyDecision::allow}, - { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 399, true, PolicyDecision::allow}, - { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 400, true, PolicyDecision::failInitialNavigation}, - { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 500, false, PolicyDecision::allow}, - { PolicyEvent::newWindow, "https://other.example/page", false, 0, false, PolicyDecision::popup}, - { PolicyEvent::newWindow, nullptr, false, 0, false, PolicyDecision::popup}, - {static_cast(99), nullptr, false, 0, false, PolicyDecision::cancel}, - }); - then("responses enforce main-document origins and initial HTTP failures while actions reject opaque schemes", [&] { - for (const auto& entry : cases) { - auto scope = info(entry.uri ? entry.uri : "null URI"); - check(decidePolicy(policy, {entry.event, entry.uri, entry.mainResource, entry.status, entry.initial}) == entry.expected); - } - }); - given("an explicitly allowed destination", [&] { - ContentPolicy options; - options.navigationAllowedOrigins = {"https://other.example"}; - const detail::BoundContentPolicy allowed("http://127.0.0.1:9002", options); - then("its redirected response may commit", [&] { - check(decidePolicy(allowed, {PolicyEvent::response, "https://other.example/redirect", true, 200, true}) == PolicyDecision::allow); - }); - }); -}}; + const detail::BoundContentPolicy policy; + struct Case { + PolicyEvent event; + const char* uri; + bool mainResource; + unsigned status; + bool initial; + PolicyDecision expected; + }; + const auto cases = std::to_array({ + { PolicyEvent::navigation, "http://127.0.0.1:9002/page", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "https://other.example/page", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "about:blank", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "about:srcdoc", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "data:text/html,hello", false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::navigation, "blob:http://127.0.0.1:9002/id", false, 0, false, PolicyDecision::allow}, + { PolicyEvent::navigation, "blob:null/id", false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::navigation, "file:///etc/passwd", false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::navigation, nullptr, false, 0, false, PolicyDecision::cancel}, + { PolicyEvent::response, "https://other.example/page", false, 403, true, PolicyDecision::allow}, + { PolicyEvent::response, nullptr, false, 0, true, PolicyDecision::allow}, + { PolicyEvent::response, "https://other.example/page", true, 200, false, PolicyDecision::cancel}, + { PolicyEvent::response, nullptr, true, 200, false, PolicyDecision::cancel}, + { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 200, true, PolicyDecision::allow}, + { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 399, true, PolicyDecision::allow}, + { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 400, true, PolicyDecision::failInitialNavigation}, + { PolicyEvent::response, "http://127.0.0.1:9002/page", true, 500, false, PolicyDecision::allow}, + { PolicyEvent::newWindow, "https://other.example/page", false, 0, false, PolicyDecision::popup}, + { PolicyEvent::newWindow, nullptr, false, 0, false, PolicyDecision::popup}, + {static_cast(99), nullptr, false, 0, false, PolicyDecision::cancel}, + }); + then("responses enforce main-document origins and initial HTTP failures while actions reject opaque schemes", [&] { + for (const auto& entry : cases) { + auto scope = info(entry.uri ? entry.uri : "null URI"); + check(decidePolicy(policy, {entry.event, entry.uri, entry.mainResource, entry.status, entry.initial}) + == entry.expected); + } + }); + given("an explicitly allowed destination", [&] { + ContentPolicy options; + options.navigationAllowedOrigins = {"https://other.example"}; + const detail::BoundContentPolicy allowed("http://127.0.0.1:9002", options); + then("its redirected response may commit", [&] { + check(decidePolicy(allowed, {PolicyEvent::response, "https://other.example/redirect", true, 200, true}) + == PolicyDecision::allow); + }); + }); + }}; const Scenario webKitGTKRetains{"WebKitGTK retains the first session failure", [] { - FailureState state; - checkNothrow([&] { state.rethrowIfFailed(); }); - when("a navigation error is followed by a queued timeout and callback exception", [&] { - state.fail("original navigation error"); - const auto original = state.failure; - state.fail("initial navigation timed out"); - try { - throw std::logic_error("late callback failure"); - } catch (...) { - state.rememberFailure(); - } - then("the original exception remains observable", [&] { - require(state.failure == original); - requireThrows([&] { state.rethrowIfFailed(); }, equals("WebKitGTK: original navigation error")); - }); - }); - when("the first failure came from a callback", [&] { - try { - throw std::logic_error("original callback failure"); - } catch (...) { - state.rememberFailure(); - } - state.fail("late timeout"); - then("a later native failure preserves the exception type and message", [&] { - requireThrows([&] { state.rethrowIfFailed(); }); - requireThrows([&] { state.rethrowIfFailed(); }, equals("original callback failure")); - }); - }); -}}; + FailureState state; + checkNothrow([&] { + state.rethrowIfFailed(); + }); + when("a navigation error is followed by a queued timeout and callback exception", [&] { + state.fail("original navigation error"); + const auto original = state.failure; + state.fail("initial navigation timed out"); + try { + throw std::logic_error("late callback failure"); + } catch (...) { + state.rememberFailure(); + } + then("the original exception remains observable", [&] { + require(state.failure == original); + requireThrows( + [&] { + state.rethrowIfFailed(); + }, + equals("WebKitGTK: original navigation error")); + }); + }); + when("the first failure came from a callback", [&] { + try { + throw std::logic_error("original callback failure"); + } catch (...) { + state.rememberFailure(); + } + state.fail("late timeout"); + then("a later native failure preserves the exception type and message", [&] { + requireThrows([&] { + state.rethrowIfFailed(); + }); + requireThrows( + [&] { + state.rethrowIfFailed(); + }, + equals("original callback failure")); + }); + }); + }}; const Scenario webKitGTKHandles{"WebKitGTK handles missing native navigation diagnostics", [] { - then("a null GError message has an actionable fallback", [&] { - check(initialNavigationError(nullptr) == "initial navigation failed: unknown error; check the local server and page path"); - check(initialNavigationError("connection refused") == "initial navigation failed: connection refused; check the local server and page path"); - }); -}}; + then("a null GError message has an actionable fallback", [&] { + check(initialNavigationError(nullptr) + == "initial navigation failed: unknown error; check the local server and page path"); + check(initialNavigationError("connection refused") + == "initial navigation failed: connection refused; check the local server and page path"); + }); + }}; #if defined(__linux__) namespace { @@ -270,7 +286,7 @@ const Scenario webKitGTKProbeLifecycle{"WebKitGTK probes tolerate host child man SIGCHLD, +[](int) { const int savedError = errno; - int status; + int status; while (waitpid(-1, &status, WNOHANG) > 0) {} errno = savedError; }); diff --git a/test/unit/WebLinkTests.cpp b/test/unit/WebLinkTests.cpp index f95747e5..758c861b 100644 --- a/test/unit/WebLinkTests.cpp +++ b/test/unit/WebLinkTests.cpp @@ -1,7 +1,6 @@ #include "InjectableNetworking.hpp" - -#include #include +#include #include #include @@ -9,9 +8,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -41,9 +40,14 @@ void browserHandshake() { /// Runs its cleanup once, on request or at scope exit: a failing REQUIRE must not leave a sink that points into the test. struct LogRestore { std::function cleanup; - ~LogRestore() { run(); } + ~LogRestore() { + run(); + } void run() { - if (auto once = std::move(cleanup); once) { cleanup = nullptr; once(); } + if (auto once = std::move(cleanup); once) { + cleanup = nullptr; + once(); + } } }; @@ -73,53 +77,55 @@ vector returnMessage(msg::CallId callId, Configure configure) { } // namespace const Scenario webLinkSettles{"WebLink settles correlated asynchronous results", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) { }, scope}; - - given("a pending string result", [&] { - auto [callId, result] = link.expectResult(); - - when("the browser returns a matching value", [&] { - auto response = returnMessage(callId, [](auto& message, auto& frame) { - const string value{"done"}; - message.encodeParameter(value, frame); - frame.freeze(); - }); - InjectableSocket::receive(response); - - then("the future receives the decoded value", [&] { - require(result.get() == "done"); - }); - }); - - when("the browser returns an exception", [&] { - auto response = returnMessage(callId, [](auto& message, auto& frame) { - const runtime_error error{"JavaScript failed"}; - message.encodeParameter(error, frame); - frame.freeze(); - }); - InjectableSocket::receive(response); - - then("the future rethrows it with its message", [&] { - require(futureError(result) == "JavaScript failed"); - }); - }); - }); - - given("a pending void result", [&] { - auto [callId, result] = link.expectResult(); - - when("the browser returns no value", [&] { - auto response = returnMessage(callId, [](auto&, auto&) {}); - InjectableSocket::receive(response); - - then("the future completes", [&] { - requireNothrow([&] { result.get(); }); - }); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) {}, scope}; + + given("a pending string result", [&] { + auto [callId, result] = link.expectResult(); + + when("the browser returns a matching value", [&] { + auto response = returnMessage(callId, [](auto& message, auto& frame) { + const string value{"done"}; + message.encodeParameter(value, frame); + frame.freeze(); + }); + InjectableSocket::receive(response); + + then("the future receives the decoded value", [&] { + require(result.get() == "done"); + }); + }); + + when("the browser returns an exception", [&] { + auto response = returnMessage(callId, [](auto& message, auto& frame) { + const runtime_error error{"JavaScript failed"}; + message.encodeParameter(error, frame); + frame.freeze(); + }); + InjectableSocket::receive(response); + + then("the future rethrows it with its message", [&] { + require(futureError(result) == "JavaScript failed"); + }); + }); + }); + + given("a pending void result", [&] { + auto [callId, result] = link.expectResult(); + + when("the browser returns no value", [&] { + auto response = returnMessage(callId, [](auto&, auto&) {}); + InjectableSocket::receive(response); + + then("the future completes", [&] { + requireNothrow([&] { + result.get(); + }); + }); + }); + }); + }}; namespace { /// The BridgeError a future rethrows, as its code and message. @@ -137,315 +143,324 @@ pair futureFailure(future& result) { } // namespace const Scenario browserRejection{"A browser rejection reaches C++ with its code", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) { }, scope}; - - given("a pending call the browser rejects with an application code", [&] { - auto [callId, result] = link.expectResult(); - InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { - const BridgeError error{"denied", "the user said no"}; - message.encodeParameter(error, frame); - frame.freeze(); - })); - then("the future throws a BridgeError with that code and message", [&] { - require(futureFailure(result) == pair{"denied", "the user said no"}); - }); - }); - given("a pending call the browser rejects with a plain error", [&] { - auto [callId, result] = link.expectResult(); - InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { - const runtime_error error{"plain failure"}; - message.encodeParameter(error, frame); - frame.freeze(); - })); - then("the code is the generic one", [&] { - require(futureFailure(result) == pair{string(bridge_code::generic), "plain failure"}); - }); - }); - given("a pending call the browser rejects with a code of the bridge", [&] { - auto [callId, result] = link.expectResult(); - InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { - const auto error = detail::makeBridgeError(bridge_code::notFound, "JavaScript function 'x' was not found"); - message.encodeParameter(error, frame); - frame.freeze(); - })); - then("the reserved code is kept, which tells it from an application's", [&] { - const auto [code, text] = futureFailure(result); - require(code == bridge_code::notFound); - require(BridgeError::isReserved(code)); - }); - }); - given("a pending call whose result is not of the expected type", [&] { - auto [callId, result] = link.expectResult(); - InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { - const string text{"text"}; // the frame borrows it until freeze() - message.encodeParameter(text, frame); - frame.freeze(); - })); - then("the failure has the malformed code", [&] { - require(futureFailure(result).first == bridge_code::malformed); - }); - }); - given("a call pending when the connection closes", [&] { - auto [callId, result] = link.expectResult(); - static_cast(callId); - InjectableSocket::fail(make_error_code(errc::connection_reset)); - then("the failure has the disconnected code", [&] { - require(futureFailure(result).first == bridge_code::disconnected); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) {}, scope}; + + given("a pending call the browser rejects with an application code", [&] { + auto [callId, result] = link.expectResult(); + InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { + const BridgeError error{"denied", "the user said no"}; + message.encodeParameter(error, frame); + frame.freeze(); + })); + then("the future throws a BridgeError with that code and message", [&] { + require(futureFailure(result) == pair{"denied", "the user said no"}); + }); + }); + given("a pending call the browser rejects with a plain error", [&] { + auto [callId, result] = link.expectResult(); + InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { + const runtime_error error{"plain failure"}; + message.encodeParameter(error, frame); + frame.freeze(); + })); + then("the code is the generic one", [&] { + require(futureFailure(result) == pair{string(bridge_code::generic), "plain failure"}); + }); + }); + given("a pending call the browser rejects with a code of the bridge", [&] { + auto [callId, result] = link.expectResult(); + InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { + const auto error = detail::makeBridgeError(bridge_code::notFound, "JavaScript function 'x' was not found"); + message.encodeParameter(error, frame); + frame.freeze(); + })); + then("the reserved code is kept, which tells it from an application's", [&] { + const auto [code, text] = futureFailure(result); + require(code == bridge_code::notFound); + require(BridgeError::isReserved(code)); + }); + }); + given("a pending call whose result is not of the expected type", [&] { + auto [callId, result] = link.expectResult(); + InjectableSocket::receive(returnMessage(callId, [](auto& message, auto& frame) { + const string text{"text"}; // the frame borrows it until freeze() + message.encodeParameter(text, frame); + frame.freeze(); + })); + then("the failure has the malformed code", [&] { + require(futureFailure(result).first == bridge_code::malformed); + }); + }); + given("a call pending when the connection closes", [&] { + auto [callId, result] = link.expectResult(); + static_cast(callId); + InjectableSocket::fail(make_error_code(errc::connection_reset)); + then("the failure has the disconnected code", [&] { + require(futureFailure(result).first == bridge_code::disconnected); + }); + }); + }}; const Scenario webLinkRejects{"WebLink rejects incomplete asynchronous results", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 8, [](WebLinkEvent) { }, scope}; - - given("a pending value whose return is malformed", [&] { - auto [callId, result] = link.expectResult(); - auto response = returnMessage(callId, [](auto& message, auto&) { - message.setParametersCount(1); - }); - InjectableSocket::receive(response); - - then("the future receives the decoding error", [&] { - require(futureError(result) == "Not enough data for msg::FunctionCall::decodeParameter"); - }); - }); - - given("a pending value when the browser disconnects", [&] { - auto [callId, result] = link.expectResult(); - static_cast(callId); - InjectableSocket::fail(make_error_code(errc::connection_reset)); - - then("the future receives a connection error", [&] { - require(futureError(result).starts_with("Browser connection closed:")); - }); - }); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 8, [](WebLinkEvent) {}, scope}; + + given("a pending value whose return is malformed", [&] { + auto [callId, result] = link.expectResult(); + auto response = returnMessage(callId, [](auto& message, auto&) { + message.setParametersCount(1); + }); + InjectableSocket::receive(response); + + then("the future receives the decoding error", [&] { + require(futureError(result) == "Not enough data for msg::FunctionCall::decodeParameter"); + }); + }); + + given("a pending value when the browser disconnects", [&] { + auto [callId, result] = link.expectResult(); + static_cast(callId); + InjectableSocket::fail(make_error_code(errc::connection_reset)); + + then("the future receives a connection error", [&] { + require(futureError(result).starts_with("Browser connection closed:")); + }); + }); + }}; const Scenario webLinkDispatches{"WebLink dispatches browser messages and allocates distinct calls", [] { - InjectableSocket::reset(); - vector events; - string calledName; - int calledValue{}; - msg::CallId receivedCallId{}; - InlineTaskScope scope; - WebLink link{InjectableSocket{}, - 9, - [&](WebLinkEvent event) { - events.push_back(event.code); - if (event.code == WebLinkEvent::Code::cppFunctionCalled) { - calledName = event.text; - receivedCallId = event.callId; - msg::FunctionCall<>::decodeParameter(calledValue, event.data); - } - }, - scope}; - - given("a browser handshake and function call", [&] { - msg::Handshake handshake; - auto handshakePayload = span(reinterpret_cast(handshake.header().data()), handshake.header().size()); - InjectableSocket::receive(clientFrame(handshakePayload)); - - msg::FunctionCall<> call; - call.setCallId(37); - websocket::Frame frame{span(reinterpret_cast(call.header().data()), call.header().size())}; - const string functionName{"registered"}; - call.encodeParameter(functionName, frame); - call.encodeParameter(42, frame); - frame.freeze(); - InjectableSocket::receive(clientFrame(messagePayload(frame))); - - then("the link acknowledges and dispatches the correlated call", [&] { - require(events == vector{WebLinkEvent::Code::linked, WebLinkEvent::Code::cppFunctionCalled}); - require(calledName == "registered"); - require(calledValue == 42); - require(receivedCallId == 37); - require(InjectableSocket::hasWrittenData()); - }); - }); - - given("multiple pending calls", [&] { - auto [firstId, first] = link.expectResult(); - auto [secondId, second] = link.expectResult(); - static_cast(first); - static_cast(second); - - then("their nonzero correlation identifiers are distinct", [&] { - require(firstId != 0); - require(secondId != 0); - require(firstId != secondId); - }); - }); - - given("an explicit error response", [&] { - link.sendError(12, "not available"); - - then("the encoded exception is written", [&] { - require(InjectableSocket::hasWrittenData()); - }); - }); - - given("an application error with a code, and one that tries to pass for the bridge's", [&] { - link.sendError(15, "no space", "quota:exceeded"); - link.sendError(16, "forged", "webfront.notFound"); - link.sendError(17, "ill formed", "bad code"); - - then("the application code is kept and the others are sent as the generic one", [&] { - require(InjectableSocket::wrote("quota:exceeded")); - require(!InjectableSocket::wrote(std::string(bridge_code::notFound))); - require(!InjectableSocket::wrote("bad code")); - require(InjectableSocket::wrote(std::string(bridge_code::generic))); - }); - }); - - given("a closed browser connection", [&] { - InjectableSocket::fail(make_error_code(errc::connection_reset)); - auto [callId, result] = link.expectResult(); - - then("new calls fail without allocating an identifier", [&] { - require(callId == 0); - require(futureError(result) == "Browser connection closed"); - }); - then("the link reports the disconnection once", [&] { - require(events == vector{WebLinkEvent::Code::closed}); - }); - }); -}}; + InjectableSocket::reset(); + vector events; + string calledName; + int calledValue{}; + msg::CallId receivedCallId{}; + InlineTaskScope scope; + WebLink link{InjectableSocket{}, + 9, + [&](WebLinkEvent event) { + events.push_back(event.code); + if (event.code == WebLinkEvent::Code::cppFunctionCalled) { + calledName = event.text; + receivedCallId = event.callId; + msg::FunctionCall<>::decodeParameter(calledValue, event.data); + } + }, + scope}; + + given("a browser handshake and function call", [&] { + msg::Handshake handshake; + auto handshakePayload = span(reinterpret_cast(handshake.header().data()), handshake.header().size()); + InjectableSocket::receive(clientFrame(handshakePayload)); + + msg::FunctionCall<> call; + call.setCallId(37); + websocket::Frame frame{ + span(reinterpret_cast(call.header().data()), call.header().size())}; + const string functionName{"registered"}; + call.encodeParameter(functionName, frame); + call.encodeParameter(42, frame); + frame.freeze(); + InjectableSocket::receive(clientFrame(messagePayload(frame))); + + then("the link acknowledges and dispatches the correlated call", [&] { + require(events == vector{WebLinkEvent::Code::linked, WebLinkEvent::Code::cppFunctionCalled}); + require(calledName == "registered"); + require(calledValue == 42); + require(receivedCallId == 37); + require(InjectableSocket::hasWrittenData()); + }); + }); + + given("multiple pending calls", [&] { + auto [firstId, first] = link.expectResult(); + auto [secondId, second] = link.expectResult(); + static_cast(first); + static_cast(second); + + then("their nonzero correlation identifiers are distinct", [&] { + require(firstId != 0); + require(secondId != 0); + require(firstId != secondId); + }); + }); + + given("an explicit error response", [&] { + link.sendError(12, "not available"); + + then("the encoded exception is written", [&] { + require(InjectableSocket::hasWrittenData()); + }); + }); + + given("an application error with a code, and one that tries to pass for the bridge's", [&] { + link.sendError(15, "no space", "quota:exceeded"); + link.sendError(16, "forged", "webfront.notFound"); + link.sendError(17, "ill formed", "bad code"); + + then("the application code is kept and the others are sent as the generic one", [&] { + require(InjectableSocket::wrote("quota:exceeded")); + require(!InjectableSocket::wrote(std::string(bridge_code::notFound))); + require(!InjectableSocket::wrote("bad code")); + require(InjectableSocket::wrote(std::string(bridge_code::generic))); + }); + }); + + given("a closed browser connection", [&] { + InjectableSocket::fail(make_error_code(errc::connection_reset)); + auto [callId, result] = link.expectResult(); + + then("new calls fail without allocating an identifier", [&] { + require(callId == 0); + require(futureError(result) == "Browser connection closed"); + }); + then("the link reports the disconnection once", [&] { + require(events == vector{WebLinkEvent::Code::closed}); + }); + }); + }}; const Scenario webLinkReportsBrowser{"WebLink reports a browser's close frame as its disconnection", [] { - InjectableSocket::reset(); - vector events; - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 10, [&](WebLinkEvent event) { events.push_back(event.code); }, scope}; - when("the browser sends a close frame", [&] { - InjectableSocket::receive(std::array{byte{0x88}, byte{0x80}, byte{1}, byte{2}, byte{3}, byte{4}}); - then("the link reports one disconnection, and none when it is destroyed", [&] { - require(events == vector{WebLinkEvent::Code::closed}); - }); - }); -}}; + InjectableSocket::reset(); + vector events; + InlineTaskScope scope; + WebLink link{InjectableSocket{}, + 10, + [&](WebLinkEvent event) { + events.push_back(event.code); + }, + scope}; + when("the browser sends a close frame", [&] { + InjectableSocket::receive(std::array{byte{0x88}, byte{0x80}, byte{1}, byte{2}, byte{3}, byte{4}}); + then("the link reports one disconnection, and none when it is destroyed", [&] { + require(events == vector{WebLinkEvent::Code::closed}); + }); + }); + }}; const Scenario webLinkDispatchesEvery{"WebLink dispatches every WebSocket frame coalesced in one read", [] { - InjectableSocket::reset(); - vector events; - string calledName; - InlineTaskScope scope; - WebLink link{InjectableSocket{}, - 10, - [&](WebLinkEvent event) { - events.push_back(event.code); - if (event.code == WebLinkEvent::Code::cppFunctionCalled) - calledName = event.text; - }, - scope}; - - given("A handshake and function call delivered together", [&] { - msg::Handshake handshake; - const auto handshakePayload = span(reinterpret_cast(handshake.header().data()), handshake.header().size()); - auto received = clientFrame(handshakePayload); - - msg::FunctionCall<> call; - websocket::Frame frame{span(reinterpret_cast(call.header().data()), call.header().size())}; - const string functionName{"registered"}; - call.encodeParameter(functionName, frame); - frame.freeze(); - const auto callFrame = clientFrame(messagePayload(frame)); - received.insert(received.end(), callFrame.begin(), callFrame.end()); - - when("The socket completes one read", [&] { - InjectableSocket::receive(received); - - then("Both frames are dispatched in order", [&] { - require(events == vector{WebLinkEvent::Code::linked, WebLinkEvent::Code::cppFunctionCalled}); - require(calledName == "registered"); - }); - }); - }); -}}; + InjectableSocket::reset(); + vector events; + string calledName; + InlineTaskScope scope; + WebLink link{InjectableSocket{}, + 10, + [&](WebLinkEvent event) { + events.push_back(event.code); + if (event.code == WebLinkEvent::Code::cppFunctionCalled) + calledName = event.text; + }, + scope}; + + given("A handshake and function call delivered together", [&] { + msg::Handshake handshake; + const auto handshakePayload = span(reinterpret_cast(handshake.header().data()), + handshake.header().size()); + auto received = clientFrame(handshakePayload); + + msg::FunctionCall<> call; + websocket::Frame frame{ + span(reinterpret_cast(call.header().data()), call.header().size())}; + const string functionName{"registered"}; + call.encodeParameter(functionName, frame); + frame.freeze(); + const auto callFrame = clientFrame(messagePayload(frame)); + received.insert(received.end(), callFrame.begin(), callFrame.end()); + + when("The socket completes one read", [&] { + InjectableSocket::receive(received); + + then("Both frames are dispatched in order", [&] { + require(events == vector{WebLinkEvent::Code::linked, WebLinkEvent::Code::cppFunctionCalled}); + require(calledName == "registered"); + }); + }); + }); + }}; const Scenario webLinkForwards{"WebLink forwards logs to the browser until a write fails", [] { - InjectableSocket::reset(); - log::setLogLevel(log::Info); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 41, [](WebLinkEvent) { }, scope}; - browserHandshake(); - log::info("forwarded to the browser"); - drainBrowserLogs(); - require(InjectableSocket::wrote("forwarded to the browser")); - - InjectableSocket::receive(clientFrame({})); // An empty message is reported, not dispatched. - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - log::info("lost with the connection"); - drainBrowserLogs(); - InjectableSocket::failWrites({}); - log::info("after the failure"); - drainBrowserLogs(); - - // The failing write detached the transport before its diagnostic. - check(!InjectableSocket::wrote("after the failure")); - log::setLogLevel(log::Disabled); -}}; + InjectableSocket::reset(); + log::setLogLevel(log::Info); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 41, [](WebLinkEvent) {}, scope}; + browserHandshake(); + log::info("forwarded to the browser"); + drainBrowserLogs(); + require(InjectableSocket::wrote("forwarded to the browser")); + + InjectableSocket::receive(clientFrame({})); // An empty message is reported, not dispatched. + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + log::info("lost with the connection"); + drainBrowserLogs(); + InjectableSocket::failWrites({}); + log::info("after the failure"); + drainBrowserLogs(); + + // The failing write detached the transport before its diagnostic. + check(!InjectableSocket::wrote("after the failure")); + log::setLogLevel(log::Disabled); + }}; const Scenario writeFailing{"A write failing after its WebLink is destroyed does not reach the link or its successor", [] { - InjectableSocket::reset(); - log::setLogLevel(log::Info); - InlineTaskScope scope; - auto link = make_unique>(InjectableSocket{}, WebLinkId{31}, [](WebLinkEvent) { }, scope); - browserHandshake(); - // The old link's write completes only after the link is gone, keeping its WebSocket alive. - InjectableSocket::deferWrites(); - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - log::info("written by the old link"); - drainBrowserLogs(); - link.reset(); - InjectableSocket::failWrites({}); - InjectableSocket::deferWrites(false); - - // A new link, possibly at the same address, attaches its own transport. - link = make_unique>(InjectableSocket{}, WebLinkId{32}, [](WebLinkEvent) { }, scope); - browserHandshake(); - require(InjectableSocket::completeDeferredWrites() == 1); - log::info("delivered by the new link"); - drainBrowserLogs(); - - check(InjectableSocket::wrote("delivered by the new link")); - link.reset(); - log::setLogLevel(log::Disabled); -}}; + InjectableSocket::reset(); + log::setLogLevel(log::Info); + InlineTaskScope scope; + auto link = make_unique>(InjectableSocket{}, WebLinkId{31}, [](WebLinkEvent) {}, scope); + browserHandshake(); + // The old link's write completes only after the link is gone, keeping its WebSocket alive. + InjectableSocket::deferWrites(); + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + log::info("written by the old link"); + drainBrowserLogs(); + link.reset(); + InjectableSocket::failWrites({}); + InjectableSocket::deferWrites(false); + + // A new link, possibly at the same address, attaches its own transport. + link = make_unique>(InjectableSocket{}, WebLinkId{32}, [](WebLinkEvent) {}, scope); + browserHandshake(); + require(InjectableSocket::completeDeferredWrites() == 1); + log::info("delivered by the new link"); + drainBrowserLogs(); + + check(InjectableSocket::wrote("delivered by the new link")); + link.reset(); + log::setLogLevel(log::Disabled); + }}; const Scenario browserStops{"A browser that stops reading bounds the diagnostic frames queued for it", [] { - InjectableSocket::reset(); - log::setLogLevel(log::Info); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 51, [](WebLinkEvent) { }, scope}; - browserHandshake(); - // Only the first write reaches the network, and it does not complete. - InjectableSocket::deferWrites(); + InjectableSocket::reset(); + log::setLogLevel(log::Info); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 51, [](WebLinkEvent) {}, scope}; + browserHandshake(); + // Only the first write reaches the network, and it does not complete. + InjectableSocket::deferWrites(); #if defined(WEBFRONT_USE_MDDLOG) && WEBFRONT_USE_MDDLOG - const auto before = log::transportHealth(); + const auto before = log::transportHealth(); #endif - static constexpr size_t messages = 10240; - for (size_t index = 0; index < messages; ++index) { - log::info("unread diagnostic"); - if (index % 64 == 63) drainBrowserLogs(); // Keep the rings below saturation. - } - drainBrowserLogs(); - - check(link.pendingWrites() == link.maxPendingLogFrames); - check(link.droppedLogFrames() == messages - link.maxPendingLogFrames); + static constexpr size_t messages = 10240; + for (size_t index = 0; index < messages; ++index) { + log::info("unread diagnostic"); + if (index % 64 == 63) + drainBrowserLogs(); // Keep the rings below saturation. + } + drainBrowserLogs(); + + check(link.pendingWrites() == link.maxPendingLogFrames); + check(link.droppedLogFrames() == messages - link.maxPendingLogFrames); #if defined(WEBFRONT_USE_MDDLOG) && WEBFRONT_USE_MDDLOG - check(log::transportHealth().overflows - before.overflows == link.droppedLogFrames()); + check(log::transportHealth().overflows - before.overflows == link.droppedLogFrames()); #endif - // Once the network completes, the queue drains and the link keeps working. - InjectableSocket::deferWrites(false); - require(InjectableSocket::completeDeferredWrites() == 1); - check(link.pendingWrites() == 0); - log::setLogLevel(log::Disabled); -}}; + // Once the network completes, the queue drains and the link keeps working. + InjectableSocket::deferWrites(false); + require(InjectableSocket::completeDeferredWrites() == 1); + check(link.pendingWrites() == 0); + log::setLogLevel(log::Disabled); + }}; namespace { template @@ -463,104 +478,115 @@ networking::Task waitWritesSeeing(Writes writes, const vector>(InjectableSocket{}, WebLinkId{12}, [](WebLinkEvent) { }, scope); - InjectableSocket::deferWrites(); - for (msg::CallId call = 1; call <= 3; ++call) - link->sendError(call, "queued"); - require(link->pendingWrites() == 3); - using Writes = webfront::detail::WritesAtMost>; - bool woken = false; - given("a task waiting for at most one queued frame", [&] { - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{link, 1}, woken)); - then("it wakes when the second write ends, not before", [&] { - check(!woken); - InjectableSocket::completeDeferredWrites(); - check(!woken); - InjectableSocket::completeDeferredWrites(); - check(woken); - }); - }); - given("a waiting task that is stopped", [&] { - networking::ex::inplace_stop_source stop; - networking::Spawn(scope, networking::ex::inline_scheduler{}, stop.get_token(), waitWrites(Writes{link, 0}, woken)); - stop.request_stop(); - then("it unwinds, and the drained queue does not call it", [&] { - while (InjectableSocket::completeDeferredWrites() > 0) { } - check(!woken); - check(link->pendingWrites() == 0); - }); - }); - given("a link destroyed while a task waits", [&] { - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{link, 0}, woken)); - link.reset(); - then("the task resumes: nothing is left to wait for", [&] { - check(woken); - }); - }); - given("a link that is gone", [&] { - std::weak_ptr> gone; - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{gone, 0}, woken)); - then("the task does not wait", [&] { - check(woken); - }); - }); - InjectableSocket::deferWrites(false); - while (InjectableSocket::completeDeferredWrites() > 0) { } -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + auto link = make_shared>(InjectableSocket{}, WebLinkId{12}, [](WebLinkEvent) {}, scope); + InjectableSocket::deferWrites(); + for (msg::CallId call = 1; call <= 3; ++call) + link->sendError(call, "queued"); + require(link->pendingWrites() == 3); + using Writes = webfront::detail::WritesAtMost>; + bool woken = false; + given("a task waiting for at most one queued frame", [&] { + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{link, 1}, woken)); + then("it wakes when the second write ends, not before", [&] { + check(!woken); + InjectableSocket::completeDeferredWrites(); + check(!woken); + InjectableSocket::completeDeferredWrites(); + check(woken); + }); + }); + given("a waiting task that is stopped", [&] { + networking::ex::inplace_stop_source stop; + networking::Spawn(scope, networking::ex::inline_scheduler{}, stop.get_token(), waitWrites(Writes{link, 0}, woken)); + stop.request_stop(); + then("it unwinds, and the drained queue does not call it", [&] { + while (InjectableSocket::completeDeferredWrites() > 0) {} + check(!woken); + check(link->pendingWrites() == 0); + }); + }); + given("a link destroyed while a task waits", [&] { + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{link, 0}, woken)); + link.reset(); + then("the task resumes: nothing is left to wait for", [&] { + check(woken); + }); + }); + given("a link that is gone", [&] { + std::weak_ptr> gone; + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(Writes{gone, 0}, woken)); + then("the task does not wait", [&] { + check(woken); + }); + }); + InjectableSocket::deferWrites(false); + while (InjectableSocket::completeDeferredWrites() > 0) {} + }}; const Scenario writerResumes{"A writer resumes after a failed write reported the closure", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - vector events; - auto link = make_shared>(InjectableSocket{}, WebLinkId{13}, [&events](WebLinkEvent event) { events.push_back(event.code); }, scope); - InjectableSocket::deferWrites(); - for (msg::CallId call = 1; call <= 3; ++call) - link->sendError(call, "queued"); - vector seen{WebLinkEvent::Code::linked}; // replaced when the writer resumes - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWritesSeeing(webfront::detail::WritesAtMost>{link, 0}, events, seen)); - when("the write fails", [&] { - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - InjectableSocket::deferWrites(false); - InjectableSocket::completeDeferredWrites(); - then("the writer resumes once the closure was reported", [&] { - check(seen == vector{WebLinkEvent::Code::closed}); - }); - }); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + vector events; + auto link = make_shared>( + InjectableSocket{}, + WebLinkId{13}, + [&events](WebLinkEvent event) { + events.push_back(event.code); + }, + scope); + InjectableSocket::deferWrites(); + for (msg::CallId call = 1; call <= 3; ++call) + link->sendError(call, "queued"); + vector seen{WebLinkEvent::Code::linked}; // replaced when the writer resumes + networking::Spawn(scope, + networking::ex::inline_scheduler{}, + waitWritesSeeing(webfront::detail::WritesAtMost>{link, 0}, events, seen)); + when("the write fails", [&] { + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + InjectableSocket::deferWrites(false); + InjectableSocket::completeDeferredWrites(); + then("the writer resumes once the closure was reported", [&] { + check(seen == vector{WebLinkEvent::Code::closed}); + }); + }); + InjectableSocket::reset(); + }}; const Scenario webLinkNever{"WebLink never logs the payload of an incoming message", [] { - InjectableSocket::reset(); - InlineTaskScope scope; - WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) { }, scope}; - auto [callId, result] = link.expectResult(); - - log::setLogLevel(log::Info); - string logged; - std::mutex loggedMutex; - const auto sink = log::addSinks([&](string_view line) { - std::scoped_lock lock{loggedMutex}; - logged += string(line) + "\n"; - }); - LogRestore restore_sink{[&] { log::removeSinks(sink); log::setLogLevel(log::Error); }}; - auto response = returnMessage(callId, [](auto& message, auto& frame) { - const string value{"/webfront/services/files/0123456789abcdef.QQQQQQQQQQQQQQQQ/a.txt"}; - message.encodeParameter(value, frame); - frame.freeze(); - }); - InjectableSocket::receive(response); - require(result.get().starts_with("/webfront/services/files/")); - restore_sink.run(); - std::scoped_lock lock{loggedMutex}; - require(logged.find("QQQQ") == string::npos); - require(logged.find("51 51") == string::npos); -}}; + InjectableSocket::reset(); + InlineTaskScope scope; + WebLink link{InjectableSocket{}, 7, [](WebLinkEvent) {}, scope}; + auto [callId, result] = link.expectResult(); + + log::setLogLevel(log::Info); + string logged; + std::mutex loggedMutex; + const auto sink = log::addSinks([&](string_view line) { + std::scoped_lock lock{loggedMutex}; + logged += string(line) + "\n"; + }); + LogRestore restore_sink{[&] { + log::removeSinks(sink); + log::setLogLevel(log::Error); + }}; + auto response = returnMessage(callId, [](auto& message, auto& frame) { + const string value{"/webfront/services/files/0123456789abcdef.QQQQQQQQQQQQQQQQ/a.txt"}; + message.encodeParameter(value, frame); + frame.freeze(); + }); + InjectableSocket::receive(response); + require(result.get().starts_with("/webfront/services/files/")); + restore_sink.run(); + std::scoped_lock lock{loggedMutex}; + require(logged.find("QQQQ") == string::npos); + require(logged.find("51 51") == string::npos); + }}; namespace { struct SecureCloseTestNetwork : InjectableNetworking { - static constexpr bool secure = true; + static constexpr bool secure = true; static inline unsigned alerts = 0; static networking::Task Close(Socket&) { @@ -568,43 +594,51 @@ struct SecureCloseTestNetwork : InjectableNetworking { co_return; } }; -} +} // namespace -const Scenario securePeerCloseResumesWriters{"A secure peer Close releases writers during backpressure", [] { - InjectableSocket::reset(); - SecureCloseTestNetwork::alerts = 0; - InlineTaskScope scope; - using Link = WebLink; - vector events; - auto link = make_shared(InjectableSocket{}, WebLinkId{54}, [&](WebLinkEvent event) { events.push_back(event.code); }, scope); - InjectableSocket::deferWrites(); - link->sendError(1, "in flight"); - link->sendError(2, "queued before Close"); - bool waiting = false; - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, waiting)); - given("a blocked writer and a peer Close frame", [&] { - require(!waiting); - InjectableSocket::receive(std::array{byte{0x88}, byte{0x80}, byte{1}, byte{2}, byte{3}, byte{4}}); - require(waiting); - require(events == vector{WebLinkEvent::Code::closed}); - link->sendError(3, "queued after Close"); - bool last = false; - networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, last)); - then("the terminal frame drains the queue and wakes a late waiter", [&] { - require(!last); - require(SecureCloseTestNetwork::alerts == 0); - while (InjectableSocket::completeDeferredWrites() != 0) {} - require(last); - require(link->pendingWrites() == 0); - require(SecureCloseTestNetwork::alerts == 1); - require(InjectableSocket::wrote("in flight")); - require(!InjectableSocket::wrote("queued before Close")); - require(!InjectableSocket::wrote("queued after Close")); +const Scenario securePeerCloseResumesWriters{ + "A secure peer Close releases writers during backpressure", + [] { + InjectableSocket::reset(); + SecureCloseTestNetwork::alerts = 0; + InlineTaskScope scope; + using Link = WebLink; + vector events; + auto link = make_shared( + InjectableSocket{}, + WebLinkId{54}, + [&](WebLinkEvent event) { + events.push_back(event.code); + }, + scope); + InjectableSocket::deferWrites(); + link->sendError(1, "in flight"); + link->sendError(2, "queued before Close"); + bool waiting = false; + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, waiting)); + given("a blocked writer and a peer Close frame", [&] { + require(!waiting); + InjectableSocket::receive(std::array{byte{0x88}, byte{0x80}, byte{1}, byte{2}, byte{3}, byte{4}}); + require(waiting); + require(events == vector{WebLinkEvent::Code::closed}); + link->sendError(3, "queued after Close"); + bool last = false; + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, last)); + then("the terminal frame drains the queue and wakes a late waiter", [&] { + require(!last); + require(SecureCloseTestNetwork::alerts == 0); + while (InjectableSocket::completeDeferredWrites() != 0) {} + require(last); + require(link->pendingWrites() == 0); + require(SecureCloseTestNetwork::alerts == 1); + require(InjectableSocket::wrote("in flight")); + require(!InjectableSocket::wrote("queued before Close")); + require(!InjectableSocket::wrote("queued after Close")); + }); }); - }); - InjectableSocket::deferWrites(false); - InjectableSocket::reset(); -}}; + InjectableSocket::deferWrites(false); + InjectableSocket::reset(); + }}; namespace { struct SecureDeadlineNetwork : SecureCloseTestNetwork { @@ -618,32 +652,38 @@ struct SecureDeadlineNetwork : SecureCloseTestNetwork { }); } }; -} +} // namespace const Scenario securePeerEofBoundsBlockedWrite{"A secure peer EOF cannot hold a blocked write for ever", [] { - InjectableSocket::reset(); - SecureDeadlineNetwork::alerts = 0; - SecureDeadlineNetwork::timers = 0; - SecureDeadlineNetwork::timer = {}; - InlineTaskScope scope; - using Link = WebLink; - vector events; - auto link = make_shared(InjectableSocket{}, WebLinkId{55}, [&](WebLinkEvent event) { events.push_back(event.code); }, scope); - InjectableSocket::deferWrites(); - link->sendError(1, "in flight"); - given("a write blocked by backpressure and a peer close_notify", [&] { - require(link->pendingWrites() == 1); - InjectableSocket::fail({}); - require(events == vector{WebLinkEvent::Code::closed}); - then("the wait for the writer is bounded by the close deadline", [&] { - require(SecureDeadlineNetwork::timers == 1); - require(link->pendingWrites() == 1); - require(SecureDeadlineNetwork::alerts == 0); - require(SecureDeadlineNetwork::timer.complete); - SecureDeadlineNetwork::timer.complete({}, 0); - require(link->pendingWrites() == 0); - }); - }); - InjectableSocket::deferWrites(false); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + SecureDeadlineNetwork::alerts = 0; + SecureDeadlineNetwork::timers = 0; + SecureDeadlineNetwork::timer = {}; + InlineTaskScope scope; + using Link = WebLink; + vector events; + auto link = make_shared( + InjectableSocket{}, + WebLinkId{55}, + [&](WebLinkEvent event) { + events.push_back(event.code); + }, + scope); + InjectableSocket::deferWrites(); + link->sendError(1, "in flight"); + given("a write blocked by backpressure and a peer close_notify", [&] { + require(link->pendingWrites() == 1); + InjectableSocket::fail({}); + require(events == vector{WebLinkEvent::Code::closed}); + then("the wait for the writer is bounded by the close deadline", [&] { + require(SecureDeadlineNetwork::timers == 1); + require(link->pendingWrites() == 1); + require(SecureDeadlineNetwork::alerts == 0); + require(SecureDeadlineNetwork::timer.complete); + SecureDeadlineNetwork::timer.complete({}, 0); + require(link->pendingWrites() == 0); + }); + }); + InjectableSocket::deferWrites(false); + InjectableSocket::reset(); + }}; diff --git a/test/unit/WebSocketTests.cpp b/test/unit/WebSocketTests.cpp index 239f83a4..88c29508 100644 --- a/test/unit/WebSocketTests.cpp +++ b/test/unit/WebSocketTests.cpp @@ -1,8 +1,8 @@ #include "InjectableNetworking.hpp" #include "InlineTaskScope.hpp" -#include #include #include +#include #include #include @@ -20,623 +20,681 @@ using webfront::testing::InjectableNetworking; using webfront::testing::InjectableSocket; const Scenario stoppedWebSocket{"A stopped WebSocket does not read again", [] { - InjectableSocket::reset(); - int closeHandlerCalls = 0; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onClose([&](websocket::CloseEvent) { ++closeHandlerCalls; }); - ws->start(); - require(InjectableSocket::readCallCount() == 1); - - given("A read is pending when the WebSocket is stopped", [&] { - ws->stop(); - - when("The read completes", [&] { - InjectableSocket::fail({}); - - then("No other read is started and an explicit stop is not reported as a closure", [&] { - require(InjectableSocket::readCallCount() == 1); - require(closeHandlerCalls == 0); - }); - }); - }); -}}; + InjectableSocket::reset(); + int closeHandlerCalls = 0; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onClose([&](websocket::CloseEvent) { + ++closeHandlerCalls; + }); + ws->start(); + require(InjectableSocket::readCallCount() == 1); + + given("A read is pending when the WebSocket is stopped", [&] { + ws->stop(); + + when("The read completes", [&] { + InjectableSocket::fail({}); + + then("No other read is started and an explicit stop is not reported as a closure", [&] { + require(InjectableSocket::readCallCount() == 1); + require(closeHandlerCalls == 0); + }); + }); + }); + }}; namespace { struct SecureTestNetwork : InjectableNetworking { static constexpr bool secure = true; - static networking::Task Close(Socket&) { co_return; } + static networking::Task Close(Socket&) { + co_return; + } }; -} +} // namespace const Scenario secureWriteBeforeStart{"A secure WebSocket queues a frame written before start() and drops one written after stop()", [] { - InjectableSocket::reset(); - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - - given("a frame written before start(), as with the TCP provider", [&] { - ws->write("before start"); - ws->start(); - - then("it reaches the network", [&] { require(InjectableSocket::wrote("before start")); }); - - when("the WebSocket is stopped", [&] { - ws->stop(); - ws->write("after stop"); - - then("a later frame is dropped", [&] { require(!InjectableSocket::wrote("after stop")); }); - }); - }); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + + given("a frame written before start(), as with the TCP provider", [&] { + ws->write("before start"); + ws->start(); + + then("it reaches the network", [&] { + require(InjectableSocket::wrote("before start")); + }); + + when("the WebSocket is stopped", [&] { + ws->stop(); + ws->write("after stop"); + + then("a later frame is dropped", [&] { + require(!InjectableSocket::wrote("after stop")); + }); + }); + }); + InjectableSocket::reset(); + }}; const Scenario failedWrite{"A failed write closes the WebSocket", [] { - InjectableSocket::reset(); - int closeHandlerCalls = 0; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onClose([&](websocket::CloseEvent) { ++closeHandlerCalls; }); - ws->start(); - - given("A pending read and a write which fails", [&] { - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - ws->write("pending write"); - - then("The closure is reported once", [&] { require(closeHandlerCalls == 1); }); - - when("The read completes", [&] { - InjectableSocket::fail({}); - - then("No other read is started and the closure is not reported again", [&] { - require(InjectableSocket::readCallCount() == 1); - require(closeHandlerCalls == 1); - }); - }); - }); -}}; + InjectableSocket::reset(); + int closeHandlerCalls = 0; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onClose([&](websocket::CloseEvent) { + ++closeHandlerCalls; + }); + ws->start(); + + given("A pending read and a write which fails", [&] { + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + ws->write("pending write"); + + then("The closure is reported once", [&] { + require(closeHandlerCalls == 1); + }); + + when("The read completes", [&] { + InjectableSocket::fail({}); + + then("No other read is started and the closure is not reported again", [&] { + require(InjectableSocket::readCallCount() == 1); + require(closeHandlerCalls == 1); + }); + }); + }); + }}; const Scenario webSocketKeeps{"A WebSocket keeps only the latest frame of a key that has too many frames waiting", [] { - InjectableSocket::reset(); - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->start(); - InjectableSocket::deferWrites(); - const auto shared = [](std::string_view text) { - return websocket::Frame(text).share(); - }; - - given("another frame being written and a limit of one frame for the key", [&] { - ws->write("other-frame"); - ws->writeLatest(shared("state-1"), "onState", 1); - const auto intermediate = shared("state-2"); - ws->writeLatest(intermediate, "onState", 1); - ws->writeLatest(shared("state-3"), "onState", 1); - - then("the other frame does not count, and the intermediate frame was released when replaced", [&] { - require(ws->pendingWrites() == 2); - require(intermediate.use_count() == 1); - }); - when("the network completes the writes", [&] { - while (InjectableSocket::completeDeferredWrites() != 0) { } - then("the first and latest frames are written in order, not the intermediate one", [&] { - require(InjectableSocket::wrote("other-frame")); - require(InjectableSocket::wrote("state-1")); - require(InjectableSocket::wrote("state-3")); - require(!InjectableSocket::wrote("state-2")); - require(ws->pendingWrites() == 0); - }); - }); - }); - given("a frame held back behind a write that fails", [&] { - InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); - ws->writeLatest(shared("state-1"), "onState", 1); - const auto held = shared("state-2"); - ws->writeLatest(held, "onState", 1); - require(held.use_count() == 2); - - when("the write fails", [&] { - while (InjectableSocket::completeDeferredWrites() != 0) { } - then("the held frame is released with the queue", [&] { - require(held.use_count() == 1); - require(ws->pendingWrites() == 0); - }); - }); - }); - InjectableSocket::deferWrites(false); - while (InjectableSocket::completeDeferredWrites() != 0) { } - ws->stop(); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->start(); + InjectableSocket::deferWrites(); + const auto shared = [](std::string_view text) { + return websocket::Frame(text).share(); + }; + + given("another frame being written and a limit of one frame for the key", [&] { + ws->write("other-frame"); + ws->writeLatest(shared("state-1"), "onState", 1); + const auto intermediate = shared("state-2"); + ws->writeLatest(intermediate, "onState", 1); + ws->writeLatest(shared("state-3"), "onState", 1); + + then("the other frame does not count, and the intermediate frame was released when replaced", [&] { + require(ws->pendingWrites() == 2); + require(intermediate.use_count() == 1); + }); + when("the network completes the writes", [&] { + while (InjectableSocket::completeDeferredWrites() != 0) {} + then("the first and latest frames are written in order, not the intermediate one", [&] { + require(InjectableSocket::wrote("other-frame")); + require(InjectableSocket::wrote("state-1")); + require(InjectableSocket::wrote("state-3")); + require(!InjectableSocket::wrote("state-2")); + require(ws->pendingWrites() == 0); + }); + }); + }); + given("a frame held back behind a write that fails", [&] { + InjectableSocket::failWrites(make_error_code(errc::broken_pipe)); + ws->writeLatest(shared("state-1"), "onState", 1); + const auto held = shared("state-2"); + ws->writeLatest(held, "onState", 1); + require(held.use_count() == 2); + + when("the write fails", [&] { + while (InjectableSocket::completeDeferredWrites() != 0) {} + then("the held frame is released with the queue", [&] { + require(held.use_count() == 1); + require(ws->pendingWrites() == 0); + }); + }); + }); + InjectableSocket::deferWrites(false); + while (InjectableSocket::completeDeferredWrites() != 0) {} + ws->stop(); + InjectableSocket::reset(); + }}; const Scenario webSocketReassembles{"A WebSocket reassembles the messages a browser sends in several frames", [] { - InjectableSocket::reset(); - vector> binaryMessages; - vector textMessages; - int closeHandlerCalls = 0; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onMessage([&](span data) { binaryMessages.emplace_back(data.begin(), data.end()); }); - ws->onMessage([&](string_view text) { textMessages.emplace_back(text); }); - ws->onClose([&](websocket::CloseEvent) { ++closeHandlerCalls; }); - ws->start(); - const auto bytes = [](string_view text) { return as_bytes(span(text)); }; - const auto receive = [&](string_view payload, uint8_t finAndOpcode) { - InjectableSocket::receive(webfront::testing::clientFrame(bytes(payload), byte{finAndOpcode})); - }; - - given("A binary message in three fragments, with a control frame between them", [&] { - receive("ab", 0x02); - receive("", 0x89); // ping - receive("cd", 0x00); - require(binaryMessages.empty()); - receive("ef", 0x80); - - then("The handler receives the whole message once", [&] { - const auto whole = bytes("abcdef"); - require(binaryMessages == vector>{{whole.begin(), whole.end()}}); - require(closeHandlerCalls == 0); - }); - andWhen("A text message follows in two fragments", [&] { - receive("hel", 0x01); - receive("lo", 0x80); - then("It is delivered as text", [&] { - require(textMessages == vector{"hello"}); - require(binaryMessages.size() == 1); - }); - }); - }); - given("A continuation frame without a message to continue", [&] { - receive("x", 0x80); - then("The connection fails without delivering it", [&] { - require(closeHandlerCalls == 1); - require(binaryMessages.empty()); - }); - }); - given("A new message before the previous one is finished", [&] { - receive("a", 0x02); - receive("b", 0x82); - then("The connection fails without delivering either", [&] { - require(closeHandlerCalls == 1); - require(binaryMessages.empty()); - }); - }); - given("A fragmented ping", [&] { - receive("p", 0x09); - then("The connection fails, since control frames cannot be fragmented", [&] { - require(closeHandlerCalls == 1); - }); - }); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + vector> binaryMessages; + vector textMessages; + int closeHandlerCalls = 0; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onMessage([&](span data) { + binaryMessages.emplace_back(data.begin(), data.end()); + }); + ws->onMessage([&](string_view text) { + textMessages.emplace_back(text); + }); + ws->onClose([&](websocket::CloseEvent) { + ++closeHandlerCalls; + }); + ws->start(); + const auto bytes = [](string_view text) { + return as_bytes(span(text)); + }; + const auto receive = [&](string_view payload, uint8_t finAndOpcode) { + InjectableSocket::receive(webfront::testing::clientFrame(bytes(payload), byte{finAndOpcode})); + }; + + given("A binary message in three fragments, with a control frame between them", [&] { + receive("ab", 0x02); + receive("", 0x89); // ping + receive("cd", 0x00); + require(binaryMessages.empty()); + receive("ef", 0x80); + + then("The handler receives the whole message once", [&] { + const auto whole = bytes("abcdef"); + require(binaryMessages + == vector>{ + {whole.begin(), whole.end()} + }); + require(closeHandlerCalls == 0); + }); + andWhen("A text message follows in two fragments", [&] { + receive("hel", 0x01); + receive("lo", 0x80); + then("It is delivered as text", [&] { + require(textMessages == vector{"hello"}); + require(binaryMessages.size() == 1); + }); + }); + }); + given("A continuation frame without a message to continue", [&] { + receive("x", 0x80); + then("The connection fails without delivering it", [&] { + require(closeHandlerCalls == 1); + require(binaryMessages.empty()); + }); + }); + given("A new message before the previous one is finished", [&] { + receive("a", 0x02); + receive("b", 0x82); + then("The connection fails without delivering either", [&] { + require(closeHandlerCalls == 1); + require(binaryMessages.empty()); + }); + }); + given("A fragmented ping", [&] { + receive("p", 0x09); + then("The connection fails, since control frames cannot be fragmented", [&] { + require(closeHandlerCalls == 1); + }); + }); + InjectableSocket::reset(); + }}; const Scenario webSocketLimits{"A WebSocket limits the size of the messages it reassembles", [] { - InjectableSocket::reset(); - vector> messages; - optional closeCode; - using Limited = http::CustomBuffersPolicy<8192, 8192, 32768, 4>; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onMessage([&](span data) { messages.emplace_back(data.begin(), data.end()); }); - ws->onClose([&](websocket::CloseEvent event) { closeCode = event.status; }); - ws->start(); - const auto receive = [&](string_view payload, uint8_t finAndOpcode) { - InjectableSocket::receive(webfront::testing::clientFrame(as_bytes(span(payload)), byte{finAndOpcode})); - }; - const auto messageSize = static_cast(std::make_error_code(std::errc::message_size).value()); - - given("Fragments adding up to the limit", [&] { - receive("ab", 0x02); - receive("cd", 0x80); - then("The message is delivered", [&] { - require(messages.size() == 1); - require(!closeCode); - }); - }); - // Only the header of a frame (2 bytes, then the 4-byte mask): the payload never comes. - const auto receiveHeader = [&](string_view payload, uint8_t finAndOpcode) { - auto frame = webfront::testing::clientFrame(as_bytes(span(payload)), byte{finAndOpcode}); - frame.resize(6); - InjectableSocket::receive(frame); - }; - - given("A ping of 125 bytes, more than the message limit", [&] { - receive(string(125, 'p'), 0x89); - then("The connection stays open, since control frames have their own limit", [&] { - require(!closeCode); - receive("ok", 0x82); - require(messages.size() == 1); - }); - }); - given("The header of a ping announcing 126 bytes", [&] { - // FIN and ping; masked 16-bit length 126; masking key. - InjectableSocket::receive(vector{byte{0x89}, byte{0xfe}, byte{0}, byte{126}, byte{0x12}, byte{0x34}, byte{0x56}, byte{0x78}}); - then("The connection fails with protocol_error", [&] { - require(closeCode == static_cast(std::make_error_code(std::errc::protocol_error).value())); - }); - }); - given("A continuation announcing more than what is left of the limit", [&] { - receive("ab", 0x02); - receiveHeader("cde", 0x80); - then("The connection fails with message_size on its header", [&] { - require(messages.empty()); - require(closeCode == messageSize); - }); - }); - given("The header of a first fragment announcing more than the limit", [&] { - receiveHeader("abcde", 0x02); - then("The connection fails with message_size without waiting for the payload", [&] { - require(closeCode == messageSize); - }); - }); - given("The header of a message in one frame announcing more than the limit", [&] { - receiveHeader("abcde", 0x82); - then("The connection fails with message_size", [&] { - require(messages.empty()); - require(closeCode == messageSize); - }); - }); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + vector> messages; + optional closeCode; + using Limited = http::CustomBuffersPolicy<8192, 8192, 32768, 4>; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onMessage([&](span data) { + messages.emplace_back(data.begin(), data.end()); + }); + ws->onClose([&](websocket::CloseEvent event) { + closeCode = event.status; + }); + ws->start(); + const auto receive = [&](string_view payload, uint8_t finAndOpcode) { + InjectableSocket::receive(webfront::testing::clientFrame(as_bytes(span(payload)), byte{finAndOpcode})); + }; + const auto messageSize = static_cast(std::make_error_code(std::errc::message_size).value()); + + given("Fragments adding up to the limit", [&] { + receive("ab", 0x02); + receive("cd", 0x80); + then("The message is delivered", [&] { + require(messages.size() == 1); + require(!closeCode); + }); + }); + // Only the header of a frame (2 bytes, then the 4-byte mask): the payload never comes. + const auto receiveHeader = [&](string_view payload, uint8_t finAndOpcode) { + auto frame = webfront::testing::clientFrame(as_bytes(span(payload)), byte{finAndOpcode}); + frame.resize(6); + InjectableSocket::receive(frame); + }; + + given("A ping of 125 bytes, more than the message limit", [&] { + receive(string(125, 'p'), 0x89); + then("The connection stays open, since control frames have their own limit", [&] { + require(!closeCode); + receive("ok", 0x82); + require(messages.size() == 1); + }); + }); + given("The header of a ping announcing 126 bytes", [&] { + // FIN and ping; masked 16-bit length 126; masking key. + InjectableSocket::receive( + vector{byte{0x89}, byte{0xfe}, byte{0}, byte{126}, byte{0x12}, byte{0x34}, byte{0x56}, byte{0x78}}); + then("The connection fails with protocol_error", [&] { + require(closeCode == static_cast(std::make_error_code(std::errc::protocol_error).value())); + }); + }); + given("A continuation announcing more than what is left of the limit", [&] { + receive("ab", 0x02); + receiveHeader("cde", 0x80); + then("The connection fails with message_size on its header", [&] { + require(messages.empty()); + require(closeCode == messageSize); + }); + }); + given("The header of a first fragment announcing more than the limit", [&] { + receiveHeader("abcde", 0x02); + then("The connection fails with message_size without waiting for the payload", [&] { + require(closeCode == messageSize); + }); + }); + given("The header of a message in one frame announcing more than the limit", [&] { + receiveHeader("abcde", 0x82); + then("The connection fails with message_size", [&] { + require(messages.empty()); + require(closeCode == messageSize); + }); + }); + InjectableSocket::reset(); + }}; const Scenario webSocketRejects{"A WebSocket rejects a frame announcing gigabytes before buffering it", [] { - InjectableSocket::reset(); - optional closeCode; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onMessage([](span) {}); - ws->onClose([&](websocket::CloseEvent event) { closeCode = event.status; }); - ws->start(); - - given("The header of a first fragment announcing 8 GiB, with the default limit", [&] { - // FIN clear, binary; masked 64-bit length 0x200000000; masking key. - InjectableSocket::receive(vector{byte{0x02}, byte{0xff}, byte{0}, byte{0}, byte{0}, byte{2}, byte{0}, byte{0}, byte{0}, byte{0}, - byte{0x12}, byte{0x34}, byte{0x56}, byte{0x78}}); - then("The connection fails with message_size", [&] { - require(closeCode == static_cast(std::make_error_code(std::errc::message_size).value())); - }); - }); - InjectableSocket::reset(); -}}; + InjectableSocket::reset(); + optional closeCode; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onMessage([](span) {}); + ws->onClose([&](websocket::CloseEvent event) { + closeCode = event.status; + }); + ws->start(); + + given("The header of a first fragment announcing 8 GiB, with the default limit", [&] { + // FIN clear, binary; masked 64-bit length 0x200000000; masking key. + InjectableSocket::receive(vector{byte{0x02}, + byte{0xff}, + byte{0}, + byte{0}, + byte{0}, + byte{2}, + byte{0}, + byte{0}, + byte{0}, + byte{0}, + byte{0x12}, + byte{0x34}, + byte{0x56}, + byte{0x78}}); + then("The connection fails with message_size", [&] { + require(closeCode == static_cast(std::make_error_code(std::errc::message_size).value())); + }); + }); + InjectableSocket::reset(); + }}; const Scenario webSocketHeaders{"WebSocket Headers decoding", [] { - given("Some Header data", [&] { - array data{0b10000001, 0b10000000 | 63, 0x10, 0x11, 0x12, 0x13}; - when("Casting to header", [&] { - auto header = reinterpret_cast(data.data()); - then("Fields should be", [&] { - require(header->FIN() == true); - require(header->RSV1() == false); - require(header->RSV2() == false); - require(header->RSV3() == false); - require(header->opcode() == websocket::Header::Opcode::text); - require(header->MASK() == true); - require(header->maskingKey() == std::array{std::byte{0x10}, std::byte{0x11}, std::byte{0x12}, std::byte{0x13}}); - require(header->payloadLenField() == 63); - require(header->payloadSize() == 63); - require(header->headerSize() == 6); - }); - }); - }); - - given("Header data", [&] { - array data{0b10000001, 0b10000000 | 126, 10, 20, 0x10, 0x11, 0x12, 0x13}; - when("Casting to header", [&] { - auto header = reinterpret_cast(data.data()); - then("Payload size should be 31127 from the 16 bits field", [&] { - require(header->payloadSize() == 2580); - require(header->headerSize() == 8); - }); - }); - }); - - given("Header data", [&] { - array data{0b10000001, 0b10000000 | 127, 10, 20, 30, 40, 50, 60, 70, 80, 0x10, 0x11, 0x12, 0x13}; - when("Casting to header", [&] { - auto header = reinterpret_cast(data.data()); - then("Payload size should be 13 256 444 from the 64 bits field", [&] { - require(header->payloadSize() == 726238597903828560); - require(header->headerSize() == 14); - }); - }); - }); -}}; + given("Some Header data", [&] { + array data{0b10000001, 0b10000000 | 63, 0x10, 0x11, 0x12, 0x13}; + when("Casting to header", [&] { + auto header = reinterpret_cast(data.data()); + then("Fields should be", [&] { + require(header->FIN() == true); + require(header->RSV1() == false); + require(header->RSV2() == false); + require(header->RSV3() == false); + require(header->opcode() == websocket::Header::Opcode::text); + require(header->MASK() == true); + require(header->maskingKey() + == std::array{std::byte{0x10}, std::byte{0x11}, std::byte{0x12}, std::byte{0x13}}); + require(header->payloadLenField() == 63); + require(header->payloadSize() == 63); + require(header->headerSize() == 6); + }); + }); + }); + + given("Header data", [&] { + array data{0b10000001, 0b10000000 | 126, 10, 20, 0x10, 0x11, 0x12, 0x13}; + when("Casting to header", [&] { + auto header = reinterpret_cast(data.data()); + then("Payload size should be 31127 from the 16 bits field", [&] { + require(header->payloadSize() == 2580); + require(header->headerSize() == 8); + }); + }); + }); + + given("Header data", [&] { + array data{0b10000001, 0b10000000 | 127, 10, 20, 30, 40, 50, 60, 70, 80, 0x10, 0x11, 0x12, 0x13}; + when("Casting to header", [&] { + auto header = reinterpret_cast(data.data()); + then("Payload size should be 13 256 444 from the 64 bits field", [&] { + require(header->payloadSize() == 726238597903828560); + require(header->headerSize() == 14); + }); + }); + }); + }}; const Scenario webSocketFrame{"WebSocket frame encoding", [] { - - given("Some text to send", [&] { - - std::string text = "Hello WS"; - -when("Encoding it", [&] { - websocket::Frame frame(text); - then("A text frame is produced", [&] { - require(frame.FIN() == true); - require(frame.RSV1() == false); - require(frame.RSV2() == false); - require(frame.RSV3() == false); - require(frame.opcode() == websocket::Header::Opcode::text); - require(frame.MASK() == false); - require(frame.payloadLenField() == 8); - require(frame.payloadSize() == 8); - require(frame.headerSize() == 2); - - auto buffers = frame.toBuffers(); - using Buffer = decltype(buffers[0]); - auto compare = [](Buffer b, std::string s) { - auto data = reinterpret_cast(b.data()); - for (size_t index = 0; index < s.size(); ++index) - if (data[index] != s[index]) return false; - return true; - }; - - require(compare(buffers[1], "Hello WS")); - }); -}); -}); -}}; + given("Some text to send", [&] { + std::string text = "Hello WS"; + + when("Encoding it", [&] { + websocket::Frame frame(text); + then("A text frame is produced", [&] { + require(frame.FIN() == true); + require(frame.RSV1() == false); + require(frame.RSV2() == false); + require(frame.RSV3() == false); + require(frame.opcode() == websocket::Header::Opcode::text); + require(frame.MASK() == false); + require(frame.payloadLenField() == 8); + require(frame.payloadSize() == 8); + require(frame.headerSize() == 2); + + auto buffers = frame.toBuffers(); + using Buffer = decltype(buffers[0]); + auto compare = [](Buffer b, std::string s) { + auto data = reinterpret_cast(b.data()); + for (size_t index = 0; index < s.size(); ++index) + if (data[index] != s[index]) + return false; + return true; + }; + + require(compare(buffers[1], "Hello WS")); + }); + }); + }); + }}; ; const Scenario webSocketFrames{"WebSocket frames can own payloads for asynchronous writes", [] { - given("A frame assembled from temporary message buffers", [&] { - array header{byte{0x01}, byte{0x02}}; - array payload{byte{0x03}, byte{0x04}, byte{0x05}}; - websocket::Frame frame(header); - frame.addBuffer(payload); - - when("The frame is frozen before the source buffers change", [&] { - frame.freeze(); - frame.freeze(); - header.fill(byte{0xff}); - payload.fill(byte{0xff}); - const auto buffers = frame.toBuffers(); - - then("Repeated freezing keeps the encoded payload valid", [&] { - const auto* encodedHeader = static_cast(buffers[1].data()); - const auto* encodedPayload = static_cast(buffers[2].data()); - require(buffers[1].size() == 2); - require(encodedHeader[0] == byte{0x01}); - require(encodedHeader[1] == byte{0x02}); - require(buffers[2].size() == 3); - require(encodedPayload[0] == byte{0x03}); - require(encodedPayload[1] == byte{0x04}); - require(encodedPayload[2] == byte{0x05}); - }); - }); - }); -}}; + given("A frame assembled from temporary message buffers", [&] { + array header{byte{0x01}, byte{0x02}}; + array payload{byte{0x03}, byte{0x04}, byte{0x05}}; + websocket::Frame frame(header); + frame.addBuffer(payload); + + when("The frame is frozen before the source buffers change", [&] { + frame.freeze(); + frame.freeze(); + header.fill(byte{0xff}); + payload.fill(byte{0xff}); + const auto buffers = frame.toBuffers(); + + then("Repeated freezing keeps the encoded payload valid", [&] { + const auto* encodedHeader = static_cast(buffers[1].data()); + const auto* encodedPayload = static_cast(buffers[2].data()); + require(buffers[1].size() == 2); + require(encodedHeader[0] == byte{0x01}); + require(encodedHeader[1] == byte{0x02}); + require(buffers[2].size() == 3); + require(encodedPayload[0] == byte{0x03}); + require(encodedPayload[1] == byte{0x04}); + require(encodedPayload[2] == byte{0x05}); + }); + }); + }); + }}; const Scenario webSocketDecoder{"WebSocket decoder", [] { - given("Some frame data and a decoder", [&] { - array frame{0x1, - 0b10000000 | 8, - 0x10, - 0x11, - 0x12, - 0x13, - uint8_t{'H' ^ 0x10}, - uint8_t{'e' ^ 0x11}, - uint8_t{'l' ^ 0x12}, - uint8_t{'l' ^ 0x13}, - uint8_t{'o' ^ 0x10}, - uint8_t{' ' ^ 0x11}, - uint8_t{'W' ^ 0x12}, - uint8_t{'S' ^ 0x13}}; - websocket::FrameDecoder decoder; - when("All data is received in one unique chunk", [&] { - require(decoder.parse(std::span(reinterpret_cast(frame.data()), frame.size()))); - auto bufferParser = std::cbegin(decoder.payload()); - then("Payload is correctly decoded", [&] { - for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) require(std::to_integer(*bufferParser++) == c); - }); - }); - - when("Data is received in two chunks but the first has a complete header", [&] { - require(decoder.parse(std::span(reinterpret_cast(frame.data()), 7)) == false); - require(decoder.parse(std::span(reinterpret_cast(frame.data() + 7), frame.size() - 7))); - auto bufferParser = std::cbegin(decoder.payload()); - then("Payload is correctly decoded", [&] { - for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) require(std::to_integer(*bufferParser++) == c); - }); - }); - - when("Data is received in two chunks but the first has an incomplete header", [&] { - require(decoder.parse(std::span(reinterpret_cast(frame.data()), 3)) == false); - require(decoder.parse(std::span(reinterpret_cast(frame.data() + 3), frame.size() - 3))); - auto bufferParser = std::cbegin(decoder.payload()); - then("Payload is correctly decoded", [&] { - for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) require(std::to_integer(*bufferParser++) == c); - }); - }); - }); -}}; + given("Some frame data and a decoder", [&] { + array frame{0x1, + 0b10000000 | 8, + 0x10, + 0x11, + 0x12, + 0x13, + uint8_t{'H' ^ 0x10}, + uint8_t{'e' ^ 0x11}, + uint8_t{'l' ^ 0x12}, + uint8_t{'l' ^ 0x13}, + uint8_t{'o' ^ 0x10}, + uint8_t{' ' ^ 0x11}, + uint8_t{'W' ^ 0x12}, + uint8_t{'S' ^ 0x13}}; + websocket::FrameDecoder decoder; + when("All data is received in one unique chunk", [&] { + require(decoder.parse(std::span(reinterpret_cast(frame.data()), frame.size()))); + auto bufferParser = std::cbegin(decoder.payload()); + then("Payload is correctly decoded", [&] { + for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) + require(std::to_integer(*bufferParser++) == c); + }); + }); + + when("Data is received in two chunks but the first has a complete header", [&] { + require(decoder.parse(std::span(reinterpret_cast(frame.data()), 7)) == false); + require(decoder.parse(std::span(reinterpret_cast(frame.data() + 7), frame.size() - 7))); + auto bufferParser = std::cbegin(decoder.payload()); + then("Payload is correctly decoded", [&] { + for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) + require(std::to_integer(*bufferParser++) == c); + }); + }); + + when("Data is received in two chunks but the first has an incomplete header", [&] { + require(decoder.parse(std::span(reinterpret_cast(frame.data()), 3)) == false); + require(decoder.parse(std::span(reinterpret_cast(frame.data() + 3), frame.size() - 3))); + auto bufferParser = std::cbegin(decoder.payload()); + then("Payload is correctly decoded", [&] { + for (auto c : {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'S'}) + require(std::to_integer(*bufferParser++) == c); + }); + }); + }); + }}; const Scenario webSocketDecoderPreserves{"WebSocket decoder preserves coalesced frames", [] { - given("Two masked text frames received in one chunk", [&] { - const array frames{0x81, - 0x82, - 0x10, - 0x11, - 0x12, - 0x13, - uint8_t{'o' ^ 0x10}, - uint8_t{'n' ^ 0x11}, - 0x81, - 0x82, - 0x20, - 0x21, - 0x22, - 0x23, - uint8_t{'o' ^ 0x20}, - uint8_t{'k' ^ 0x21}}; - const auto bytes = std::span(reinterpret_cast(frames.data()), frames.size()); - websocket::FrameDecoder decoder; - - when("The first frame is decoded", [&] { - require(decoder.parse(bytes)); - require(decoder.consumed() == 8); - require(vector(decoder.payload().begin(), decoder.payload().end()) == vector{byte{'o'}, byte{'n'}}); - - then("The unconsumed bytes decode as the second frame", [&] { - const auto firstFrameSize = decoder.consumed(); - decoder.reset(); - require(decoder.parse(bytes.subspan(firstFrameSize))); - require(decoder.consumed() == 8); - require(vector(decoder.payload().begin(), decoder.payload().end()) == vector{byte{'o'}, byte{'k'}}); - }); - }); - }); -}}; + given("Two masked text frames received in one chunk", [&] { + const array frames{0x81, + 0x82, + 0x10, + 0x11, + 0x12, + 0x13, + uint8_t{'o' ^ 0x10}, + uint8_t{'n' ^ 0x11}, + 0x81, + 0x82, + 0x20, + 0x21, + 0x22, + 0x23, + uint8_t{'o' ^ 0x20}, + uint8_t{'k' ^ 0x21}}; + const auto bytes = std::span(reinterpret_cast(frames.data()), frames.size()); + websocket::FrameDecoder decoder; + + when("The first frame is decoded", [&] { + require(decoder.parse(bytes)); + require(decoder.consumed() == 8); + require(vector(decoder.payload().begin(), decoder.payload().end()) == vector{byte{'o'}, byte{'n'}}); + + then("The unconsumed bytes decode as the second frame", [&] { + const auto firstFrameSize = decoder.consumed(); + decoder.reset(); + require(decoder.parse(bytes.subspan(firstFrameSize))); + require(decoder.consumed() == 8); + require(vector(decoder.payload().begin(), decoder.payload().end()) + == vector{byte{'o'}, byte{'k'}}); + }); + }); + }); + }}; const Scenario webSocketHeader{"WebSocket header completeness follows its encoded length and mask", [] { - given("An encoded WebSocket header", [&] { - then("It becomes complete at exactly the header boundary", [&] { - for (const auto lengthField : {125, 126, 127}) - for (const auto masked : {false, true}) { - auto scope = info(lengthField, masked ? " masked" : ""); - websocket::Header header; - header.raw[1] = byte(lengthField | (masked ? 0x80 : 0)); - const size_t expectedSize = (lengthField == 125 ? 2u : lengthField == 126 ? 4u : 10u) + (masked ? 4u : 0u); - require(!header.isComplete(expectedSize - 1)); - require(header.isComplete(expectedSize)); - require(header.isComplete(expectedSize + 1)); - } - }); - }); -}}; + given("An encoded WebSocket header", [&] { + then("It becomes complete at exactly the header boundary", [&] { + for (const auto lengthField : {125, 126, 127}) + for (const auto masked : {false, true}) { + auto scope = info(lengthField, masked ? " masked" : ""); + websocket::Header header; + header.raw[1] = byte(lengthField | (masked ? 0x80 : 0)); + const size_t expectedSize = (lengthField == 125 ? 2u : lengthField == 126 ? 4u : 10u) + (masked ? 4u : 0u); + require(!header.isComplete(expectedSize - 1)); + require(header.isComplete(expectedSize)); + require(header.isComplete(expectedSize + 1)); + } + }); + }); + }}; const Scenario shortWebSocket{"Short WebSocket headers do not interpret payload bytes as an extended length", [] { - websocket::Header header; - header.raw.fill(byte{0xff}); - header.raw[1] = byte{0x82}; - - given("A short masked header with nonzero bytes after its length field", [&] { - then("Only the inline length is used", [&] { - require(header.extendedLenField() == 0); - require(header.payloadSize() == 2); - require(header.headerSize() == 6); - }); - }); -}}; - -const Scenario webSocketDecoderPreservesSplit{"WebSocket decoder preserves split extended headers and the following frame", [] { - for (const size_t split : {1u, 2u, 7u, 8u, 9u, 13u}) - section("split after ", split, " bytes", [&] { - // A masked 16-bit length frame followed by an empty masked text frame. - vector frames{byte{0x81}, byte{0xfe}, byte{0}, byte{126}, byte{0x10}, byte{0x11}, byte{0x12}, byte{0x13}}; - const vector expected(126, byte{'x'}); - const array mask{byte{0x10}, byte{0x11}, byte{0x12}, byte{0x13}}; - for (size_t i = 0; i < expected.size(); ++i) - frames.push_back(expected[i] ^ mask[i % mask.size()]); - frames.insert(frames.end(), {byte{0x81}, byte{0x80}, byte{0}, byte{0}, byte{0}, byte{0}}); - websocket::FrameDecoder decoder; - const auto bytes = span(frames); - - given("The first frame starts in one read and finishes alongside another frame", [&] { - require(!decoder.parse(bytes.first(split))); - require(decoder.consumed() == split); - - when("The rest of the stream arrives", [&] { - require(decoder.parse(bytes.subspan(split))); - require(decoder.consumed() == 134 - split); - require(vector(decoder.payload().begin(), decoder.payload().end()) == expected); - const auto nextFrameOffset = split + decoder.consumed(); - decoder.reset(); - - then("The next frame has not been consumed as part of the payload", [&] { - require(decoder.parse(bytes.subspan(nextFrameOffset))); - require(decoder.consumed() == 6); - require(decoder.payload().empty()); + websocket::Header header; + header.raw.fill(byte{0xff}); + header.raw[1] = byte{0x82}; + + given("A short masked header with nonzero bytes after its length field", [&] { + then("Only the inline length is used", [&] { + require(header.extendedLenField() == 0); + require(header.payloadSize() == 2); + require(header.headerSize() == 6); + }); + }); + }}; + +const Scenario webSocketDecoderPreservesSplit{ + "WebSocket decoder preserves split extended headers and the following frame", + [] { + for (const size_t split : {1u, 2u, 7u, 8u, 9u, 13u}) + section("split after ", split, " bytes", [&] { + // A masked 16-bit length frame followed by an empty masked text frame. + vector frames{byte{0x81}, byte{0xfe}, byte{0}, byte{126}, byte{0x10}, byte{0x11}, byte{0x12}, byte{0x13}}; + const vector expected(126, byte{'x'}); + const array mask{byte{0x10}, byte{0x11}, byte{0x12}, byte{0x13}}; + for (size_t i = 0; i < expected.size(); ++i) + frames.push_back(expected[i] ^ mask[i % mask.size()]); + frames.insert(frames.end(), {byte{0x81}, byte{0x80}, byte{0}, byte{0}, byte{0}, byte{0}}); + websocket::FrameDecoder decoder; + const auto bytes = span(frames); + + given("The first frame starts in one read and finishes alongside another frame", [&] { + require(!decoder.parse(bytes.first(split))); + require(decoder.consumed() == split); + + when("The rest of the stream arrives", [&] { + require(decoder.parse(bytes.subspan(split))); + require(decoder.consumed() == 134 - split); + require(vector(decoder.payload().begin(), decoder.payload().end()) == expected); + const auto nextFrameOffset = split + decoder.consumed(); + decoder.reset(); + + then("The next frame has not been consumed as part of the payload", [&] { + require(decoder.parse(bytes.subspan(nextFrameOffset))); + require(decoder.consumed() == 6); + require(decoder.payload().empty()); + }); }); }); }); - }); -}}; + }}; const Scenario webSocketDecoderWaits{"WebSocket decoder waits for an entire split payload", [] { - given("A masked text frame split across three reads", [&] { - const array frame{0x81, - 0x88, - 0x10, - 0x11, - 0x12, - 0x13, - uint8_t{'H' ^ 0x10}, - uint8_t{'e' ^ 0x11}, - uint8_t{'l' ^ 0x12}, - uint8_t{'l' ^ 0x13}, - uint8_t{'o' ^ 0x10}, - uint8_t{' ' ^ 0x11}, - uint8_t{'W' ^ 0x12}, - uint8_t{'S' ^ 0x13}}; - const auto bytes = std::span(reinterpret_cast(frame.data()), frame.size()); - websocket::FrameDecoder decoder; - - require(!decoder.parse(bytes.first(7))); - require(decoder.consumed() == 7); - - // Six of the seven outstanding bytes arrive next. Comparing this chunk's size - // against the remaining length after appending would report completion one byte early. - when("The middle read still leaves payload bytes outstanding", [&] { - require(!decoder.parse(bytes.subspan(7, 6))); - require(decoder.consumed() == 6); - - then("Only the final read completes the frame", [&] { - require(decoder.parse(bytes.subspan(13))); - require(decoder.consumed() == 1); - require(decoder.payload().size() == 8); - }); - }); - }); -}}; + given("A masked text frame split across three reads", [&] { + const array frame{0x81, + 0x88, + 0x10, + 0x11, + 0x12, + 0x13, + uint8_t{'H' ^ 0x10}, + uint8_t{'e' ^ 0x11}, + uint8_t{'l' ^ 0x12}, + uint8_t{'l' ^ 0x13}, + uint8_t{'o' ^ 0x10}, + uint8_t{' ' ^ 0x11}, + uint8_t{'W' ^ 0x12}, + uint8_t{'S' ^ 0x13}}; + const auto bytes = std::span(reinterpret_cast(frame.data()), frame.size()); + websocket::FrameDecoder decoder; + + require(!decoder.parse(bytes.first(7))); + require(decoder.consumed() == 7); + + // Six of the seven outstanding bytes arrive next. Comparing this chunk's size + // against the remaining length after appending would report completion one byte early. + when("The middle read still leaves payload bytes outstanding", [&] { + require(!decoder.parse(bytes.subspan(7, 6))); + require(decoder.consumed() == 6); + + then("Only the final read completes the frame", [&] { + require(decoder.parse(bytes.subspan(13))); + require(decoder.consumed() == 1); + require(decoder.payload().size() == 8); + }); + }); + }); + }}; const Scenario webSocketStop{"WebSocket stop() is idempotent", [] { - InjectableSocket::reset(); - int closeHandlerCalls = 0; - webfront::testing::InlineTaskScope scope; - auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); - ws->onClose([&closeHandlerCalls](websocket::CloseEvent) { ++closeHandlerCalls; }); - - given("a started WebSocket that is stopped explicitly while a read is pending", [&] { - ws->start(); - ws->stop(); - - when("the still-pending read then completes with an error", [&] { - InjectableSocket::fail(make_error_code(errc::bad_file_descriptor)); - - then("the error is treated as harmless: no duplicate close handler call", [&] { - require(closeHandlerCalls == 0); - }); - }); - - when("stop() is called again", [&] { - then("the second call has no effect", [&] { requireNothrow([&] { ws->stop(); }); }); - }); - }); - - given("a started WebSocket whose pending read fails with no prior explicit stop", [&] { - ws->start(); - - when("the read completes with an error", [&] { - InjectableSocket::fail(make_error_code(errc::bad_file_descriptor)); - - then("the close handler fires exactly once", [&] { require(closeHandlerCalls == 1); }); - }); - }); -}}; + InjectableSocket::reset(); + int closeHandlerCalls = 0; + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + ws->onClose([&closeHandlerCalls](websocket::CloseEvent) { + ++closeHandlerCalls; + }); + + given("a started WebSocket that is stopped explicitly while a read is pending", [&] { + ws->start(); + ws->stop(); + + when("the still-pending read then completes with an error", [&] { + InjectableSocket::fail(make_error_code(errc::bad_file_descriptor)); + + then("the error is treated as harmless: no duplicate close handler call", [&] { + require(closeHandlerCalls == 0); + }); + }); + + when("stop() is called again", [&] { + then("the second call has no effect", [&] { + requireNothrow([&] { + ws->stop(); + }); + }); + }); + }); + + given("a started WebSocket whose pending read fails with no prior explicit stop", [&] { + ws->start(); + + when("the read completes with an error", [&] { + InjectableSocket::fail(make_error_code(errc::bad_file_descriptor)); + + then("the close handler fires exactly once", [&] { + require(closeHandlerCalls == 1); + }); + }); + }); + }}; const Scenario webSocketFramesEncode{"WebSocket frames encode extended payload lengths big-endian", [] { - struct Expected { - size_t size; - unsigned lengthField; - size_t headerSize; - }; - static constexpr std::array cases{{{125, 125, 2}, {126, 126, 4}, {65535, 126, 4}, {65536, 127, 10}}}; - for (const auto& expected : cases) { - const std::string text(expected.size, 'x'); - websocket::Frame frame(text); - check(frame.payloadLenField() == expected.lengthField); - check(frame.payloadSize() == expected.size); - check(frame.headerSize() == expected.headerSize); - } -}}; + struct Expected { + size_t size; + unsigned lengthField; + size_t headerSize; + }; + static constexpr std::array cases{ + {{125, 125, 2}, {126, 126, 4}, {65535, 126, 4}, {65536, 127, 10}} + }; + for (const auto& expected : cases) { + const std::string text(expected.size, 'x'); + websocket::Frame frame(text); + check(frame.payloadLenField() == expected.lengthField); + check(frame.payloadSize() == expected.size); + check(frame.headerSize() == expected.headerSize); + } + }}; diff --git a/test/unit/WebView2Tests.cpp b/test/unit/WebView2Tests.cpp index c22b1e27..ddefe2c9 100644 --- a/test/unit/WebView2Tests.cpp +++ b/test/unit/WebView2Tests.cpp @@ -1,7 +1,7 @@ #include "WebView2ControllerMock.hpp" #include "WebView2PolicyMocks.hpp" -#include #include +#include #include @@ -10,8 +10,8 @@ using namespace webfront::bdd; namespace { struct ViewRegistrationBrowser { Microsoft::WRL::ComPtr completion; - unsigned navigations = 0; - HRESULT navigationResult = S_OK; + unsigned navigations = 0; + HRESULT navigationResult = S_OK; HRESULT AddScriptToExecuteOnDocumentCreated(LPCWSTR, ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler* handler) { completion = handler; return S_OK; @@ -21,343 +21,381 @@ struct ViewRegistrationBrowser { return navigationResult; } }; -} +} // namespace const Scenario webView2Waits{"WebView2 waits for view association registration before navigation", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(std::chrono::milliseconds{25}); - session->createWindow(); - session->viewLaunch = {std::string(64, 'a'), "http://127.0.0.1:9002"}; - ViewRegistrationBrowser browser; - session->installViewAssociationThenNavigate(&browser); - require(browser.completion); - require(browser.navigations == 0); - require(session->startupTimer != 0); - when("registration completes successfully", [&] { - require(browser.completion->Invoke(S_OK, L"script") == S_OK); - require(browser.navigations == 1); - require(session->startupTimer == 0); - require(!session->failure); - }); - when("registration fails", [&] { - require(browser.completion->Invoke(E_FAIL, nullptr) == S_OK); - require(browser.navigations == 0); - require(session->failure); - require(session->startupTimer == 0); - }); - when("registration never completes", [&] { - requireThrows([&] { session->run(); }, contains("25 milliseconds")); - require(browser.navigations == 0); - }); - when("the window closes before registration completes", [&] { - session->close(); - require(browser.completion->Invoke(S_OK, L"script") == S_OK); - require(browser.navigations == 0); - }); - when("navigation fails after successful registration", [&] { - browser.navigationResult = E_FAIL; - require(browser.completion->Invoke(S_OK, L"script") == S_OK); - require(session->failure); - }); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(std::chrono::milliseconds{25}); + session->createWindow(); + session->viewLaunch = {std::string(64, 'a'), "http://127.0.0.1:9002"}; + ViewRegistrationBrowser browser; + session->installViewAssociationThenNavigate(&browser); + require(browser.completion); + require(browser.navigations == 0); + require(session->startupTimer != 0); + when("registration completes successfully", [&] { + require(browser.completion->Invoke(S_OK, L"script") == S_OK); + require(browser.navigations == 1); + require(session->startupTimer == 0); + require(!session->failure); + }); + when("registration fails", [&] { + require(browser.completion->Invoke(E_FAIL, nullptr) == S_OK); + require(browser.navigations == 0); + require(session->failure); + require(session->startupTimer == 0); + }); + when("registration never completes", [&] { + requireThrows( + [&] { + session->run(); + }, + contains("25 milliseconds")); + require(browser.navigations == 0); + }); + when("the window closes before registration completes", [&] { + session->close(); + require(browser.completion->Invoke(S_OK, L"script") == S_OK); + require(browser.navigations == 0); + }); + when("navigation fails after successful registration", [&] { + browser.navigationResult = E_FAIL; + require(browser.completion->Invoke(S_OK, L"script") == S_OK); + require(session->failure); + }); + }}; const Scenario webView2Installs{"WebView2 installs the window close script even without a view association secret", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(); - session->createWindow(); - ViewRegistrationBrowser browser; - session->installViewAssociationThenNavigate(&browser); - require(browser.completion); - require(browser.navigations == 0); - require(browser.completion->Invoke(S_OK, L"script") == S_OK); - require(browser.navigations == 1); - require(session->startupTimer == 0); - then("the script asks the host to close instead of relying on Chromium's window.close() filter", [&] { - const auto script = Session::windowCloseScript(); - require(script, contains("webfront:close-window")); - require(script, contains("window.top!==window")); - require(Session::windowCloseMessage() == L"webfront:close-window"); - }); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(); + session->createWindow(); + ViewRegistrationBrowser browser; + session->installViewAssociationThenNavigate(&browser); + require(browser.completion); + require(browser.navigations == 0); + require(browser.completion->Invoke(S_OK, L"script") == S_OK); + require(browser.navigations == 1); + require(session->startupTimer == 0); + then("the script asks the host to close instead of relying on Chromium's window.close() filter", [&] { + const auto script = Session::windowCloseScript(); + require(script, contains("webfront:close-window")); + require(script, contains("window.top!==window")); + require(Session::windowCloseMessage() == L"webfront:close-window"); + }); + }}; const Scenario webView2Encodes{"WebView2 encodes application paths", [] { - using webfront::frontend::detail::webview2::applicationUrl; - given("a UTF-8 filename containing percent-escaped URL delimiters", [&] { - then("all frontends share URI-reference encoding", [&] { - require(applicationUrl("9002", "folder/a b%23c%3Fd%25\xc3\xa9.html") == L"http://127.0.0.1:9002/folder/a%20b%23c%3Fd%25%C3%A9.html"); - require(applicationUrl("127.0.0.2", "9002", "index.html?x=1#result") == L"http://127.0.0.2:9002/index.html?x=1#result"); - }); - }); -}}; + using webfront::frontend::detail::webview2::applicationUrl; + given("a UTF-8 filename containing percent-escaped URL delimiters", [&] { + then("all frontends share URI-reference encoding", [&] { + require(applicationUrl("9002", "folder/a b%23c%3Fd%25\xc3\xa9.html") + == L"http://127.0.0.1:9002/folder/a%20b%23c%3Fd%25%C3%A9.html"); + require(applicationUrl("127.0.0.2", "9002", "index.html?x=1#result") + == L"http://127.0.0.2:9002/index.html?x=1#result"); + }); + }); + }}; const Scenario webView2Presentation{"WebView2 prepares a background and a first-frame probe", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(); - webfront::WindowOptions options; - options.background = "#123456"; - session->createWindow(false, options); - const auto brush = reinterpret_cast(GetClassLongPtrW(session->window, GCLP_HBRBACKGROUND)); - LOGBRUSH description{}; - require(GetObjectW(brush, sizeof(description), &description) == static_cast(sizeof(description))); - require(description.lbColor == RGB(0x12, 0x34, 0x56)); - const auto script = Session::firstFrameScript(); - require(script, contains("window.top!==window")); - require(script, contains("DOMContentLoaded")); - require(script, contains("webfront:first-frame")); - require(script, contains("requestAnimationFrame(()=>requestAnimationFrame")); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(); + webfront::WindowOptions options; + options.background = "#123456"; + session->createWindow(false, options); + const auto brush = reinterpret_cast(GetClassLongPtrW(session->window, GCLP_HBRBACKGROUND)); + LOGBRUSH description{}; + require(GetObjectW(brush, sizeof(description), &description) == static_cast(sizeof(description))); + require(description.lbColor == RGB(0x12, 0x34, 0x56)); + const auto script = Session::firstFrameScript(); + require(script, contains("window.top!==window")); + require(script, contains("DOMContentLoaded")); + require(script, contains("webfront:first-frame")); + require(script, contains("requestAnimationFrame(()=>requestAnimationFrame")); + }}; const Scenario webView2PresentationDeadline{"WebView2 reveals a page that never reports its first frame", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(); - session->createWindow(); - BYTE initial = 0; - require(GetLayeredWindowAttributes(session->window, nullptr, &initial, nullptr)); - require(initial == 3); - ViewRegistrationBrowser browser; - session->installViewAssociationThenNavigate(&browser); - require(browser.completion->Invoke(S_OK, L"script") == S_OK); - BYTE finalAlpha = 0; - const HWND window = session->window; - std::jthread observer([&] { - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; - do { - std::this_thread::sleep_for(std::chrono::milliseconds{20}); - GetLayeredWindowAttributes(window, nullptr, &finalAlpha, nullptr); - } while (finalAlpha != 255 && std::chrono::steady_clock::now() < deadline); - PostMessageW(window, WM_CLOSE, 0, 0); - }); - session->run(); - observer.join(); - require(finalAlpha == 255); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(); + session->createWindow(); + BYTE initial = 0; + require(GetLayeredWindowAttributes(session->window, nullptr, &initial, nullptr)); + require(initial == 3); + ViewRegistrationBrowser browser; + session->installViewAssociationThenNavigate(&browser); + require(browser.completion->Invoke(S_OK, L"script") == S_OK); + BYTE finalAlpha = 0; + const HWND window = session->window; + std::jthread observer([&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; + do { + std::this_thread::sleep_for(std::chrono::milliseconds{20}); + GetLayeredWindowAttributes(window, nullptr, &finalAlpha, nullptr); + } while (finalAlpha != 255 && std::chrono::steady_clock::now() < deadline); + PostMessageW(window, WM_CLOSE, 0, 0); + }); + session->run(); + observer.join(); + require(finalAlpha == 255); + }}; const Scenario webView2EngineSlowToStart{"WebView2 shows its window after the delay even when the engine never starts", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(); - session->createWindow(); // no environment, no controller, no navigation: the engine is still starting - BYTE initial = 0; - require(GetLayeredWindowAttributes(session->window, nullptr, &initial, nullptr)); - require(initial == 3); - BYTE finalAlpha = 0; - const HWND window = session->window; - std::jthread observer([&] { - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; - do { - std::this_thread::sleep_for(std::chrono::milliseconds{20}); - GetLayeredWindowAttributes(window, nullptr, &finalAlpha, nullptr); - } while (finalAlpha != 255 && std::chrono::steady_clock::now() < deadline); - PostMessageW(window, WM_CLOSE, 0, 0); - }); - session->run(); - observer.join(); - require(finalAlpha == 255); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(); + session->createWindow(); // no environment, no controller, no navigation: the engine is still starting + BYTE initial = 0; + require(GetLayeredWindowAttributes(session->window, nullptr, &initial, nullptr)); + require(initial == 3); + BYTE finalAlpha = 0; + const HWND window = session->window; + std::jthread observer([&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; + do { + std::this_thread::sleep_for(std::chrono::milliseconds{20}); + GetLayeredWindowAttributes(window, nullptr, &finalAlpha, nullptr); + } while (finalAlpha != 255 && std::chrono::steady_clock::now() < deadline); + PostMessageW(window, WM_CLOSE, 0, 0); + }); + session->run(); + observer.join(); + require(finalAlpha == 255); + }}; const Scenario webView2Runtime{"WebView2 runtime startup has a configurable deadline", [] { - using namespace webfront::frontend::detail::webview2; - using namespace std::chrono_literals; - requireNothrow([&] { Session{3min}; }); - requireThrows([&] { Session{0ms}; }); - requireThrows([&] { Session{-1ms}; }); - Apartment apartment; - auto session = std::make_shared(25ms); - session->createWindow(); - requireThrows([&] { session->run(); }, contains("25 milliseconds")); -}}; + using namespace webfront::frontend::detail::webview2; + using namespace std::chrono_literals; + requireNothrow([&] { + Session{3min}; + }); + requireThrows([&] { + Session{0ms}; + }); + requireThrows([&] { + Session{-1ms}; + }); + Apartment apartment; + auto session = std::make_shared(25ms); + session->createWindow(); + requireThrows( + [&] { + session->run(); + }, + contains("25 milliseconds")); + }}; const Scenario webView2Controller{"WebView2 controller closure is idempotent and preserves errors", [] { - using webfront::frontend::detail::webview2::Session; - auto session = std::make_shared(); - auto controller = Microsoft::WRL::Make(); - session->controller = controller; - controller->duringClose = [&] { - session->close(); - }; - controller->closeResult = E_FAIL; - session->close(); - session->close(); - require(controller->closeCalls == 1); - require(!session->controller); - require(session->failure); - requireThrows([&] { std::rethrow_exception(session->failure); }, contains("closing controller")); -}}; + using webfront::frontend::detail::webview2::Session; + auto session = std::make_shared(); + auto controller = Microsoft::WRL::Make(); + session->controller = controller; + controller->duringClose = [&] { + session->close(); + }; + controller->closeResult = E_FAIL; + session->close(); + session->close(); + require(controller->closeCalls == 1); + require(!session->controller); + require(session->failure); + requireThrows( + [&] { + std::rethrow_exception(session->failure); + }, + contains("closing controller")); + }}; const Scenario webView2Tolerates{"WebView2 tolerates a temporarily unresponsive renderer", [] { - using webfront::frontend::detail::webview2::Session; - then("unresponsive and recoverable auxiliary processes are not fatal", [&] { - requireNothrow([&] { Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE); }); - requireNothrow([&] { Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_GPU_PROCESS_EXITED); }); - }); - then("browser and main renderer exits remain fatal", [&] { - requireThrows([&] { Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED); }); - requireThrows([&] { Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED); }); - }); -}}; + using webfront::frontend::detail::webview2::Session; + then("unresponsive and recoverable auxiliary processes are not fatal", [&] { + requireNothrow([&] { + Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE); + }); + requireNothrow([&] { + Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_GPU_PROCESS_EXITED); + }); + }); + then("browser and main renderer exits remain fatal", [&] { + requireThrows([&] { + Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED); + }); + requireThrows([&] { + Session::checkProcessFailure(COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED); + }); + }); + }}; const Scenario webView2Errors{"WebView2 errors display the Windows HRESULT in hexadecimal", [] { - using webfront::frontend::detail::webview2::check; - then("the original HRESULT can be compared directly with Windows diagnostics", [&] { - requireThrows([&] { check(HRESULT_FROM_WIN32(ERROR_BAD_COMPRESSION_BUFFER), "creating environment"); }, contains("HRESULT 0x8007025D")); - requireNothrow([&] { check(S_OK, "creating environment"); }); - }); -}}; + using webfront::frontend::detail::webview2::check; + then("the original HRESULT can be compared directly with Windows diagnostics", [&] { + requireThrows( + [&] { + check(HRESULT_FROM_WIN32(ERROR_BAD_COMPRESSION_BUFFER), "creating environment"); + }, + contains("HRESULT 0x8007025D")); + requireNothrow([&] { + check(S_OK, "creating environment"); + }); + }); + }}; const Scenario webView2Forwards{"WebView2 forwards native focus and movement messages", [] { - using namespace webfront::frontend::detail::webview2; - Apartment apartment; - auto session = std::make_shared(); - session->createWindow(); - auto controller = Microsoft::WRL::Make(); - session->controller = controller; - when("the native window receives focus", [&] { - SendMessageW(session->window, WM_SETFOCUS, 0, 0); - then("focus is restored programmatically to the WebView", [&] { - require(controller->focusCalls == 1); - require(controller->focusReason == COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC); - }); - }); - when("the parent window moves", [&] { - SendMessageW(session->window, WM_MOVE, 0, 0); - then("the WebView is notified independently of resizing", [&] { - require(controller->positionCalls == 1); - }); - }); - when("Windows suggests new bounds after a DPI change", [&] { - RECT suggested{100, 100, 1000, 800}; - SendMessageW(session->window, WM_DPICHANGED, MAKELONG(144, 144), reinterpret_cast(&suggested)); - RECT actual{}; - require(GetWindowRect(session->window, &actual)); - then("the native window adopts the suggested size", [&] { - require(actual.right - actual.left == 900); - require(actual.bottom - actual.top == 700); - require(!session->failure); - }); - }); - when("controller shutdown sends reentrant window messages", [&] { - controller->duringClose = [&] { - controller->focusResult = HRESULT_FROM_WIN32(ERROR_INVALID_STATE); - controller->positionResult = HRESULT_FROM_WIN32(ERROR_INVALID_STATE); - SendMessageW(session->window, WM_SETFOCUS, 0, 0); - SendMessageW(session->window, WM_MOVE, 0, 0); - }; - session->close(); - then("closed controllers are not called and closure remains successful", [&] { - require(controller->focusCalls == 0); - require(controller->positionCalls == 0); - require(!session->failure); - }); - }); - then("the window has a background while the runtime starts", [&] { - require(GetClassLongPtrW(session->window, GCLP_HBRBACKGROUND) != 0); - }); -}}; + using namespace webfront::frontend::detail::webview2; + Apartment apartment; + auto session = std::make_shared(); + session->createWindow(); + auto controller = Microsoft::WRL::Make(); + session->controller = controller; + when("the native window receives focus", [&] { + SendMessageW(session->window, WM_SETFOCUS, 0, 0); + then("focus is restored programmatically to the WebView", [&] { + require(controller->focusCalls == 1); + require(controller->focusReason == COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC); + }); + }); + when("the parent window moves", [&] { + SendMessageW(session->window, WM_MOVE, 0, 0); + then("the WebView is notified independently of resizing", [&] { + require(controller->positionCalls == 1); + }); + }); + when("Windows suggests new bounds after a DPI change", [&] { + RECT suggested{100, 100, 1000, 800}; + SendMessageW(session->window, WM_DPICHANGED, MAKELONG(144, 144), reinterpret_cast(&suggested)); + RECT actual{}; + require(GetWindowRect(session->window, &actual)); + then("the native window adopts the suggested size", [&] { + require(actual.right - actual.left == 900); + require(actual.bottom - actual.top == 700); + require(!session->failure); + }); + }); + when("controller shutdown sends reentrant window messages", [&] { + controller->duringClose = [&] { + controller->focusResult = HRESULT_FROM_WIN32(ERROR_INVALID_STATE); + controller->positionResult = HRESULT_FROM_WIN32(ERROR_INVALID_STATE); + SendMessageW(session->window, WM_SETFOCUS, 0, 0); + SendMessageW(session->window, WM_MOVE, 0, 0); + }; + session->close(); + then("closed controllers are not called and closure remains successful", [&] { + require(controller->focusCalls == 0); + require(controller->positionCalls == 0); + require(!session->failure); + }); + }); + then("the window has a background while the runtime starts", [&] { + require(GetClassLongPtrW(session->window, GCLP_HBRBACKGROUND) != 0); + }); + }}; const Scenario webView2Only{"WebView2 only forwards user-initiated popups", [] { - using webfront::frontend::detail::webview2::Session; - auto session = std::make_shared(); - session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {.popups = webfront::PopupPolicy::systemBrowser}}; - auto args = Microsoft::WRL::Make(); - for (const BOOL initiated : {FALSE, TRUE}) { - when((initiated ? "the user requests a popup" : "a script requests a popup without user initiation"), [&] { - static bool launched = false; - launched = false; - args->userInitiated = initiated; - session->newWindowRequested(args.Get(), [](const std::string&) { - launched = true; - }); - then("only the user-initiated popup reaches the external launcher", [&] { - require(launched == (initiated != FALSE)); - require(args->handled); - require(!session->failure); - }); - }); - } -}}; + using webfront::frontend::detail::webview2::Session; + auto session = std::make_shared(); + session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", + {.popups = webfront::PopupPolicy::systemBrowser}}; + auto args = Microsoft::WRL::Make(); + for (const BOOL initiated : {FALSE, TRUE}) { + when((initiated ? "the user requests a popup" : "a script requests a popup without user initiation"), [&] { + static bool launched = false; + launched = false; + args->userInitiated = initiated; + session->newWindowRequested(args.Get(), [](const std::string&) { + launched = true; + }); + then("only the user-initiated popup reaches the external launcher", [&] { + require(launched == (initiated != FALSE)); + require(args->handled); + require(!session->failure); + }); + }); + } + }}; const Scenario webView2Popup{"WebView2 popup launcher failures leave the application running", [] { - using webfront::frontend::detail::webview2::Session; - auto session = std::make_shared(); - session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {.popups = webfront::PopupPolicy::systemBrowser}}; - auto args = Microsoft::WRL::Make(); - when("the external launcher throws a standard exception", [&] { - session->newWindowRequested(args.Get(), [](const std::string&) { - throw std::runtime_error("No URL association"); - }); - require(args->handled); - require(!session->failure); - require(!session->closed); - }); - when("the external launcher throws a non-standard exception", [&] { - session->newWindowRequested(args.Get(), [](const std::string&) { - throw 42; - }); - require(args->handled); - require(!session->failure); - require(!session->closed); - }); - when("marking the popup handled fails", [&] { - args->handledResult = E_FAIL; - session->newWindowRequested(args.Get()); - require(session->failure); - }); - when("reading the popup URI fails", [&] { - args->uriResult = E_FAIL; - session->newWindowRequested(args.Get()); - require(session->failure); - }); - when("reading popup user initiation fails", [&] { - args->userInitiatedResult = E_FAIL; - session->newWindowRequested(args.Get()); - require(session->failure); - }); -}}; + using webfront::frontend::detail::webview2::Session; + auto session = std::make_shared(); + session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", + {.popups = webfront::PopupPolicy::systemBrowser}}; + auto args = Microsoft::WRL::Make(); + when("the external launcher throws a standard exception", [&] { + session->newWindowRequested(args.Get(), [](const std::string&) { + throw std::runtime_error("No URL association"); + }); + require(args->handled); + require(!session->failure); + require(!session->closed); + }); + when("the external launcher throws a non-standard exception", [&] { + session->newWindowRequested(args.Get(), [](const std::string&) { + throw 42; + }); + require(args->handled); + require(!session->failure); + require(!session->closed); + }); + when("marking the popup handled fails", [&] { + args->handledResult = E_FAIL; + session->newWindowRequested(args.Get()); + require(session->failure); + }); + when("reading the popup URI fails", [&] { + args->uriResult = E_FAIL; + session->newWindowRequested(args.Get()); + require(session->failure); + }); + when("reading popup user initiation fails", [&] { + args->userInitiatedResult = E_FAIL; + session->newWindowRequested(args.Get()); + require(session->failure); + }); + }}; const Scenario webView2Content{"WebView2 content controls map to engine settings", [] { - auto settings = Microsoft::WRL::Make(); - using webfront::frontend::detail::webview2::configureContentSettings; - configureContentSettings(settings.Get(), {}); - require(settings->devTools); - require(settings->contextMenus); - configureContentSettings(settings.Get(), {.devToolsEnabled = false}); - require(!settings->devTools); - require(settings->contextMenus); - configureContentSettings(settings.Get(), {.contextMenusEnabled = false}); - require(settings->devTools); - require(!settings->contextMenus); - settings->settingsResult = E_FAIL; - requireThrows([&] { configureContentSettings(settings.Get(), {}); }); -}}; + auto settings = Microsoft::WRL::Make(); + using webfront::frontend::detail::webview2::configureContentSettings; + configureContentSettings(settings.Get(), {}); + require(settings->devTools); + require(settings->contextMenus); + configureContentSettings(settings.Get(), {.devToolsEnabled = false}); + require(!settings->devTools); + require(settings->contextMenus); + configureContentSettings(settings.Get(), {.contextMenusEnabled = false}); + require(settings->devTools); + require(!settings->contextMenus); + settings->settingsResult = E_FAIL; + requireThrows([&] { + configureContentSettings(settings.Get(), {}); + }); + }}; const Scenario apartmentWebView2{"The apartment of a WebView2 window leaves the thread as it found it", [] { - using namespace webfront::frontend::detail::webview2; - // A thread of its own: no other scenario and no engine has initialized COM there (#564). - struct State { - HRESULT result{}; - APTTYPE apartment{}; - APTTYPEQUALIFIER qualifier{}; - bool operator==(const State&) const = default; - static State read() { - State state; - state.result = CoGetApartmentType(&state.apartment, &state.qualifier); - return state; - } - }; - State before, during, after; - std::thread([&] { - before = State::read(); - { - Apartment apartment; - during = State::read(); - } - after = State::read(); - }).join(); - require(during.result == S_OK); - require((during.apartment == APTTYPE_STA || during.apartment == APTTYPE_MAINSTA)); - require(after == before); -}}; + using namespace webfront::frontend::detail::webview2; + // A thread of its own: no other scenario and no engine has initialized COM there (#564). + struct State { + HRESULT result{}; + APTTYPE apartment{}; + APTTYPEQUALIFIER qualifier{}; + bool operator==(const State&) const = default; + static State read() { + State state; + state.result = CoGetApartmentType(&state.apartment, &state.qualifier); + return state; + } + }; + State before, during, after; + std::thread([&] { + before = State::read(); + { + Apartment apartment; + during = State::read(); + } + after = State::read(); + }).join(); + require(during.result == S_OK); + require((during.apartment == APTTYPE_STA || during.apartment == APTTYPE_MAINSTA)); + require(after == before); + }}; diff --git a/test/unit/WfDriverTests.cpp b/test/unit/WfDriverTests.cpp index 0619a8a6..bfe5bbc4 100644 --- a/test/unit/WfDriverTests.cpp +++ b/test/unit/WfDriverTests.cpp @@ -1,9 +1,8 @@ #include "../driver/WfDriver.hpp" #include -#include - #include +#include using namespace webfront::bdd; @@ -19,142 +18,153 @@ webfront::testdriver::Options parseDriver(std::initializer_list ext } // namespace const Scenario usageBeforeEngine{"A missing project directory is a usage error that main reports before an engine starts", [] { - given("an options structure naming a directory that does not exist, and one naming a directory that does", [&] { - webfront::testdriver::Options missing = parseDriver({"list"}); - missing.project = std::filesystem::temp_directory_path() / "webfront-no-such-project-628"; - webfront::testdriver::Options present = parseDriver({"list"}); - present.project = std::filesystem::temp_directory_path(); - then("only the missing one is refused, with a usage error", [&] { - requireThrows([&] { webfront::testdriver::requireProject(missing); }); - requireNothrow([&] { webfront::testdriver::requireProject(present); }); - }); - }); -}}; + given("an options structure naming a directory that does not exist, and one naming a directory that does", [&] { + webfront::testdriver::Options missing = parseDriver({"list"}); + missing.project = std::filesystem::temp_directory_path() / "webfront-no-such-project-628"; + webfront::testdriver::Options present = parseDriver({"list"}); + present.project = std::filesystem::temp_directory_path(); + then("only the missing one is refused, with a usage error", [&] { + requireThrows([&] { + webfront::testdriver::requireProject(missing); + }); + requireNothrow([&] { + webfront::testdriver::requireProject(present); + }); + }); + }); + }}; const Scenario browserTest{"Browser test diagnostics retain HTTP failures without filling the transcript with bridge traffic", [] { - std::ostringstream output; - auto* previous = std::clog.rdbuf(output.rdbuf()); - const auto sink = webfront::testdriver::logRequests(); - webfront::log::info("Received request GET on /scripts.js"); - webfront::log::info(" responding http 404"); - webfront::log::info("onMessage(binary): bridge traffic"); - webfront::log::warn("HTTP asset request failed: denied"); - webfront::log::warn("File response ended its response early: short read"); - webfront::log::warn("WebSocket disconnected unexpectedly"); - webfront::log::removeSinks(sink); - std::clog.rdbuf(previous); - webfront::log::setLogLevel(webfront::log::Disabled); - then("the resource, status and failures remain, but ordinary bridge messages do not", [&] { - check(output.str().find("GET on /scripts.js") != std::string::npos); - check(output.str().find("responding http 404") != std::string::npos); - check(output.str().find("request failed: denied") != std::string::npos); - check(output.str().find("response early: short read") != std::string::npos); - check(output.str().find("WebSocket disconnected unexpectedly") != std::string::npos); - check(output.str().find("bridge traffic") == std::string::npos); - }); -}}; + std::ostringstream output; + auto* previous = std::clog.rdbuf(output.rdbuf()); + const auto sink = webfront::testdriver::logRequests(); + webfront::log::info("Received request GET on /scripts.js"); + webfront::log::info(" responding http 404"); + webfront::log::info("onMessage(binary): bridge traffic"); + webfront::log::warn("HTTP asset request failed: denied"); + webfront::log::warn("File response ended its response early: short read"); + webfront::log::warn("WebSocket disconnected unexpectedly"); + webfront::log::removeSinks(sink); + std::clog.rdbuf(previous); + webfront::log::setLogLevel(webfront::log::Disabled); + then("the resource, status and failures remain, but ordinary bridge messages do not", [&] { + check(output.str().find("GET on /scripts.js") != std::string::npos); + check(output.str().find("responding http 404") != std::string::npos); + check(output.str().find("request failed: denied") != std::string::npos); + check(output.str().find("response early: short read") != std::string::npos); + check(output.str().find("WebSocket disconnected unexpectedly") != std::string::npos); + check(output.str().find("bridge traffic") == std::string::npos); + }); + }}; const Scenario driverRepeats{"The driver repeats its close request until the window has closed", [] { - using namespace std::chrono_literals; - using webfront::testdriver::closeUntilShown; - std::stop_source shown; - std::atomic requests = 0; - given("a window that only exists after a few requests reached nothing", [&] { - const auto requestClose = [&] { - // The third request finds the window; show() then returns. - if (++requests < 3) - return false; - shown.request_stop(); - return true; - }; - then("the request is repeated until show() returns", [&] { - require(closeUntilShown(shown.get_token(), requestClose, 1h)); - require(requests == 3); - }); - }); - given("a window that never closes", [&] { - then("the driver gives up after its patience", [&] { - require(!(closeUntilShown( - shown.get_token(), - [&] { - ++requests; - return true; - }, - 30ms))); - require(requests >= 1); - }); - }); -}}; + using namespace std::chrono_literals; + using webfront::testdriver::closeUntilShown; + std::stop_source shown; + std::atomic requests = 0; + given("a window that only exists after a few requests reached nothing", [&] { + const auto requestClose = [&] { + // The third request finds the window; show() then returns. + if (++requests < 3) + return false; + shown.request_stop(); + return true; + }; + then("the request is repeated until show() returns", [&] { + require(closeUntilShown(shown.get_token(), requestClose, 1h)); + require(requests == 3); + }); + }); + given("a window that never closes", [&] { + then("the driver gives up after its patience", [&] { + require(!(closeUntilShown( + shown.get_token(), + [&] { + ++requests; + return true; + }, + 30ms))); + require(requests >= 1); + }); + }); + }}; const Scenario pageEnd{"The page's end releases the driver's close without a time limit", [] { - using namespace std::chrono_literals; - webfront::testdriver::DriverDeadline deadline{1h}; - std::stop_source shown; - std::jthread page([&] { - deadline.finish(); - }); - require(!deadline.expired(shown.get_token())); - require(!shown.stop_requested()); -}}; + using namespace std::chrono_literals; + webfront::testdriver::DriverDeadline deadline{1h}; + std::stop_source shown; + std::jthread page([&] { + deadline.finish(); + }); + require(!deadline.expired(shown.get_token())); + require(!shown.stop_requested()); + }}; -const Scenario driverWebView2{"Driver WebView2 profiles isolate environments served at identical URLs", [] { - using namespace webfront; - static_assert(std::is_same_v, frontend::WebView2FrontendWithOptions>); - static_assert(std::is_same_v, testdriver::DriverCEFFrontend>); - const auto first = testdriver::DriverWebView2Options::get("first-session"); - const auto second = testdriver::DriverWebView2Options::get("second-session"); - require(first.userDataFolder == std::filesystem::path("first-session")); - require(second.userDataFolder != first.userDataFolder); - require(testdriver::DriverWebView2Options::get(nullptr).userDataFolder.empty()); - require(testdriver::DriverWebView2Options::get("").userDataFolder.empty()); -}}; +const Scenario driverWebView2{ + "Driver WebView2 profiles isolate environments served at identical URLs", + [] { + using namespace webfront; + static_assert( + std::is_same_v, frontend::WebView2FrontendWithOptions>); + static_assert(std::is_same_v, testdriver::DriverCEFFrontend>); + const auto first = testdriver::DriverWebView2Options::get("first-session"); + const auto second = testdriver::DriverWebView2Options::get("second-session"); + require(first.userDataFolder == std::filesystem::path("first-session")); + require(second.userDataFolder != first.userDataFolder); + require(testdriver::DriverWebView2Options::get(nullptr).userDataFolder.empty()); + require(testdriver::DriverWebView2Options::get("").userDataFolder.empty()); + }}; const Scenario singleCommand{"A single-command watchdog has a separate budget after bootstrap", [] { - using namespace std::chrono_literals; - given("an overall deadline and a shorter command limit", [&] { - const auto options = parseDriver({"--timeout", "100", "--command-timeout", "4", "--", "run", "sleep"}); - then("both limits survive argument parsing independently", [&] { - require(options.timeout == 100s); - require(options.commandTimeout == 4s); - require(options.command == std::vector{"run", "sleep"}); - }); - }); - given("no separate command limit", [&] { - require(!parseDriver({"list"}).commandTimeout); - }); - given("invalid or ambiguous limits", [&] { - requireThrows([&] { parseDriver({"--command-timeout", "0", "list"}); }); - requireThrows([&] { parseDriver({"--command-timeout", "bad", "list"}); }); - }); -}}; + using namespace std::chrono_literals; + given("an overall deadline and a shorter command limit", [&] { + const auto options = parseDriver({"--timeout", "100", "--command-timeout", "4", "--", "run", "sleep"}); + then("both limits survive argument parsing independently", [&] { + require(options.timeout == 100s); + require(options.commandTimeout == 4s); + require(options.command == std::vector{"run", "sleep"}); + }); + }); + given("no separate command limit", [&] { + require(!parseDriver({"list"}).commandTimeout); + }); + given("invalid or ambiguous limits", [&] { + requireThrows([&] { + parseDriver({"--command-timeout", "0", "list"}); + }); + requireThrows([&] { + parseDriver({"--command-timeout", "bad", "list"}); + }); + }); + }}; const Scenario driverWatchdog{"The driver watchdog keeps a native command limit inside the overall budget", [] { - using namespace std::chrono_literals; - using webfront::testdriver::DriverDeadline; - DriverDeadline deadline{1h}; - deadline.beginCase(1ms); - std::stop_source fallback; - std::jthread cancelIfBroken([&](std::stop_token stop) { - std::mutex mutex; - std::condition_variable_any wake; - std::unique_lock lock{mutex}; - if (!wake.wait_for(lock, - stop, - 10s, - [] { - return false; - }) - && !stop.stop_requested()) - fallback.request_stop(); - }); - require(deadline.expired(fallback.get_token())); - // Starting a command never extends an already expiring overall limit. - DriverDeadline overall{1ms}; - overall.beginCase(1h); - require(overall.expired(fallback.get_token())); - cancelIfBroken.request_stop(); - deadline.endCase(); - std::stop_source cancelled; - cancelled.request_stop(); - require(!deadline.expired(cancelled.get_token())); -}}; + using namespace std::chrono_literals; + using webfront::testdriver::DriverDeadline; + DriverDeadline deadline{1h}; + deadline.beginCase(1ms); + std::stop_source fallback; + std::jthread cancelIfBroken([&](std::stop_token stop) { + std::mutex mutex; + std::condition_variable_any wake; + std::unique_lock lock{mutex}; + if (!wake.wait_for(lock, + stop, + 10s, + [] { + return false; + }) + && !stop.stop_requested()) + fallback.request_stop(); + }); + require(deadline.expired(fallback.get_token())); + // Starting a command never extends an already expiring overall limit. + DriverDeadline overall{1ms}; + overall.beginCase(1h); + require(overall.expired(fallback.get_token())); + cancelIfBroken.request_stop(); + deadline.endCase(); + std::stop_source cancelled; + cancelled.request_stop(); + require(!deadline.expired(cancelled.get_token())); + }}; diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 8bcbc051..c17081a6 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief The registry of the secondary windows and the session of one open(), shared by the native frontends (#652, #616). -#include #include #include #include #include +#include #include #include @@ -23,16 +23,16 @@ std::vector events; // what the fake toolkit was asked, in order // A window of a fake toolkit: it closes when asked, or by itself during its start. struct FakeSession { - std::string page; - bool closed = false; - std::exception_ptr failure; - std::function closedHook; - bool inCallback = false; // true while its own closedHook runs - bool closeOnStart = false; - std::exception_ptr failOnStart; + std::string page; + bool closed = false; + std::exception_ptr failure; + std::function closedHook; + bool inCallback = false; // true while its own closedHook runs + bool closeOnStart = false; + std::exception_ptr failOnStart; static inline std::function destroyProbe; // runs in every destructor: what a window's teardown can observe - explicit FakeSession(std::string name = {}) : page(std::move(name)) { } + explicit FakeSession(std::string name = {}) : page(std::move(name)) {} ~FakeSession() { events.push_back("destroy " + page); if (destroyProbe) @@ -60,7 +60,7 @@ struct FakeSession { }; struct FakeHooks { - static constexpr std::string_view name = "FakeFrontend"; + static constexpr std::string_view name = "FakeFrontend"; int reapsScheduled = 0; bool canClose = true; @@ -110,203 +110,238 @@ struct SessionTag; struct PublishTag; } // namespace -const Scenario secondaryWindowRegistry{"The registry of the secondary windows is shared by the native frontends", {"window-registry"}, [] { - given("a registry whose first window is open", [&] { - events.clear(); - Registry windows; - FakeSession first("first"); - windows.primary = &first; +const Scenario secondaryWindowRegistry{ + "The registry of the secondary windows is shared by the native frontends", + {"window-registry"}, + [] { + given("a registry whose first window is open", [&] { + events.clear(); + Registry windows; + FakeSession first("first"); + windows.primary = &first; - when("a page is opened", [&] { - openPage(windows, "a.html"); - then("the window is created, started and registered", [&] { - require(windows.secondary.size() == 1); - check(events == std::vector{"create a.html", "start a.html"}); - }); - andWhen("the same page is opened again", [&] { + when("a page is opened", [&] { openPage(windows, "a.html"); - then("the window already showing it comes to the front and nothing is created", [&] { - check(happened("present a.html")); - check(std::ranges::count(events, "create a.html") == 1); - check(windows.secondary.size() == 1); + then("the window is created, started and registered", [&] { + require(windows.secondary.size() == 1); + check(events == std::vector{"create a.html", "start a.html"}); + }); + andWhen("the same page is opened again", [&] { + openPage(windows, "a.html"); + then("the window already showing it comes to the front and nothing is created", [&] { + check(happened("present a.html")); + check(std::ranges::count(events, "create a.html") == 1); + check(windows.secondary.size() == 1); + }); + }); + andWhen("its window closes", [&] { + require(windows.close("a.html")); + then("it leaves the table, is destroyed later and not in its own callback", [&] { + check(windows.secondary.empty()); + check(windows.finished.size() == 1); + check(windows.hooks.reapsScheduled == 1); + check(!happened("destroy a.html")); + windows.reap(); + check(happened("destroy a.html")); + check(!happened("destroyed in its own callback")); + check(windows.finished.empty()); + }); + andWhen("the page is opened again", [&] { + windows.reap(); + openPage(windows, "a.html"); + then("it is a new window", [&] { + check(std::ranges::count(events, "create a.html") == 2); + check(windows.secondary.size() == 1); + }); + }); + }); + andWhen("closing is asked for a page nobody shows, or for one that cannot close", [&] { + windows.hooks.canClose = false; + then("it answers false", [&] { + check(!windows.close("b.html")); + check(!windows.close("a.html")); + }); }); }); - andWhen("its window closes", [&] { - require(windows.close("a.html")); - then("it leaves the table, is destroyed later and not in its own callback", [&] { + + when("a window closes by itself while it starts", [&] { + then("the caller learns why, and the page is not registered", [&] { + checkThrows( + [&] { + openPage(windows, "a.html", true, std::make_exception_ptr(std::runtime_error("navigation failed"))); + }, + contains("navigation failed")); check(windows.secondary.empty()); - check(windows.finished.size() == 1); - check(windows.hooks.reapsScheduled == 1); - check(!happened("destroy a.html")); - windows.reap(); - check(happened("destroy a.html")); - check(!happened("destroyed in its own callback")); - check(windows.finished.empty()); }); - andWhen("the page is opened again", [&] { + andWhen("it closed without a failure", [&] { + then("the caller still gets an error that names the page", [&] { + checkThrows( + [&] { + openPage(windows, "b.html", true); + }, + contains("'b.html' closed while it started")); + check(windows.secondary.empty()); + }); + }); + andWhen("the page is opened once more", [&] { windows.reap(); openPage(windows, "a.html"); - then("it is a new window", [&] { - check(std::ranges::count(events, "create a.html") == 2); + then("it works", [&] { check(windows.secondary.size() == 1); }); }); }); - andWhen("closing is asked for a page nobody shows, or for one that cannot close", [&] { - windows.hooks.canClose = false; - then("it answers false", [&] { - check(!windows.close("b.html")); - check(!windows.close("a.html")); - }); - }); - }); - when("a window closes by itself while it starts", [&] { - then("the caller learns why, and the page is not registered", [&] { - checkThrows([&] { - openPage(windows, "a.html", true, std::make_exception_ptr(std::runtime_error("navigation failed"))); - }, contains("navigation failed")); - check(windows.secondary.empty()); - }); - andWhen("it closed without a failure", [&] { - then("the caller still gets an error that names the page", [&] { - checkThrows([&] { openPage(windows, "b.html", true); }, contains("'b.html' closed while it started")); - check(windows.secondary.empty()); + when("the first window closes in the pass that handles the request", [&] { + first.closed = true; + then("nothing is built and the caller is told", [&] { + checkThrows( + [&] { + openPage(windows, "a.html"); + }, + contains("FakeFrontend: no window of the application is open")); + check(!happened("create a.html")); }); }); - andWhen("the page is opened once more", [&] { - windows.reap(); + + when("the first window closes while a secondary one still shows the page", [&] { openPage(windows, "a.html"); - then("it works", [&] { + events.clear(); + first.closed = true; + then("asking for that page brings its window to the front instead of failing", [&] { + openPage(windows, "a.html"); + check(!happened("create a.html")); check(windows.secondary.size() == 1); }); }); - }); - when("the first window closes in the pass that handles the request", [&] { - first.closed = true; - then("nothing is built and the caller is told", [&] { - checkThrows([&] { openPage(windows, "a.html"); }, contains("FakeFrontend: no window of the application is open")); - check(!happened("create a.html")); + when("a window opens a page while the others are destroyed", [&] { + openPage(windows, "a.html"); + bool lateOpened = true; + FakeSession::destroyProbe = [&] { + lateOpened = openPage(windows, "late.html"); // a destructor cannot be refused by an exception: it is told false + }; + windows.clear(); + FakeSession::destroyProbe = nullptr; + then("no window outlives the session, and the request is told it was refused", [&] { + check(!lateOpened); + check(windows.secondary.empty()); + check(!happened("create late.html")); + }); }); - }); - when("the first window closes while a secondary one still shows the page", [&] { - openPage(windows, "a.html"); - events.clear(); - first.closed = true; - then("asking for that page brings its window to the front instead of failing", [&] { + when("the first window ends with secondary windows open", [&] { openPage(windows, "a.html"); - check(!happened("create a.html")); - check(windows.secondary.size() == 1); + openPage(windows, "b.html"); + require(windows.close("a.html")); + events.clear(); + windows.clear(); + then("the reap is withdrawn and every session is destroyed with its hook cleared", [&] { + require(!events.empty()); + check(events.front() == "cancel reap"); + check(happened("destroy a.html")); + check(happened("destroy b.html")); + check(!happened("hook still set b.html")); + check(windows.secondary.empty() && windows.finished.empty()); + check(windows.primary == nullptr); + }); }); - }); - - when("a window opens a page while the others are destroyed", [&] { - openPage(windows, "a.html"); - bool lateOpened = true; - FakeSession::destroyProbe = [&] { - lateOpened = openPage(windows, "late.html"); // a destructor cannot be refused by an exception: it is told false - }; windows.clear(); - FakeSession::destroyProbe = nullptr; - then("no window outlives the session, and the request is told it was refused", [&] { - check(!lateOpened); - check(windows.secondary.empty()); - check(!happened("create late.html")); - }); }); - - when("the first window ends with secondary windows open", [&] { - openPage(windows, "a.html"); - openPage(windows, "b.html"); - require(windows.close("a.html")); - events.clear(); - windows.clear(); - then("the reap is withdrawn and every session is destroyed with its hook cleared", [&] { - require(!events.empty()); - check(events.front() == "cancel reap"); - check(happened("destroy a.html")); - check(happened("destroy b.html")); - check(!happened("hook still set b.html")); - check(windows.secondary.empty() && windows.finished.empty()); - check(windows.primary == nullptr); + given("a registry without a first window", [&] { + Registry windows; + then("opening is refused", [&] { + checkThrows( + [&] { + openPage(windows, "a.html"); + }, + contains("show() it before opening another")); }); }); - windows.clear(); - }); - given("a registry without a first window", [&] { - Registry windows; - then("opening is refused", [&] { - checkThrows([&] { openPage(windows, "a.html"); }, contains("show() it before opening another")); - }); - }); -}}; + }}; -const Scenario interfaceSessionOrder{"The session of an open() attaches, publishes and withdraws in order", {"window-registry"}, [] { - given("an open() that attaches its loop", [&] { - auto& host = uiExecutorHostOf(); - auto& windowHost = nativeWindowHostOf(); - int handle = 0; - Registry windows; - FakeSession first("first"); - const auto published = [&] { - return windowHost.window(); - }; - when("the session is held", [&] { - { - frontend::detail::InterfaceSession session(host, windowHost, windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); - then("the executor is available, the window published and the first window registered", [&] { - check(host.executor().available()); - check(windows.primary == &first); - const auto window = published().get(); - require(window.has_value()); - check(window->pointer == &handle); - }); - andWhen("another open() starts", [&] { - then("it is refused", [&] { - checkThrows([&] { frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }, - contains("FakeFrontend: open() is already running")); +const Scenario interfaceSessionOrder{ + "The session of an open() attaches, publishes and withdraws in order", + {"window-registry"}, + [] { + given("an open() that attaches its loop", [&] { + auto& host = uiExecutorHostOf(); + auto& windowHost = nativeWindowHostOf(); + int handle = 0; + Registry windows; + FakeSession first("first"); + const auto published = [&] { + return windowHost.window(); + }; + when("the session is held", [&] { + { + frontend::detail::InterfaceSession session(host, + windowHost, + windows, + first, + [] {}, + {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + then("the executor is available, the window published and the first window registered", [&] { + check(host.executor().available()); + check(windows.primary == &first); + const auto window = published().get(); + require(window.has_value()); + check(window->pointer == &handle); }); + andWhen("another open() starts", [&] { + then("it is refused", [&] { + checkThrows( + [&] { + frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); + }, + contains("FakeFrontend: open() is already running")); + }); + }); + openPage(windows, "a.html"); + events.clear(); + FakeSession::destroyProbe = [&] { // the secondary windows are destroyed while the window is still published + if (!published().get().has_value() || !host.executor().available()) + events.push_back("withdrawn too early"); + }; + } + FakeSession::destroyProbe = nullptr; + then("the secondary windows are cleared first, then the window is withdrawn and the host closed", [&] { + check(!events.empty() && events.front() == "cancel reap"); + check(happened("destroy a.html") && !happened("withdrawn too early")); + check(windows.primary == nullptr && windows.secondary.empty()); + check(!host.executor().available()); + check(!published().get().has_value()); }); - openPage(windows, "a.html"); - events.clear(); - FakeSession::destroyProbe = [&] { // the secondary windows are destroyed while the window is still published - if (!published().get().has_value() || !host.executor().available()) - events.push_back("withdrawn too early"); - }; - } - FakeSession::destroyProbe = nullptr; - then("the secondary windows are cleared first, then the window is withdrawn and the host closed", [&] { - check(!events.empty() && events.front() == "cancel reap"); - check(happened("destroy a.html") && !happened("withdrawn too early")); - check(windows.primary == nullptr && windows.secondary.empty()); - check(!host.executor().available()); - check(!published().get().has_value()); - }); - andWhen("a later open() starts", [&] { - then("it is accepted", [&] { - checkNothrow([&] { frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }); + andWhen("a later open() starts", [&] { + then("it is accepted", [&] { + checkNothrow([&] { + frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); + }); + }); }); }); }); - }); - given("a loop that is already attached", [&] { - auto& host = uiExecutorHostOf(); - host.attach([] {}); - Registry windows; - FakeSession first("first"); - int handle = 0; - then("a second session throws and leaves the first loop attached", [&] { - checkThrows([&] { - frontend::detail::InterfaceSession session(host, nativeWindowHostOf(), windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + given("a loop that is already attached", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); + Registry windows; + FakeSession first("first"); + int handle = 0; + then("a second session throws and leaves the first loop attached", [&] { + checkThrows([&] { + frontend::detail::InterfaceSession session(host, + nativeWindowHostOf(), + windows, + first, + [] {}, + {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + }); + check(host.executor().available()); + check(windows.primary == nullptr); }); - check(host.executor().available()); - check(windows.primary == nullptr); + host.close(); }); - host.close(); - }); -}}; + }}; namespace window_registry_fakes { // named, not anonymous: the clang warning for unused constants of anonymous types struct FakeHost; @@ -319,19 +354,23 @@ struct FakeFrontend : EmbeddedFrontend { static constexpr bool compiled = true; static constexpr std::string_view name = "FakeFrontend"; static constexpr std::string_view enable = "Configure it."; - using Host = FakeHost; - using Options = ViewOptions; + using Host = FakeHost; + using Options = ViewOptions; static inline std::vector opened; - static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { - opened.push_back(std::string(address) + ":" + std::string(port) + "/" + std::string(file) + (options.window.title.empty() ? "" : " " + options.window.title) + - (options.launch.secret.empty() ? "" : " launched") + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools")); + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { + opened.push_back(std::string(address) + ":" + std::string(port) + "/" + std::string(file) + + (options.window.title.empty() ? "" : " " + options.window.title) + (options.launch.secret.empty() ? "" : " launched") + + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools")); } - static void closeNative(const NativeWindowHandle&) { } + static void closeNative(const NativeWindowHandle&) {} static inline std::vector openedSecondary; - static void openSecondaryNative(std::string_view, std::string_view, std::string_view page, const Options& options) { - openedSecondary.push_back(std::string(page) + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools") + " " + options.window.title + " " + options.launch.secret); + static void openSecondaryNative(std::string_view, std::string_view, std::string_view page, const Options& options) { + openedSecondary.push_back(std::string(page) + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools") + " " + options.window.title + " " + + options.launch.secret); + } + static bool closeSecondaryNative(std::string_view) { + return true; } - static bool closeSecondaryNative(std::string_view) { return true; } }; // A frontend whose options come from a provider (WebView2FrontendWithOptions): a call overrides only what it passes. @@ -339,37 +378,42 @@ struct ConfiguredFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = false; static constexpr bool compiled = true; static constexpr std::string_view name = "ConfiguredFrontend"; - using Host = ConfiguredFrontend; - using Options = ViewOptions; + using Host = ConfiguredFrontend; + using Options = ViewOptions; static inline std::vector opened; - static ViewOptions defaultOptions() { - return {.window = {.title = "configured"}, .launch = {"configured-secret", "configured-origin"}}; + static ViewOptions defaultOptions() { + return { + .window = {.title = "configured"}, + .launch = {"configured-secret", "configured-origin"} + }; } static void openNative(std::string_view, std::string_view, std::string_view file, const Options& options) { opened.push_back(std::string(file) + " " + options.window.title + " " + options.launch.secret); } - static void closeNative(const NativeWindowHandle&) { } + static void closeNative(const NativeWindowHandle&) {} }; // A configured frontend with secondary windows (WebView2FrontendWithOptions): a secondary window does not ask the provider. struct ConfiguredSecondaryFrontend : EmbeddedFrontend { - static constexpr bool secondaryWindows = true; - static constexpr bool compiled = true; - static constexpr std::string_view name = "ConfiguredSecondaryFrontend"; - using Host = ConfiguredSecondaryFrontend; - using Options = ViewOptions; + static constexpr bool secondaryWindows = true; + static constexpr bool compiled = true; + static constexpr std::string_view name = "ConfiguredSecondaryFrontend"; + using Host = ConfiguredSecondaryFrontend; + using Options = ViewOptions; static inline int providerCalls = 0; static inline std::vector openedSecondary; - static ViewOptions defaultOptions() { + static ViewOptions defaultOptions() { ++providerCalls; throw std::runtime_error("the provider failed"); } - static void openNative(std::string_view, std::string_view, std::string_view, const Options&) { } - static void closeNative(const NativeWindowHandle&) { } + static void openNative(std::string_view, std::string_view, std::string_view, const Options&) {} + static void closeNative(const NativeWindowHandle&) {} static void openSecondaryNative(std::string_view, std::string_view, std::string_view page, const Options& options) { openedSecondary.push_back(std::string(page) + " " + options.window.title + " " + options.launch.secret); } - static bool closeSecondaryNative(std::string_view) { return true; } + static bool closeSecondaryNative(std::string_view) { + return true; + } }; struct AbsentFrontend : EmbeddedFrontend { @@ -377,18 +421,18 @@ struct AbsentFrontend : EmbeddedFrontend { static constexpr bool compiled = false; static constexpr std::string_view name = "AbsentFrontend"; static constexpr std::string_view enable = "Configure on Nowhere with -DNOWHERE=ON"; - using Host = UnavailableHost; - using Options = ViewOptions; + using Host = UnavailableHost; + using Options = ViewOptions; }; struct SingleWindowFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = false; static constexpr bool compiled = true; static constexpr std::string_view name = "SingleWindowFrontend"; - using Host = SingleWindowFrontend; - using Options = ViewOptions; - static void openNative(std::string_view, std::string_view, std::string_view, const Options&) { } - static void closeNative(const NativeWindowHandle&) { } + using Host = SingleWindowFrontend; + using Options = ViewOptions; + static void openNative(std::string_view, std::string_view, std::string_view, const Options&) {} + static void closeNative(const NativeWindowHandle&) {} }; template @@ -401,114 +445,158 @@ static_assert(FrontendType && FrontendType && Fron } // namespace window_registry_fakes using namespace window_registry_fakes; -const Scenario embeddedFrontendFacade{"The facade of the embedded frontends gives every overload of open()", {"window-registry"}, [] { - given("a frontend that declares its toolkit calls", [&] { - FakeFrontend::opened.clear(); - when("it is opened with every form the application uses", [&] { - FakeFrontend::open("9000", "a.html"); - FakeFrontend::open("1.2.3.4", "9001", "b.html"); - FakeFrontend::open("1.2.3.4", "9002", "c.html", ContentPolicy{}); - FakeFrontend::open("1.2.3.4", "9003", "d.html", ContentPolicy{}, WindowOptions{.title = "T"}); - FakeFrontend::open("1.2.3.4", "9004", "e.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{"secret", "origin"}); - FakeFrontend::open("1.2.3.4", "9005", "f.html", ViewOptions{.window = {.title = "O"}}); - FakeFrontend::open("1.2.3.4", "9006", "g.html", ContentPolicy{.devToolsEnabled = false}); - then("each reaches the toolkit with its settings", [&] { - check(FakeFrontend::opened == std::vector{"127.0.0.1:9000/a.html", "1.2.3.4:9001/b.html", "1.2.3.4:9002/c.html", - "1.2.3.4:9003/d.html T", "1.2.3.4:9004/e.html launched", "1.2.3.4:9005/f.html O", - "1.2.3.4:9006/g.html nodevtools"}); +const Scenario embeddedFrontendFacade{ + "The facade of the embedded frontends gives every overload of open()", + {"window-registry"}, + [] { + given("a frontend that declares its toolkit calls", [&] { + FakeFrontend::opened.clear(); + when("it is opened with every form the application uses", [&] { + FakeFrontend::open("9000", "a.html"); + FakeFrontend::open("1.2.3.4", "9001", "b.html"); + FakeFrontend::open("1.2.3.4", "9002", "c.html", ContentPolicy{}); + FakeFrontend::open("1.2.3.4", "9003", "d.html", ContentPolicy{}, WindowOptions{.title = "T"}); + FakeFrontend::open("1.2.3.4", "9004", "e.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{"secret", "origin"}); + FakeFrontend::open("1.2.3.4", "9005", "f.html", ViewOptions{.window = {.title = "O"}}); + FakeFrontend::open("1.2.3.4", "9006", "g.html", ContentPolicy{.devToolsEnabled = false}); + then("each reaches the toolkit with its settings", [&] { + check(FakeFrontend::opened + == std::vector{"127.0.0.1:9000/a.html", + "1.2.3.4:9001/b.html", + "1.2.3.4:9002/c.html", + "1.2.3.4:9003/d.html T", + "1.2.3.4:9004/e.html launched", + "1.2.3.4:9005/f.html O", + "1.2.3.4:9006/g.html nodevtools"}); + }); }); - }); - when("no window is open", [&] { - then("nothing can be closed, and a second window is refused with the frontend's name", [&] { - check(!FakeFrontend::requestClose()); - check(!FakeFrontend::closeSecondaryWindow("a.html")); - checkThrows([&] { FakeFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); }, - contains("FakeFrontend: no window of the application is open")); + when("no window is open", [&] { + then("nothing can be closed, and a second window is refused with the frontend's name", [&] { + check(!FakeFrontend::requestClose()); + check(!FakeFrontend::closeSecondaryWindow("a.html")); + checkThrows( + [&] { + FakeFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); + }, + contains("FakeFrontend: no window of the application is open")); + }); }); }); - }); - given("a frontend configured by a provider", [&] { - ConfiguredFrontend::opened.clear(); - ConfiguredFrontend::open("127.0.0.1", "9000", "a.html", ContentPolicy{}); - ConfiguredFrontend::open("127.0.0.1", "9000", "b.html", ContentPolicy{}, WindowOptions{.title = "own"}); - ConfiguredFrontend::open("127.0.0.1", "9000", "c.html", ContentPolicy{}, WindowOptions{.title = "own"}, ViewLaunch{"own-secret", ""}); - then("a call replaces only the settings it passes", [&] { - check(ConfiguredFrontend::opened == std::vector{"a.html configured configured-secret", "b.html own configured-secret", "c.html own own-secret"}); - }); - }); - given("a configured frontend with a window open", [&] { - auto& host = uiExecutorHostOf(); - host.attach([] {}); // this thread is the interface thread: the calls run on it - ConfiguredSecondaryFrontend::providerCalls = 0; - ConfiguredSecondaryFrontend::openedSecondary.clear(); - FakeFrontend::openedSecondary.clear(); - when("a secondary window is opened", [&] { - ConfiguredSecondaryFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", ContentPolicy{}, WindowOptions{.title = "second"}, ViewLaunch{"secret", ""}); - then("the provider is not asked, and the call's settings arrive", [&] { - check(ConfiguredSecondaryFrontend::providerCalls == 0); - check(ConfiguredSecondaryFrontend::openedSecondary == std::vector{"a.html second secret"}); + given("a frontend configured by a provider", [&] { + ConfiguredFrontend::opened.clear(); + ConfiguredFrontend::open("127.0.0.1", "9000", "a.html", ContentPolicy{}); + ConfiguredFrontend::open("127.0.0.1", "9000", "b.html", ContentPolicy{}, WindowOptions{.title = "own"}); + ConfiguredFrontend::open("127.0.0.1", "9000", "c.html", ContentPolicy{}, WindowOptions{.title = "own"}, ViewLaunch{"own-secret", ""}); + then("a call replaces only the settings it passes", [&] { + check(ConfiguredFrontend::opened + == std::vector{"a.html configured configured-secret", "b.html own configured-secret", "c.html own own-secret"}); }); }); - host.close(); - }); - given("a frontend with a window open and a policy of its own", [&] { - auto& host = uiExecutorHostOf(); - host.attach([] {}); - FakeFrontend::openedSecondary.clear(); - FakeFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", ContentPolicy{.devToolsEnabled = false}, WindowOptions{.title = "T"}, ViewLaunch{"s", ""}); - then("the secondary window receives the policy", [&] { - check(FakeFrontend::openedSecondary == std::vector{"a.html nodevtools T s"}); - }); - host.close(); - }); - given("a frontend whose engine is not part of the build", [&] { - then("every entry point explains what to enable", [&] { - const auto message = equals("AbsentFrontend is unavailable. Configure on Nowhere with -DNOWHERE=ON"); - checkThrows([&] { AbsentFrontend::initialize(); }, message); - checkThrows([&] { AbsentFrontend::open("9000", "a.html"); }, message); - checkThrows([&] { AbsentFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); }, message); - check(!AbsentFrontend::requestClose()); + given("a configured frontend with a window open", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); // this thread is the interface thread: the calls run on it + ConfiguredSecondaryFrontend::providerCalls = 0; + ConfiguredSecondaryFrontend::openedSecondary.clear(); + FakeFrontend::openedSecondary.clear(); + when("a secondary window is opened", [&] { + ConfiguredSecondaryFrontend::openSecondaryWindow("127.0.0.1", + "9000", + "a.html", + ContentPolicy{}, + WindowOptions{.title = "second"}, + ViewLaunch{"secret", ""}); + then("the provider is not asked, and the call's settings arrive", [&] { + check(ConfiguredSecondaryFrontend::providerCalls == 0); + check(ConfiguredSecondaryFrontend::openedSecondary == std::vector{"a.html second secret"}); + }); + }); + host.close(); }); - }); -}}; - -const Scenario windowPresentation{"A window is made opaque once, by the first frame or by the delay", {"window-registry"}, [] { - given("a presentation", [&] { - frontend::detail::Presentation presentation; - int announced = 0; - presentation.windowShown = [&] { ++announced; }; - when("the delay expires and then the page paints", [&] { - check(presentation.begin(false)); - presentation.announce(); - check(!presentation.begin(true)); - then("it was shown once, by the delay", [&] { - check(announced == 1 && presentation.shown && !presentation.byFrame); + given("a frontend with a window open and a policy of its own", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); + FakeFrontend::openedSecondary.clear(); + FakeFrontend::openSecondaryWindow("127.0.0.1", + "9000", + "a.html", + ContentPolicy{.devToolsEnabled = false}, + WindowOptions{.title = "T"}, + ViewLaunch{"s", ""}); + then("the secondary window receives the policy", [&] { + check(FakeFrontend::openedSecondary == std::vector{"a.html nodevtools T s"}); }); + host.close(); }); - when("the first frame comes first", [&] { - check(presentation.begin(true)); - check(!presentation.begin(false)); - then("the frame made it opaque", [&] { - check(presentation.byFrame); + given("a frontend whose engine is not part of the build", [&] { + then("every entry point explains what to enable", [&] { + const auto message = equals("AbsentFrontend is unavailable. Configure on Nowhere with -DNOWHERE=ON"); + checkThrows( + [&] { + AbsentFrontend::initialize(); + }, + message); + checkThrows( + [&] { + AbsentFrontend::open("9000", "a.html"); + }, + message); + checkThrows( + [&] { + AbsentFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); + }, + message); + check(!AbsentFrontend::requestClose()); }); }); - }); -}}; + }}; + +const Scenario windowPresentation{"A window is made opaque once, by the first frame or by the delay", {"window-registry"}, [] { + given("a presentation", [&] { + frontend::detail::Presentation presentation; + int announced = 0; + presentation.windowShown = [&] { + ++announced; + }; + when("the delay expires and then the page paints", [&] { + check(presentation.begin(false)); + presentation.announce(); + check(!presentation.begin(true)); + then("it was shown once, by the delay", [&] { + check(announced == 1 && presentation.shown && !presentation.byFrame); + }); + }); + when("the first frame comes first", [&] { + check(presentation.begin(true)); + check(!presentation.begin(false)); + then("the frame made it opaque", [&] { + check(presentation.byFrame); + }); + }); + }); + }}; const Scenario startupTimeoutRange{"A startup deadline a timer cannot hold is refused", {"window-registry"}, [] { - using std::chrono::milliseconds; - then("a positive deadline is kept", [&] { - check(frontend::detail::timerMilliseconds(milliseconds{30000}, "FakeFrontend") == 30000u); - }); - then("a facade refuses them before any window is opened", [&] { - FakeFrontend::opened.clear(); - ViewOptions options; - options.startupTimeout = milliseconds{-1}; - checkThrows([&] { FakeFrontend::open("127.0.0.1", "9000", "a.html", options); }, contains("FakeFrontend: startupTimeout must be positive and at most")); - check(FakeFrontend::opened.empty()); - }); - then("zero, negative and oversized deadlines are refused with the frontend's name", [&] { - for (const auto bad : {milliseconds{0}, milliseconds{-1}, milliseconds{-86400000}, milliseconds{4294967296LL}}) - checkThrows([&] { (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); }, contains("FakeFrontend: startupTimeout must be positive and at most")); - }); -}}; + using std::chrono::milliseconds; + then("a positive deadline is kept", [&] { + check(frontend::detail::timerMilliseconds(milliseconds{30000}, "FakeFrontend") == 30000u); + }); + then("a facade refuses them before any window is opened", [&] { + FakeFrontend::opened.clear(); + ViewOptions options; + options.startupTimeout = milliseconds{-1}; + checkThrows( + [&] { + FakeFrontend::open("127.0.0.1", "9000", "a.html", options); + }, + contains("FakeFrontend: startupTimeout must be positive and at most")); + check(FakeFrontend::opened.empty()); + }); + then("zero, negative and oversized deadlines are refused with the frontend's name", [&] { + for (const auto bad : {milliseconds{0}, milliseconds{-1}, milliseconds{-86400000}, milliseconds{4294967296LL}}) + checkThrows( + [&] { + (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); + }, + contains("FakeFrontend: startupTimeout must be positive and at most")); + }); + }}; diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index 3cfc89b0..395d15f2 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -22,6 +22,7 @@ #include #ifndef _WIN32 #include + #include #include #endif @@ -85,8 +86,8 @@ int main(int argc, char** argv) { std::filesystem::path project, environment, registry, directory, sessions, called; std::string integrity, manifest, grants = "check,build,preview,inspect,interact,call", callbacks = "consumer.render"; std::chrono::seconds timeout{30}, startupTimeout{90}; - unsigned short mcpPort = 0; - bool stableMcp = false; + unsigned short mcpPort = 0; + bool stableMcp = false; for (int i = 1; i + 1 < argc; i += 2) { const std::string_view name{argv[i]}; const std::string value{argv[i + 1]}; @@ -131,8 +132,11 @@ int main(int argc, char** argv) { } webfront::testdriver::sources() = {std::filesystem::canonical(environment), registry.empty() ? std::nullopt : std::optional{std::filesystem::canonical(registry)}}; - using App = webfront::BasicDeveloperApp, webfront::testdriver::DriverFS, Pages>; - App app{project, {.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested}}; + using App = webfront::BasicDeveloperApp, webfront::testdriver::DriverFS, Pages>; + App app{ + project, + {.port = "0", .remoteFileTransport = webfront::RemoteFileTransport::loopbackAttested} + }; if (!called.empty()) { // The application's own callback: what a preview in this window can reach and a separate process cannot. app.cppFunction("consumer.render", [called](std::string text) { @@ -164,14 +168,19 @@ int main(int argc, char** argv) { while (!shown.stop_requested() && !inputClosed()) std::this_thread::sleep_for(std::chrono::milliseconds{20}); if (!shown.stop_requested()) - webfront::testdriver::closeUntilShown(shown, [&] { return app.requestClose(); }, std::chrono::seconds{10}); + webfront::testdriver::closeUntilShown( + shown, + [&] { + return app.requestClose(); + }, + std::chrono::seconds{10}); }); app.show(automation->launchPage()); closer.request_stop(); closer.join(); const webfront::automation::Object state{automation->controller()->describe()}; - const auto failure = state.string("failure"); - int status = 0; + const auto failure = state.string("failure"); + int status = 0; if (failure == "Native automation deadline exceeded") status = 71; else if (!automation->controller()->wasReady() && !failure.empty()) { diff --git a/test/web/CEFContentPolicy.cpp b/test/web/CEFContentPolicy.cpp index 514c491c..2052fee5 100644 --- a/test/web/CEFContentPolicy.cpp +++ b/test/web/CEFContentPolicy.cpp @@ -64,7 +64,7 @@ struct Probe { class DevToolsClient : public CefClient, public CefLifeSpanHandler { public: DevToolsClient(Probe& state, CefRefPtr opener, CefRefPtr client) - : probe(state), parent(std::move(opener)), delegate(std::move(client)) { } + : probe(state), parent(std::move(opener)), delegate(std::move(client)) {} CefRefPtr GetLifeSpanHandler() override { return this; } @@ -94,7 +94,7 @@ class DevToolsClient : public CefClient, public CefLifeSpanHandler { class MenuDelegate : public CefMenuModelDelegate { public: - void ExecuteCommand(CefRefPtr, int, cef_event_flags_t) override { } + void ExecuteCommand(CefRefPtr, int, cef_event_flags_t) override {} private: IMPLEMENT_REFCOUNTING(MenuDelegate); @@ -108,7 +108,7 @@ class PolicyClient : public webfront::cef::SimpleCEFClient { "http://127.0.0.1:9002", {.devToolsEnabled = false, .contextMenusEnabled = false} }), - probe(state) { } + probe(state) {} void OnBeforeDevToolsPopup(CefRefPtr browser, CefWindowInfo& info, CefRefPtr& client, diff --git a/test/web/CEFFileServices.cpp b/test/web/CEFFileServices.cpp index b8082cf5..ac3c6f05 100644 --- a/test/web/CEFFileServices.cpp +++ b/test/web/CEFFileServices.cpp @@ -18,12 +18,12 @@ void require(bool value, const char* message) { } struct Scenario { - std::string mode; // download | choose | cancel | dialogs | hold (script dialogs, issue #452) - std::filesystem::path folder; - std::filesystem::path fixture; - std::string title; - std::string downloaded; - bool asked = false; + std::string mode; // download | choose | cancel | dialogs | hold (script dialogs, issue #452) + std::filesystem::path folder; + std::filesystem::path fixture; + std::string title; + std::string downloaded; + bool asked = false; std::vector dialogs; // What the injection point saw, in order. }; Scenario scenario; @@ -143,7 +143,7 @@ int main(int argc, char** argv) { webfront::BasicWFWithFrontend app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); app.show(scenario.mode == "hold" ? std::string("script-dialogs.html?hold") : scenario.mode == "dialogs" ? std::string("script-dialogs.html") - : "file-services.html?" + (scenario.mode == "download" ? std::string("download") : std::string("choose"))); + : "file-services.html?" + (scenario.mode == "download" ? std::string("download") : std::string("choose"))); if (scenario.mode == "download") { require(!scenario.downloaded.empty(), "The download did not finish"); // The engine neutralizes the page's "../webfront-download.txt" itself (Chrome writes "_webfront-download.txt"). diff --git a/test/web/DeveloperTest.cpp b/test/web/DeveloperTest.cpp index 7f24fa7e..fbf20058 100644 --- a/test/web/DeveloperTest.cpp +++ b/test/web/DeveloperTest.cpp @@ -230,8 +230,8 @@ Mode parseMode(std::string_view argument) { mode.part = "app"; } else if (argument.starts_with("--part=")) { mode.part = std::string(argument.substr(7)); - if (mode.part != "app" && mode.part != "scripts" && mode.part != "typescript" && mode.part != "jasmine" && mode.part != "terminal" && - mode.part != "workspace") + if (mode.part != "app" && mode.part != "scripts" && mode.part != "typescript" && mode.part != "jasmine" && mode.part != "terminal" + && mode.part != "workspace") throw std::invalid_argument("Unknown part of the developer test: " + mode.part); } else { throw std::invalid_argument("Unknown smoke-test mode"); diff --git a/test/web/FrontendLifecycle.cpp b/test/web/FrontendLifecycle.cpp index 1ae8fd56..76857162 100644 --- a/test/web/FrontendLifecycle.cpp +++ b/test/web/FrontendLifecycle.cpp @@ -6,18 +6,18 @@ #include #include #include +#include #include -#include -#include -#include #include +#include #include -#include +#include #include #include #include #include #include +#include #include #ifndef WEBFRONT_TEST_FRONTEND @@ -32,32 +32,43 @@ static_assert(Frontend::action == webfront::frontend::Action::closeServerAfterOp // Values reported by the lifecycle pages; keep their named constants in sync with this enum. enum class LifecycleStage : std::int32_t { - uninstrumented = 0, - bridgeConnected = 1, - associationOrigins = 2, + uninstrumented = 0, + bridgeConnected = 1, + associationOrigins = 2, associationSecondSocket = 3, associationRegistration = 4, - policyPopup = 5, - policyNavigation = 6, - policyDestination = 7, - pageCompleted = 8, - windowClosed = 9, - startingInstrumented = 10, + policyPopup = 5, + policyNavigation = 6, + policyDestination = 7, + pageCompleted = 8, + windowClosed = 9, + startingInstrumented = 10, }; std::atomic lifecycleStage = LifecycleStage::uninstrumented; -constexpr const char* stageName(LifecycleStage stage) { +constexpr const char* stageName(LifecycleStage stage) { switch (stage) { - case LifecycleStage::uninstrumented: return "uninstrumented mode or frontend initialization"; - case LifecycleStage::bridgeConnected: return "bridge connected"; - case LifecycleStage::associationOrigins: return "association: checking origins"; - case LifecycleStage::associationSecondSocket: return "association: waiting for second WebSocket"; - case LifecycleStage::associationRegistration: return "association: waiting for second connection registration"; - case LifecycleStage::policyPopup: return "policy: bridge ready, opening popup"; - case LifecycleStage::policyNavigation: return "policy: waiting for navigation or cancellation"; - case LifecycleStage::policyDestination: return "policy: destination bridge ready"; - case LifecycleStage::pageCompleted: return "page reported completion, waiting for window close"; - case LifecycleStage::windowClosed: return "window closed, checking results or shutting down"; - case LifecycleStage::startingInstrumented: return "starting frontend or waiting for first bridge connection"; + case LifecycleStage::uninstrumented: + return "uninstrumented mode or frontend initialization"; + case LifecycleStage::bridgeConnected: + return "bridge connected"; + case LifecycleStage::associationOrigins: + return "association: checking origins"; + case LifecycleStage::associationSecondSocket: + return "association: waiting for second WebSocket"; + case LifecycleStage::associationRegistration: + return "association: waiting for second connection registration"; + case LifecycleStage::policyPopup: + return "policy: bridge ready, opening popup"; + case LifecycleStage::policyNavigation: + return "policy: waiting for navigation or cancellation"; + case LifecycleStage::policyDestination: + return "policy: destination bridge ready"; + case LifecycleStage::pageCompleted: + return "page reported completion, waiting for window close"; + case LifecycleStage::windowClosed: + return "window closed, checking results or shutting down"; + case LifecycleStage::startingInstrumented: + return "starting frontend or waiting for first bridge connection"; } return "unknown stage"; } @@ -65,18 +76,22 @@ constexpr const char* stageName(LifecycleStage stage) { // A stuck UI loop or a page which never settles must fail before CTest's outer timeout. The watchdog // terminates the process because the owning thread cannot safely be unwound; EXIT_FAILURE makes CTest fail. class LifecycleWatchdog { - std::mutex mutex; + std::mutex mutex; std::condition_variable changed; - bool finished = false; - std::thread worker; + bool finished = false; + std::thread worker; + public: - explicit LifecycleWatchdog(std::chrono::seconds timeout) : worker([this, timeout] { - std::unique_lock lock{mutex}; - if (!changed.wait_for(lock, timeout, [this] { return finished; })) { - std::cerr << "Lifecycle timeout at stage: " << stageName(lifecycleStage.load()) << std::endl; - std::_Exit(EXIT_FAILURE); - } - }) { } + explicit LifecycleWatchdog(std::chrono::seconds timeout) + : worker([this, timeout] { + std::unique_lock lock{mutex}; + if (!changed.wait_for(lock, timeout, [this] { + return finished; + })) { + std::cerr << "Lifecycle timeout at stage: " << stageName(lifecycleStage.load()) << std::endl; + std::_Exit(EXIT_FAILURE); + } + }) {} ~LifecycleWatchdog() { { std::lock_guard lock{mutex}; @@ -90,8 +105,7 @@ class LifecycleWatchdog { template void registerLifecycleStage(Application& app) { app.cppFunction("lifecycleStage", [](std::int32_t stage) { - if (stage >= static_cast(LifecycleStage::associationOrigins) - && stage <= static_cast(LifecycleStage::pageCompleted)) + if (stage >= static_cast(LifecycleStage::associationOrigins) && stage <= static_cast(LifecycleStage::pageCompleted)) lifecycleStage = static_cast(stage); }); } @@ -111,12 +125,12 @@ int show(std::string_view page) { // The page of the view is associated with the view of the frontend; a second connection from the same page, without the // secret, is not (ADR-020, rule 3). int checkViewAssociation() { - App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - std::mutex mutex; - std::vector embedded; - std::vector local; - std::atomic originsChecked = false; - lifecycleStage = LifecycleStage::startingInstrumented; + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + std::mutex mutex; + std::vector embedded; + std::vector local; + std::atomic originsChecked = false; + lifecycleStage = LifecycleStage::startingInstrumented; registerLifecycleStage(app); app.onUIStarted([&](App::UI ui) { std::scoped_lock lock{mutex}; @@ -132,7 +146,9 @@ int checkViewAssociation() { app.cppFunction("associationScript", [](std::string address) { return webfront::detail::viewSecretScript(std::string(64, 'a'), webfront::detail::browserOrigin(address, "9002")); }); - app.cppFunction("originsChecked", [&] { originsChecked = true; }); + app.cppFunction("originsChecked", [&] { + originsChecked = true; + }); app.show("view-association.html"); lifecycleStage = LifecycleStage::windowClosed; if (!originsChecked) @@ -189,12 +205,11 @@ struct OutcomeReceiver { }; struct ScheduledOperation { - std::promise> result; + std::promise> result; decltype(webfront::networking::ex::connect(std::declval().schedule())>(), - std::declval())) - operation; + std::declval())) operation; explicit ScheduledOperation(const webfront::frontend::UIExecutor& executor) - : operation(webfront::networking::ex::connect(executor.schedule(), OutcomeReceiver{&result, executor})) { } + : operation(webfront::networking::ex::connect(executor.schedule(), OutcomeReceiver{&result, executor})) {} std::future> start() { auto future = result.get_future(); webfront::networking::ex::start(operation); @@ -205,12 +220,12 @@ struct ScheduledOperation { // The window's interface thread runs the operations, and closing the window completes the pending ones stopped: every // operation completes exactly once, none runs on another thread or after closure, and the executor is unavailable afterwards. int checkUIExecutor() { - App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - const auto executor = app.uiExecutor(); - const auto mainThread = std::this_thread::get_id(); + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + const auto executor = app.uiExecutor(); + const auto mainThread = std::this_thread::get_id(); if (executor.available()) throw std::runtime_error("The executor is available before the window opens"); - std::atomic ran = 0; + std::atomic ran = 0; std::atomic error = false; std::string message; std::jthread client([&] { @@ -221,7 +236,7 @@ int checkUIExecutor() { throw std::runtime_error("The executor never became available"); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - std::list operations; + std::list operations; std::vector>> results; while (executor.available() && results.size() < 5000) { operations.emplace_back(executor); @@ -339,11 +354,11 @@ struct SecondOpenOutcome { struct SecondOpener { using receiver_concept = webfront::networking::ex::receiver_tag; - std::promise* result; - webfront::frontend::NativeWindow window; - webfront::frontend::UIExecutor executor; - void* firstWindow; - auto get_env() const noexcept { + std::promise* result; + webfront::frontend::NativeWindow window; + webfront::frontend::UIExecutor executor; + void* firstWindow; + auto get_env() const noexcept { return webfront::networking::ex::prop{webfront::networking::ex::get_stop_token, webfront::networking::ex::never_stop_token{}}; } void set_value() && noexcept { @@ -372,10 +387,10 @@ struct SecondOpener { // A second open() on the interface thread, while the first runs, is refused before it creates a view: the window published for // the first application, and its executor, stay the ones its connections and dialogs rely on. int checkSecondOpen() { - App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - const auto window = app.nativeWindow(); - const auto executor = app.uiExecutor(); - std::atomic error = false; + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + const auto window = app.nativeWindow(); + const auto executor = app.uiExecutor(); + std::atomic error = false; std::string message; std::jthread client([&] { try { @@ -503,7 +518,7 @@ struct PolicyLifecycleFrontend { } else #endif #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) - if constexpr (std::same_as) { + if constexpr (std::same_as) { using namespace webfront::frontend::detail::wkwebview; initialize(); Object pool(send(type("NSAutoreleasePool"), "new")); @@ -530,7 +545,7 @@ int checkContentPolicy(bool allowNavigation) { if (allowNavigation) policy.navigationAllowedOrigins = {"http://localhost:9002"}; using PolicyApp = webfront::BasicWFWithFrontend; - PolicyApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path(), .contentPolicy = policy}); + PolicyApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path(), .contentPolicy = policy}); lifecycleStage = LifecycleStage::startingInstrumented; registerLifecycleStage(app); app.onUIStarted([](PolicyApp::UI) { @@ -542,15 +557,15 @@ int checkContentPolicy(bool allowNavigation) { std::atomic navigated = false; app.cppFunction("policyCompleted", [&] { lifecycleStage = LifecycleStage::pageCompleted; - completed = true; + completed = true; }); app.cppFunction("policyEscaped", [&] { lifecycleStage = LifecycleStage::pageCompleted; - escaped = true; + escaped = true; }); app.cppFunction("policyNavigated", [&] { lifecycleStage = LifecycleStage::pageCompleted; - navigated = true; + navigated = true; }); app.show("content-policy.html"); lifecycleStage = LifecycleStage::windowClosed; @@ -566,8 +581,8 @@ int checkContentPolicy(bool allowNavigation) { // A host thread that keeps working while show() runs: it talks to the page, then ends the session (#567). template class HostSession { - std::mutex mutex; - std::condition_variable changed; + std::mutex mutex; + std::condition_variable changed; std::optional page; bool abandoned = false; @@ -593,7 +608,9 @@ class HostSession { /// On the host's thread: waits for the page, then exchanges with it. The watchdog bounds the wait. std::string exchange() { std::unique_lock lock{mutex}; - changed.wait(lock, [this] { return page.has_value() || abandoned; }); + changed.wait(lock, [this] { + return page.has_value() || abandoned; + }); if (!page) return {}; auto ui = *page; @@ -650,19 +667,24 @@ constexpr const char* secondPage = "second-window.html?name=editor"; constexpr const char* earlyPage = "second-window.html?name=early"; class SecondWindows { - std::mutex mutex; - std::condition_variable changed; - std::map windows; - std::map embedded; - std::map seen; - std::int64_t counter = 0; - unsigned connections = 0; - bool abandoned = false; + std::mutex mutex; + std::condition_variable changed; + std::map windows; + std::map embedded; + std::map seen; + std::int64_t counter = 0; + unsigned connections = 0; + bool abandoned = false; template bool waitFor(Predicate predicate) { std::unique_lock lock{mutex}; - return changed.wait_for(lock, std::chrono::seconds(20), [&] { return predicate() || abandoned; }) && !abandoned && predicate(); + return changed.wait_for(lock, + std::chrono::seconds(20), + [&] { + return predicate() || abandoned; + }) + && !abandoned && predicate(); } public: @@ -712,7 +734,9 @@ class SecondWindows { }); } bool ready(const std::string& name) { - return waitFor([&] { return windows.contains(name); }); + return waitFor([&] { + return windows.contains(name); + }); } bool isEmbedded(const std::string& name) { std::lock_guard lock{mutex}; @@ -731,7 +755,9 @@ class SecondWindows { windows.erase(name); } bool saw(const std::string& name, std::int64_t value) { - return waitFor([&] { return seen.contains(name) && seen[name] == value; }); + return waitFor([&] { + return seen.contains(name) && seen[name] == value; + }); } }; @@ -755,14 +781,14 @@ class OnInterfaceThread { self->done.set_value(Outcome::unavailable); } }; - Function function; - std::promise done; + Function function; + std::promise done; decltype(webfront::networking::ex::connect(std::declval().schedule())>(), - std::declval())) operation; + std::declval())) operation; public: OnInterfaceThread(const webfront::frontend::UIExecutor& executor, Function work) - : function(std::move(work)), operation(webfront::networking::ex::connect(executor.schedule(), Receiver{this})) { } + : function(std::move(work)), operation(webfront::networking::ex::connect(executor.schedule(), Receiver{this})) {} std::future outcome() { return done.get_future(); } @@ -773,7 +799,7 @@ class OnInterfaceThread { int checkSecondWindow() { App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - lifecycleStage = LifecycleStage::startingInstrumented; + lifecycleStage = LifecycleStage::startingInstrumented; bool refusedBeforeShow = false; try { app.openSecondaryWindow(secondPage); @@ -819,7 +845,8 @@ int checkSecondWindow() { windows.forget("early"); windows.window("main").jsFunction("windowTests.setStorage")(std::string("from-main")); // The round trip orders the fire-and-forget write before creating the second view. - check(windows.window("main").template jsFunction("windowTests.getStorage")().get() == "from-main", "The first window could not write storage"); + check(windows.window("main").template jsFunction("windowTests.getStorage")().get() == "from-main", + "The first window could not write storage"); webfront::WindowOptions options; options.title = "Second window"; options.width = 640; @@ -827,7 +854,8 @@ int checkSecondWindow() { app.openSecondaryWindow(secondPage, options); check(windows.ready("editor"), "The second window did not connect"); check(windows.isEmbedded("main") && windows.isEmbedded("editor"), "A window of the application lacks the proof of an embedded view"); - check(windows.window("editor").template jsFunction("windowTests.getStorage")().get() == "from-main", "The second window does not share storage"); + check(windows.window("editor").template jsFunction("windowTests.getStorage")().get() == "from-main", + "The second window does not share storage"); // The same page again brings the window to the front: no third connection. app.openSecondaryWindow(secondPage, options); check(windows.window("editor").template jsFunction("windowTests.name")().get() == "editor", "The second window did not answer"); @@ -840,7 +868,8 @@ int checkSecondWindow() { for (int attempt = 0; attempt < 200 && app.requestClose(secondPage); ++attempt) std::this_thread::sleep_for(std::chrono::milliseconds(25)); check(!app.requestClose(secondPage), "The second window did not close"); - check(windows.window("main").template jsFunction("windowTests.name")().get() == "main", "The first window is not usable after the second closed"); + check(windows.window("main").template jsFunction("windowTests.name")().get() == "main", + "The first window is not usable after the second closed"); // Opened again, it shares the state again. windows.forget("editor"); app.openSecondaryWindow(secondPage, options); @@ -868,8 +897,8 @@ int checkSecondWindow() { closeAccepted = app.requestClose(); lateOpen.start(); }); - auto lateOutcome = lateOpen.outcome(); - auto closeOutcome = closeThenOpen.outcome(); + auto lateOutcome = lateOpen.outcome(); + auto closeOutcome = closeThenOpen.outcome(); closeThenOpen.start(); check(closeOutcome.wait_for(std::chrono::seconds(20)) == std::future_status::ready && closeOutcome.get() == Outcome::ran, "The operation that closes the first window did not run"); @@ -943,8 +972,13 @@ int checkHostThread() { throw std::runtime_error("Opening off the main thread was not refused with a diagnostic: '" + diagnostic + "'"); return 0; } else { - HostSession session; - webfront::UIThread ui(config, [&](Application& app) { session.setup(app); }, "host-close.html"); + HostSession session; + webfront::UIThread ui( + config, + [&](Application& app) { + session.setup(app); + }, + "host-close.html"); const auto answer = session.exchange(); // this thread stays the host's if (!ui.running()) throw std::runtime_error("The session ended before the host stopped it"); @@ -960,7 +994,8 @@ int checkHostThread() { const auto programStart = std::chrono::steady_clock::now(); // How long the window takes to reach a working bridge: the page asks the host, which prints the time since the start of the -// program, including the frontend's initialization (#611). The CTest case StartupTime-* runs it with fresh profile directories (cold) or after a first run (warm). +// program, including the frontend's initialization (#611). The CTest case StartupTime-* runs it with fresh profile directories (cold) or after a first run +// (warm). int checkStartupTime() { const auto begin = programStart; App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); @@ -971,7 +1006,7 @@ int checkStartupTime() { long long readyMilliseconds = -1; std::thread host([&] { try { - answer = session.exchange(); + answer = session.exchange(); readyMilliseconds = std::chrono::duration_cast(std::chrono::steady_clock::now() - begin).count(); // The answer can come before the first frame: the window is shown at the first frame or, at the latest, one second // after the load, so the close waits for that milestone to be traced (RunStartupTime.cmake requires it). @@ -1040,7 +1075,11 @@ int run(std::string_view mode) { cases.emplace("host-close", checkHostClose); cases.emplace("second-window", checkSecondWindow); cases.emplace("startup-time", checkStartupTime); - cases.emplace("host-thread", +[] { return checkHostThread(); }); + cases.emplace( + "host-thread", + +[] { + return checkHostThread(); + }); cases.emplace("view-association", checkViewAssociation); cases.emplace("stage-report", checkStageReport); const auto selected = cases.find(mode); diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index e5339667..e4521a74 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -3,20 +3,20 @@ // webtest --project --registry-dir -- test --timeout 120 // The status is that of `wf test`, and 1 when the specs passed but C++ did not observe every call they make. #include +#include #include #include -#include #include #ifdef WEBFRONT_TEST_TLS_FIXTURE -#include + #include #endif -#include "../driver/WfDriver.hpp" #include "../../examples/host-loop/HostLoopUI.hpp" #include "../../examples/life/react/LifeReact.hpp" -#include "RejectedWebSocketServer.hpp" +#include "../driver/WfDriver.hpp" #include "../unit/FormsSettings.hpp" +#include "RejectedWebSocketServer.hpp" #include #include @@ -81,7 +81,7 @@ struct TestState { // The pages the specs fetch or embed (origin probes, a path containing a plus), served from the project directory. class TestPages { public: - explicit TestPages(const filesystem::path& project) : root(project / "pages") { } + explicit TestPages(const filesystem::path& project) : root(project / "pages") {} optional open(filesystem::path file) const { if (file.relative_path() == "embedded-fallback.html") @@ -114,22 +114,23 @@ using TestWF = DeveloperAppWithNetwork(fixture / "cert.pem", fixture / "key.pem"); + config.tlsCredentials = make_shared(fixture / "cert.pem", fixture / "key.pem"); config.remoteFileTransport = RemoteFileTransport::httpsByDeployment; #endif } @@ -144,13 +145,16 @@ class BrowserIntegrationTest { }); rejectedWebSocket.emplace(); registerCallbacks(); - registerPtyPage(app, { + registerPtyPage(app, + { #ifdef _WIN32 - .argv = {"cmd.exe", "/d", "/q"}, + .argv = {"cmd.exe", "/d", "/q"}, #else - .argv = {"sh", "-i"}, + .argv = {"sh", "-i"}, #endif - .directory = {}, .environment = {{"WF_PTY_MARKER", "WEBFRONT_PTY_OK"}}, .size = {} + .directory = {}, + .environment = {{"WF_PTY_MARKER", "WEBFRONT_PTY_OK"}}, + .size = {} }); registerBitsetCallbacks(); registerListCallbacks(); @@ -158,8 +162,9 @@ class BrowserIntegrationTest { registerHostLoop(app); registerMediaRoute(app); registerReadRoute(app); - streamRoute = app.addRoute("/webfront/services/test-stream/", [](const http::RouteRequest& request) { - if (request.query.find("fail=1") != std::string_view::npos) throw std::runtime_error("route failure requested by the spec"); + streamRoute = app.addRoute("/webfront/services/test-stream/", [](const http::RouteRequest& request) { + if (request.query.find("fail=1") != std::string_view::npos) + throw std::runtime_error("route failure requested by the spec"); std::uint64_t size = 0; if (const auto at = request.query.find("size="); at != std::string_view::npos) size = std::stoull(std::string(request.query.substr(at + 5))); @@ -169,7 +174,8 @@ class BrowserIntegrationTest { reply.contentLength = size; reply.body = [size, produced = std::uint64_t{0}](std::span out) mutable { const auto count = static_cast(std::min(out.size(), size - produced)); - for (std::size_t index = 0; index < count; ++index) out[index] = static_cast((((produced + index) * 7) + 3) % 251); + for (std::size_t index = 0; index < count; ++index) + out[index] = static_cast((((produced + index) * 7) + 3) % 251); produced += count; return count; }; @@ -195,61 +201,68 @@ class BrowserIntegrationTest { try { store.set({0, "after shutdown"}); return 1; - } catch (const std::runtime_error&) { } + } catch (const std::runtime_error&) {} } try { shutdownDocument->text("after shutdown"); return 1; - } catch (const std::runtime_error&) { } + } catch (const std::runtime_error&) {} return result(); } private: - TestWF* webFront{}; + TestWF* webFront{}; optional rejectedWebSocket; - optional cancelledTask; - TestState state; + optional cancelledTask; + TestState state; // Accessed only by callbacks on the server context. finish() runs after WfDriver joins app.shutdown(). std::map domRejections; - std::array domEventCounts{}; + std::array domEventCounts{}; std::map documentTexts, documentInputs; std::map documentReads; // The forms of #383 built for each browser, with the object their events write. struct FormsFixture { - std::shared_ptr object; - forms::Form form; - forms::Inspector inspector; + std::shared_ptr object; + forms::Form form; + forms::Inspector inspector; }; - std::map formsFixtures; - std::map documentCancelled; - std::map documentAwaits; - std::map awaitCancelled; - optional> shutdownDocument; - dom::Node shutdownNode; - optional connectedUI; - UISubscription uiSubscription; - UISubscription lifeReactSubscription; - http::RouteTable::Registration streamRoute, mediaRoute; - ReadRoute readRoute; - filesystem::path mediaFile; - mutex mediaMutex; - vector mediaRanges; + std::map formsFixtures; + std::map documentCancelled; + std::map documentAwaits; + std::map awaitCancelled; + optional> shutdownDocument; + dom::Node shutdownNode; + optional connectedUI; + UISubscription uiSubscription; + UISubscription lifeReactSubscription; + http::RouteTable::Registration streamRoute, mediaRoute; + ReadRoute readRoute; + filesystem::path mediaFile; + mutex mediaMutex; + vector mediaRanges; std::map>> reactStores; - UISubscription closedDomSubscription; - std::map closedDocumentRejected; - future cppResult; - jthread bitsetFutureThread; - static constexpr chrono::seconds cppResultWaitTimeout{10}; + UISubscription closedDomSubscription; + std::map closedDocumentRejected; + future cppResult; + jthread bitsetFutureThread; + static constexpr chrono::seconds cppResultWaitTimeout{10}; // The host of examples/host-loop, with its loop on a thread of this program as the example runs it beside a native // window. The page of the example is added on request of its specs, which also stop the loop from its button. - boing::Host hostLoop{{boing::Engine::cpu, false, false, 0}, 2}; - jthread hostLoopThread; + boing::Host hostLoop{ + {boing::Engine::cpu, false, false, 0}, + 2 + }; + jthread hostLoopThread; void registerHostLoop(TestWF& app) { boing::install(app, hostLoop); - app.cppFunction("hostLoopTest.mount", [](TestWF::UI ui) { ui.addScript(boing::page); }); - app.cppFunction("hostLoopTest.ended", [this] { return state.hostLoopEnded.load(); }); + app.cppFunction("hostLoopTest.mount", [](TestWF::UI ui) { + ui.addScript(boing::page); + }); + app.cppFunction("hostLoopTest.ended", [this] { + return state.hostLoopEnded.load(); + }); hostLoopThread = jthread([this] { hostLoop.run(); state.hostLoopEnded = true; @@ -414,8 +427,12 @@ class BrowserIntegrationTest { webFront->cppFunction("deepEcho", [](const vector::type>& value) { return value; }); - webFront->cppFunction("deferredEcho", [this](string value, int delayMs) { return deferredEcho(webFront, std::move(value), delayMs); }); - webFront->cppFunction("deferredFailure", [this]() { return deferredFailure(webFront, "rejected after a delay"); }); + webFront->cppFunction("deferredEcho", [this](string value, int delayMs) { + return deferredEcho(webFront, std::move(value), delayMs); + }); + webFront->cppFunction("deferredFailure", [this]() { + return deferredFailure(webFront, "rejected after a delay"); + }); webFront->cppFunction("listEcho", [](const vector& value) { return value; @@ -431,7 +448,10 @@ class BrowserIntegrationTest { return entries; }); webFront->cppFunction("pageFromCpp", []() { - return tuple, string>{{"a", "b"}, "cursor"}; + return tuple, string>{ + {"a", "b"}, + "cursor" + }; }); webFront->cppFunction("heterogeneousList", [](const vector&) {}); } @@ -454,7 +474,9 @@ class BrowserIntegrationTest { Task checkErrorCodes(TestWF::UI ui) { bool passed = false; try { - const auto codeIs = [](const string& rejection, string_view code) { return rejection.starts_with(string(code) + "|"); }; + const auto codeIs = [](const string& rejection, string_view code) { + return rejection.starts_with(string(code) + "|"); + }; const auto application = co_await rejectionOf(ui, "webfrontTests.rejectWithCode", "quota:exceeded"); const auto reserved = co_await rejectionOf(ui, "webfrontTests.rejectWithCode", "webfront.cancelled"); const auto missing = co_await rejectionOf(ui, "webfrontTests.noSuchFunction"); @@ -474,11 +496,14 @@ class BrowserIntegrationTest { bool passed = false; try { const vector names{"alpha", "", string(70000, 'z'), "\xe2\x82\xac"}; - const auto echoed = co_await ui.jsFunctionSender>("webfrontTests.listEcho")(names); - const vector records{{"a.txt", 12.5, true, {1, 2, 3}}, {"b", 0, false, {}}}; - const auto echoedRecords = co_await ui.jsFunctionSender>("webfrontTests.recordsEcho")(records); - const auto none = co_await ui.jsFunctionSender>("webfrontTests.listEcho")(vector{}); - bool heterogeneousRejected = false; + const auto echoed = co_await ui.jsFunctionSender>("webfrontTests.listEcho")(names); + const vector records{ + {"a.txt", 12.5, true, {1, 2, 3}}, + { "b", 0, false, {}} + }; + const auto echoedRecords = co_await ui.jsFunctionSender>("webfrontTests.recordsEcho")(records); + const auto none = co_await ui.jsFunctionSender>("webfrontTests.listEcho")(vector{}); + bool heterogeneousRejected = false; try { co_await ui.jsFunctionSender>("webfrontTests.heterogeneousList")(); } catch (const runtime_error&) { @@ -573,8 +598,9 @@ class BrowserIntegrationTest { }); webFront->cppFunction("mediaRanges", [this]() { lock_guard lock(mediaMutex); - string joined; - for (const auto& range : mediaRanges) joined += range + "\n"; + string joined; + for (const auto& range : mediaRanges) + joined += range + "\n"; return joined; }); } @@ -582,18 +608,35 @@ class BrowserIntegrationTest { /// Read grants bound to the browser client (#469): hostile active content is served by a bound route. void registerReadRoute(TestWF& app) { readRoute = app.addReadRoute("/webfront/services/test-read/", [](const http::RouteRequest&, const ReadGrant& grant) { - const string_view marker = "try { window.top.__readExecuted = true; parent.__readExecuted = true; } catch (e) {} fetch('/webfront/services/test-read/executed').catch(() => {});"; - string type, body; - if (grant.rest == "hello.txt") { type = "text/plain"; body = "hello"; } - else if (grant.rest == "evil.html") { type = "text/html"; body = ""; } - else if (grant.rest == "evil.svg") { type = "image/svg+xml"; body = ""; } - else if (grant.rest == "legacy.js") { type = "text/javascript1.5"; body = string(marker); } - else if (grant.rest == "legacy-ecma.js") { type = "application/x-ecmascript"; body = string(marker); } - else { http::RouteReply reply; reply.status = http::Response::notFound; reply.contentLength = 0; return reply; } + const string_view marker = "try { window.top.__readExecuted = true; parent.__readExecuted = true; } catch (e) {} " + "fetch('/webfront/services/test-read/executed').catch(() => {});"; + string type, body; + if (grant.rest == "hello.txt") { + type = "text/plain"; + body = "hello"; + } else if (grant.rest == "evil.html") { + type = "text/html"; + body = ""; + } else if (grant.rest == "evil.svg") { + type = "image/svg+xml"; + body = ""; + } else if (grant.rest == "legacy.js") { + type = "text/javascript1.5"; + body = string(marker); + } else if (grant.rest == "legacy-ecma.js") { + type = "application/x-ecmascript"; + body = string(marker); + } else { + http::RouteReply reply; + reply.status = http::Response::notFound; + reply.contentLength = 0; + return reply; + } http::RouteReply reply; reply.headers.emplace_back("Content-Type", type); reply.contentLength = body.size(); - reply.body = [body = std::move(body), position = size_t{0}](span out) mutable { + reply.body = [body = std::move(body), position = size_t{0}](span out) mutable { const auto count = min(out.size(), body.size() - position); copy_n(body.data() + position, count, out.data()); position += count; @@ -601,7 +644,9 @@ class BrowserIntegrationTest { }; return reply; }); - webFront->cppFunction("readUrl", [this](TestWF::UI ui, string name) { return ui.grantRead(readRoute, name); }); + webFront->cppFunction("readUrl", [this](TestWF::UI ui, string name) { + return ui.grantRead(readRoute, name); + }); } void registerCallbacks() { @@ -686,7 +731,7 @@ class BrowserIntegrationTest { }); // C++ changes the object, then refreshes the form and the inspector. webFront->cppFunction("formsChange", [this](TestWF::UI ui) { - auto& fixture = formsFixtures.at(ui.id()); + auto& fixture = formsFixtures.at(ui.id()); fixture.object->speed = 9; fixture.object->density = 0.5; fixture.object->wrap = true; @@ -726,12 +771,13 @@ class BrowserIntegrationTest { static_cast(ui.document()); const auto [id, operations] = msg::DomBatch::decode(std::as_bytes(std::span(bytes))); msg::DomBatch batch(id); - for (const auto& operation : operations) batch.add(operation); + for (const auto& operation : operations) + batch.add(operation); ui.sendDomBatch(batch); state.domBatchSent = true; }); webFront->cppFunction("wfDom.rejected", [this](uint32_t id, const string& reason) { - domRejections[id] = reason; + domRejections[id] = reason; state.domRejectionObserved = true; }); webFront->cppFunction("domBatchRejection", [this](uint32_t id) { @@ -742,15 +788,20 @@ class BrowserIntegrationTest { webFront->cppFunction("wfDom.event", [this](uint32_t node, uint32_t event, const string& value) { using Event = tuple; static constexpr array expected{ - Event{10, 4, "hello"}, Event{11, 5, "true"}, Event{11, 5, "false"}, - Event{10, 6, "Escape"}, Event{10, 7, ""}}; + Event{10, 4, "hello"}, + Event{11, 5, "true"}, + Event{11, 5, "false"}, + Event{10, 6, "Escape"}, + Event{10, 7, ""} + }; size_t index = 0; while (index < expected.size() && expected[index] != Event{node, event, value}) ++index; - ++domEventCounts.at(index); // Last slot counts all unexpected identities or values. + ++domEventCounts.at(index); // Last slot counts all unexpected identities or values. }); webFront->cppFunction("domEventCounts", [this] { - if (domEventCounts == array{1, 1, 1, 1, 1, 0}) state.domEventsObserved = true; + if (domEventCounts == array{1, 1, 1, 1, 1, 0}) + state.domEventsObserved = true; return domEventCounts; }); @@ -765,7 +816,9 @@ class BrowserIntegrationTest { const auto origin = webfront::detail::applicationOrigin("127.0.0.1", webFront->port(), networking::secureTransport); return frontend::detail::applicationUrl("127.0.0.1", webFront->port(), "a+b.html", origin); }); - webFront->cppFunction("rejectedWebSocketUrl", [this] { return rejectedWebSocket->url(); }); + webFront->cppFunction("rejectedWebSocketUrl", [this] { + return rejectedWebSocket->url(); + }); uiSubscription = webFront->subscribeUIStarted([this](TestWF::UI) { state.subscriberNotified = true; }); @@ -795,20 +848,39 @@ class BrowserIntegrationTest { webFront->cppFunction("specsFinished", [this] { specsFinished(); }); - webFront->cppFunction("returnFromCpp", [](const string& value) { return "cpp-result:" + value; }); - webFront->cppFunction("throwFromCpp", [] { throw runtime_error("C++ callback failed"); }); - webFront->cppFunction("throwCodedFromCpp", [] { throw BridgeError("denied", "the user said no"); }); - webFront->cppFunction("longStringFromCpp", [](size_t size) { return string(size, 'x'); }); - webFront->cppFunction("echoString", [](const string& value) { return value; }); + webFront->cppFunction("returnFromCpp", [](const string& value) { + return "cpp-result:" + value; + }); + webFront->cppFunction("throwFromCpp", [] { + throw runtime_error("C++ callback failed"); + }); + webFront->cppFunction("throwCodedFromCpp", [] { + throw BridgeError("denied", "the user said no"); + }); + webFront->cppFunction("longStringFromCpp", [](size_t size) { + return string(size, 'x'); + }); + webFront->cppFunction("echoString", [](const string& value) { + return value; + }); webFront->cppFunction("integerInCpp", [](int value) { return value; }); - webFront->cppFunction("lengthInCpp", [](const string& value) { return value.size(); }); + webFront->cppFunction("lengthInCpp", [](const string& value) { + return value.size(); + }); // Ten typed arrays as ten top-level parameters, the signature deduced from the lambda. webFront->cppFunction("recordArraysFromJs", - [this](const vector& u8, const vector& i8, const vector& u16, const vector& i16, - const vector& u32, const vector& i32, const vector& u64, const vector& i64, - const vector& floats, const vector& doubles) { + [this](const vector& u8, + const vector& i8, + const vector& u16, + const vector& i16, + const vector& u32, + const vector& i32, + const vector& u64, + const vector& i64, + const vector& floats, + const vector& doubles) { recordArraysFromJs(u8, i8, u16, i16, u32, i32, u64, i64, floats, doubles); }); webFront->cppFunction("recordTupleFromJs", [this](const tuple& value) { @@ -835,8 +907,7 @@ class BrowserIntegrationTest { /// Arity follows the bridge signature under test: ten typed arrays as ten top-level parameters. template void recordArraysFromJs(const Arrays&... arrays) { - state.jsArraysObserved = - matchesAll(tie(arrays...), tie(cppU8, cppI8, cppU16, cppI16, cppU32, cppI32, cppU64, cppI64, cppFloat, cppDouble)); + state.jsArraysObserved = matchesAll(tie(arrays...), tie(cppU8, cppI8, cppU16, cppI16, cppU32, cppI32, cppU64, cppI64, cppFloat, cppDouble)); } void browserReady() { @@ -848,13 +919,13 @@ class BrowserIntegrationTest { webFront->spawn(checkErrorCodes(requireUI())); cancelledTask = requireUI().spawn(awaitCancelledSender(requireUI())); requireUI().jsFunction("webfrontTests.receiveFromCpp")(cppToJsToken); - requireUI().jsFunction("webfrontTests.receiveArraysFromCpp")( - cppU8, cppI8, cppU16, cppI16, cppU32, cppI32, cppU64, cppI64, cppFloat, cppDouble); + requireUI().jsFunction("webfrontTests.receiveArraysFromCpp")(cppU8, cppI8, cppU16, cppI16, cppU32, cppI32, cppU64, cppI64, cppFloat, cppDouble); cppResult = requireUI().template jsFunction("webfrontTests.returnToCpp")("from-cpp"); } bool cppResultMatches() { - if (!cppResult.valid()) return false; + if (!cppResult.valid()) + return false; try { if (cppResult.wait_for(cppResultWaitTimeout) != future_status::ready) { log::error("C++ result call timed out after {} seconds", cppResultWaitTimeout.count()); @@ -896,8 +967,9 @@ class BrowserIntegrationTest { log::error("The specs did not report the end of the run"); return 1; } - if (!(state.domDocumentObserved && state.domAwaitObserved && state.domBatchSent && state.domRejectionObserved && state.domEventsObserved && state.formsObserved && state.browserReady - && state.subscriberNotified && state.hostLoopStoppedByPage && browserCallsObserved() && cppCallsObserved() && rejectedWebSocket->rejectedRequests() >= 2)) { + if (!(state.domDocumentObserved && state.domAwaitObserved && state.domBatchSent && state.domRejectionObserved && state.domEventsObserved + && state.formsObserved && state.browserReady && state.subscriberNotified && state.hostLoopStoppedByPage && browserCallsObserved() + && cppCallsObserved() && rejectedWebSocket->rejectedRequests() >= 2)) { log::error("The specs passed but one of the bridge-direction checks failed"); return 1; } @@ -918,8 +990,7 @@ int main(int argc, char** argv) { vector driverArgs{argv[0]}; for (int i = 1; i < argc; ++i) { const string_view option(argv[i]); - if (!option.starts_with("--ignore-certificate-errors-spki-list=") && !option.starts_with("--user-data-dir=") - && option != "--disable-frame-rate-limit") + if (!option.starts_with("--ignore-certificate-errors-spki-list=") && !option.starts_with("--user-data-dir=") && option != "--disable-frame-rate-limit") driverArgs.push_back(argv[i]); } argc = static_cast(driverArgs.size()); diff --git a/test/web/MultiInstance.cpp b/test/web/MultiInstance.cpp index 87f057f2..2e8986ae 100644 --- a/test/web/MultiInstance.cpp +++ b/test/web/MultiInstance.cpp @@ -20,7 +20,9 @@ using Net = webfront::NetProvider; struct Instance { webfront::WebFront app; - std::thread server{[this] { app.run(); }}; + std::thread server{[this] { + app.run(); + }}; ~Instance() { app.stop(); if (server.joinable()) diff --git a/test/web/NativeIntegrationManual.cpp b/test/web/NativeIntegrationManual.cpp index 4789b7ec..c47f707a 100644 --- a/test/web/NativeIntegrationManual.cpp +++ b/test/web/NativeIntegrationManual.cpp @@ -138,7 +138,7 @@ std::future onUI(const UIExecutor& executor, F function) { struct State { std::promise result; decltype(ex::connect(std::declval(), std::declval>())) operation; - State(const UIExecutor& e, F f) : operation(ex::connect(e.schedule(), Receiver{&result, std::move(f)})) { } + State(const UIExecutor& e, F f) : operation(ex::connect(e.schedule(), Receiver{&result, std::move(f)})) {} }; static std::list> states; static std::mutex mutex; @@ -202,7 +202,7 @@ void nativeDialog(const UIExecutor& executor, HWND parent, int visibleMs) { owner = GetWindow(shownDialog, GW_OWNER); parentDisabled = parent && !IsWindowEnabled(parent); // The dialog's modal loop must keep dispatching the executor's wake-up message. - auto during = onUI(executor, [] { }); + auto during = onUI(executor, [] {}); ranDuringDialog = ready(during, Outcome::ran, 5); std::this_thread::sleep_for(std::chrono::milliseconds(visibleMs)); PostMessageW(shownDialog, WM_CLOSE, 0, 0); @@ -361,7 +361,7 @@ int validate(int visibleMs) { check(text(app.nativeWindow().get()) == (embedded ? "error notOpen" : "error unsupported"), "app.nativeWindow() before show(): " + text(app.nativeWindow().get())); { - auto early = onUI(executor, [] { }); + auto early = onUI(executor, [] {}); check(ready(early, Outcome::unavailable), "an operation scheduled before show() is refused (UIExecutorUnavailable)"); } @@ -481,7 +481,7 @@ int validate(int visibleMs) { check(scenarioDone, "show() returned after the scenario ended the loop"); check(!executor.available() && !executor.onUIThread(), "the executor is unavailable after the loop ended"); { - auto late = onUI(executor, [] { }); + auto late = onUI(executor, [] {}); check(ready(late, Outcome::unavailable), "an operation scheduled after closure is refused"); } check(text(app.nativeWindow().get()) == (embedded ? "error closed" : "error unsupported"), diff --git a/test/web/RejectedWebSocketServer.hpp b/test/web/RejectedWebSocketServer.hpp index fcb31fec..afbfb93d 100644 --- a/test/web/RejectedWebSocketServer.hpp +++ b/test/web/RejectedWebSocketServer.hpp @@ -12,7 +12,7 @@ // A test-owned endpoint that accepts HTTP requests but always refuses WebSocket upgrades. // Binding port zero keeps the initial-connection-failure tests independent of other services. class RejectedWebSocketServer { - using Net = webfront::networking::TCPStdnet; + using Net = webfront::networking::TCPStdnet; using Task = webfront::networking::Task; public: @@ -45,19 +45,20 @@ class RejectedWebSocketServer { private: static constexpr std::string_view response{"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"}; - Net::IoContext context; - Net::Acceptor acceptor; + Net::IoContext context; + Net::Acceptor acceptor; webfront::networking::TaskScope tasks; - std::atomic rejected{0}; - std::string endpointUrl; - std::jthread worker; + std::atomic rejected{0}; + std::string endpointUrl; + std::jthread worker; void spawn(Task task) { webfront::networking::Spawn(tasks, Net::Scheduler(acceptor), std::move(task)); } Task acceptConnections() { - for (;;) spawn(reject(co_await Net::Accept(acceptor))); + for (;;) + spawn(reject(co_await Net::Accept(acceptor))); } Task reject(Net::Socket socket) { diff --git a/test/web/TransportBenchmark.hpp b/test/web/TransportBenchmark.hpp index 1d693d8b..4f2eff29 100644 --- a/test/web/TransportBenchmark.hpp +++ b/test/web/TransportBenchmark.hpp @@ -53,7 +53,7 @@ int run(int argc, char** argv, const char* usage, const char* page = "transport- try { if (argc > 2) throw std::runtime_error(usage); - Report report; + Report report; App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); app.template cppFunction("echo", [](const std::string& value) { return value; diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 4291993a..090910e5 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -83,8 +83,7 @@ void nativeClose(bool quit) { { Session session("http://127.0.0.1:0/", {.visible = webfront::testdriver::visibleWindows}); session.create(); - require(static_cast(send(session.window, "isVisible")) == webfront::testdriver::visibleWindows, - "Window visibility option was ignored"); + require(static_cast(send(session.window, "isVisible")) == webfront::testdriver::visibleWindows, "Window visibility option was ignored"); // Exercise the real native entry points before any WebKit/bridge callback. if (quit) send(app, "terminate:", static_cast(nullptr)); @@ -208,8 +207,7 @@ void settings() { .visible = webfront::testdriver::visibleWindows }); session.create(); - require(static_cast(send(session.window, "isVisible")) == webfront::testdriver::visibleWindows, - "Window visibility option was ignored"); + require(static_cast(send(session.window, "isVisible")) == webfront::testdriver::visibleWindows, "Window visibility option was ignored"); require(static_cast(send(session.view, "isInspectable")) == enabled, "Inspector policy was ignored"); require(!send(send(send(session.view, "configuration"), "websiteDataStore"), "isPersistent"), "Website data was persistent"); Object menu(send(type("NSMenu"), "new")); @@ -223,7 +221,11 @@ void settings() { // A translucent background colour makes the window non-opaque, so what is behind it shows through; an opaque one does not. void translucentBackground() { Object pool(send(type("NSAutoreleasePool"), "new")); - for (const auto& [colour, translucent] : {std::pair{"#12345680", true}, {"#123456", false}, {"#123456ff", false}}) { + for (const auto& [colour, translucent] : { + std::pair{"#12345680", true}, + { "#123456", false}, + {"#123456ff", false} + }) { Session session("http://127.0.0.1:9002/", {.window = {.background = colour}, .visible = webfront::testdriver::visibleWindows}); session.create(); require(static_cast(send(session.window, "isOpaque")) != translucent, @@ -236,13 +238,17 @@ void translucentBackground() { } void hiddenScheduling() { - Object pool(send(type("NSAutoreleasePool"), "new")); - Object configuration(send(type("WKWebViewConfiguration"), "new")); + Object pool(send(type("NSAutoreleasePool"), "new")); + Object configuration(send(type("WKWebViewConfiguration"), "new")); const auto preferences = send(configuration.get(), "preferences"); - Session session("http://127.0.0.1:0/", {.visible = false}); + Session session("http://127.0.0.1:0/", {.visible = false}); // Check the runtime capability: a test binary built on macOS 14 can also run on macOS 13.3. if (!send(preferences, "respondsToSelector:", sel_registerName("setInactiveSchedulingPolicy:"))) { - expectFailure([&] { session.create(); }, "hidden sessions require macOS 14 or later"); + expectFailure( + [&] { + session.create(); + }, + "hidden sessions require macOS 14 or later"); return; } session.create(); @@ -256,8 +262,8 @@ void hiddenScheduling() { // A secondary window of a hidden application stays hidden, also when its page is opened again (which brings a visible // window to the front). void hiddenSecondary() { - Object pool(send(type("NSAutoreleasePool"), "new")); - Object configuration(send(type("WKWebViewConfiguration"), "new")); + Object pool(send(type("NSAutoreleasePool"), "new")); + Object configuration(send(type("WKWebViewConfiguration"), "new")); if (!send(send(configuration.get(), "preferences"), "respondsToSelector:", sel_registerName("setInactiveSchedulingPolicy:"))) return; // hidden sessions require macOS 14 (see hidden-scheduling) Session primary("http://127.0.0.1:0/", {.visible = false}); @@ -336,7 +342,7 @@ std::string readFile(const std::filesystem::path& path) { /// Opens a page with the file-service test injections of WKWebViewOptions, which a scenario fills in before show(). struct ScenarioFrontend : Frontend { static inline std::function configure; - static inline std::function started; + static inline std::function started; static void open(std::string_view port, std::string_view page) { initialize(); @@ -368,7 +374,7 @@ void download() { const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-download-" + std::to_string(getpid())); std::filesystem::remove_all(folder); std::string destination; - bool done = false; + bool done = false; ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { options.downloadDirectory = folder; // Created by the frontend when the download starts. options.downloadFinished = [&](const std::string& path) { @@ -384,7 +390,8 @@ void download() { // The suggested name "../webfront-download.txt" must never leave the download folder. WebKit already neutralizes the // separators before the frontend sees the name (it arrives as "_webfront-download.txt"), so the folder is what is checked. const std::filesystem::path saved(destination); - require(saved.parent_path() == folder && saved.filename().string().ends_with("webfront-download.txt"), ("Unexpected download destination: " + destination).c_str()); + require(saved.parent_path() == folder && saved.filename().string().ends_with("webfront-download.txt"), + ("Unexpected download destination: " + destination).c_str()); require(readFile(destination) == "downloaded by WebFront", "The downloaded file has the wrong content"); std::filesystem::remove_all(folder); } @@ -392,7 +399,7 @@ void download() { void chooseFile(bool cancel, const char* page = "file-services.html?choose", const char* click = "document.getElementById('picker').click()") { const auto fixture = std::filesystem::temp_directory_path() / ("webfront-wk-chooser-" + std::to_string(getpid()) + ".txt"); std::ofstream(fixture) << "chosen by the test"; - bool asked = false; + bool asked = false; static std::string finalTitle; finalTitle.clear(); ScenarioFrontend::configure = [&](webfront::frontend::WKWebViewOptions& options) { @@ -402,7 +409,7 @@ void chooseFile(bool cancel, const char* page = "file-services.html?choose", con }; }; static std::string clickScript; - clickScript = std::string("document.title === 'ready' && !window.clicked && (window.clicked = true, ") + click + ")"; + clickScript = std::string("document.title === 'ready' && !window.clicked && (window.clicked = true, ") + click + ")"; ScenarioFrontend::started = [](Session& session) { // A chooser needs a user gesture, and evaluateJavaScript counts as one. The page reports through its title. Session* live = &session; @@ -443,11 +450,11 @@ void chooseInSrcdocFrame() { /// Closing the window while a system panel is open: the panel answers "cancel" and its late answer touches nothing. void closeWithPanel(const char* page, const char* click) { - Object pool(send(type("NSAutoreleasePool"), "new")); - static bool sawPanel; + Object pool(send(type("NSAutoreleasePool"), "new")); + static bool sawPanel; static std::string script; - sawPanel = false; - script = click; + sawPanel = false; + script = click; ScenarioFrontend::configure = [](webfront::frontend::WKWebViewOptions& options) { options.visible = true; // No injection: the real NSSavePanel / NSOpenPanel opens as a sheet of a visible window. }; @@ -570,16 +577,16 @@ void replacedDownload() { const auto folder = std::filesystem::temp_directory_path() / ("webfront-wk-replace-" + std::to_string(getpid())); std::filesystem::remove_all(folder); std::filesystem::create_directories(folder); - const auto target = folder / "report.txt"; - std::filesystem::path temporary; + const auto target = folder / "report.txt"; + std::filesystem::path temporary; std::vector finished; - Session session("http://127.0.0.1:0/", {.visible = false, .downloadFinished = [&](const std::string& path) { + Session session("http://127.0.0.1:0/", {.visible = false, .downloadFinished = [&](const std::string& path) { finished.push_back(path); }}); - const auto start = [&](std::uintptr_t key, std::string_view oldContent, std::string_view downloaded) { + const auto start = [&](std::uintptr_t key, std::string_view oldContent, std::string_view downloaded) { std::ofstream(target) << oldContent; auto staging = std::make_unique(folder); - temporary = staging->path(); + temporary = staging->path(); if (!downloaded.empty()) std::ofstream(temporary) << downloaded; session.downloadDestinations[reinterpret_cast(key)] = {std::move(staging), target, false, true}; @@ -599,7 +606,7 @@ void replacedDownload() { // A failed ordinary download removes its private fragment and releases its destination. const auto ordinary = session.reservations.reserve(folder, "ordinary.txt"); - auto staging = std::make_unique(folder); + auto staging = std::make_unique(folder); std::ofstream(staging->path()) << "partial"; const auto key = reinterpret_cast(std::uintptr_t{4}); session.downloadDestinations[key] = {std::move(staging), ordinary, true, false}; @@ -607,7 +614,7 @@ void replacedDownload() { require(!std::filesystem::exists(ordinary), "A failed ordinary download left an incomplete file"); require(session.reservations.empty() && finished.size() == 1, "A failed download kept its reservation or reported success"); - staging = std::make_unique(folder); + staging = std::make_unique(folder); session.downloadDestinations[key] = {std::move(staging), ordinary, false, false}; std::ofstream(ordinary) << "created by another process"; session.downloadEnded(key, false); @@ -641,14 +648,15 @@ void navigationDiagnostic() { // The window is nearly transparent until the initial document has loaded; without that signal the delay shows it. void loadRevealPresentation(bool delayOnly) { - Object pool(send(type("NSAutoreleasePool"), "new")); + Object pool(send(type("NSAutoreleasePool"), "new")); webfront::http::Server server("127.0.0.1", "9002", std::filesystem::current_path()); - std::jthread worker([&](std::stop_token stop) { - std::stop_callback cleanup(stop, [&] { server.stop(); }); + std::jthread worker([&](std::stop_token stop) { + std::stop_callback cleanup(stop, [&] { + server.stop(); + }); server.run(); }); - Session session("http://127.0.0.1:9002/first-frame.html", - {.window = {.background = "#123456"}, .visible = true}); + Session session("http://127.0.0.1:9002/first-frame.html", {.window = {.background = "#123456"}, .visible = true}); session.revealOnLoad = !delayOnly; session.presentDelay = delayOnly ? 1.0 : 60.0; // the load, not the delay, must show the window session.create(); @@ -657,7 +665,7 @@ void loadRevealPresentation(bool delayOnly) { Object key(text("drawsBackground")); require(!send(send(session.view, "valueForKey:", key.get()), "boolValue"), "The view still paints its own background"); } - double shownAlpha = 0; + double shownAlpha = 0; session.presentation.windowShown = [&] { shownAlpha = send(session.window, "alphaValue"); session.close(); @@ -665,13 +673,16 @@ void loadRevealPresentation(bool delayOnly) { session.start(); session.run(); require(shownAlpha == 1.0, "The window was not made opaque"); - require(session.presentation.byFrame != delayOnly, delayOnly ? "The load revealed the window although it was disabled" : "The window waited for the delay instead of the document load"); + require(session.presentation.byFrame != delayOnly, + delayOnly ? "The load revealed the window although it was disabled" : "The window waited for the delay instead of the document load"); // The displayed pixels are not read: cacheDisplayInRect renders neither the window's fill nor the web content (it reads black), // and capturing the screen needs a permission the CI does not have. The state that produces them is checked instead: the // window's colour, and the view no longer painting its own background (above). const auto color = send(send(session.window, "backgroundColor"), "colorUsingColorSpace:", send(type("NSColorSpace"), "sRGBColorSpace")); require(color != nullptr, "The window has no colour in the sRGB space"); - const auto near = [](double value, double expected) { return value > expected - 0.01 && value < expected + 0.01; }; + const auto near = [](double value, double expected) { + return value > expected - 0.01 && value < expected + 0.01; + }; require(near(send(color, "redComponent"), 0x12 / 255.0) && near(send(color, "greenComponent"), 0x34 / 255.0) && near(send(color, "blueComponent"), 0x56 / 255.0), "The window does not have the configured background colour"); @@ -682,33 +693,38 @@ int main(int argc, char** argv) { try { checkWKWebViewHeader(); const std::map cases{ - { "repeated-show", repeatedShow}, - { "main-thread", mainThread}, - { "native-close", nativeEarlyClose}, - { "quit", quit}, - { "startup-timeout", startupTimeout}, - { "redirect-policy", redirectPolicy}, - { "settings", settings}, - { "hidden-scheduling", hiddenScheduling}, - { "hidden-secondary", hiddenSecondary}, - {"translucent-background", translucentBackground}, - {"navigation-diagnostic", navigationDiagnostic}, - { "missing-response", missingResponse}, - { "committed-navigation", committedNavigation}, - { "agent-application", agentApplication}, - { "download", download}, - { "choose-file", chooseOne}, - { "cancel-choose", chooseCancel}, - { "replaced-download", replacedDownload}, - { "choose-in-blank", chooseInBlankFrame}, - { "choose-in-srcdoc", chooseInSrcdocFrame}, - { "close-with-open-panel", closeWithOpenPanel}, - { "close-with-save-panel", closeWithSavePanel}, - { "script-dialogs", scriptDialogs}, - { "close-with-script-dialog", closeWithScriptDialog}, + { "repeated-show",repeatedShow }, + { "main-thread", mainThread}, + { "native-close", nativeEarlyClose}, + { "quit", quit}, + { "startup-timeout", startupTimeout}, + { "redirect-policy", redirectPolicy}, + { "settings", settings}, + { "hidden-scheduling", hiddenScheduling}, + { "hidden-secondary", hiddenSecondary}, + { "translucent-background", translucentBackground}, + { "navigation-diagnostic", navigationDiagnostic}, + { "missing-response", missingResponse}, + { "committed-navigation", committedNavigation}, + { "agent-application", agentApplication}, + { "download", download}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel}, + { "replaced-download", replacedDownload}, + { "choose-in-blank", chooseInBlankFrame}, + { "choose-in-srcdoc", chooseInSrcdocFrame}, + { "close-with-open-panel", closeWithOpenPanel}, + { "close-with-save-panel", closeWithSavePanel}, + { "script-dialogs", scriptDialogs}, + {"close-with-script-dialog", closeWithScriptDialog}, { "sandboxed-script-dialog", sandboxedScriptDialog}, - { "load-reveal", [] { loadRevealPresentation(false); }}, - { "present-timeout", [] { loadRevealPresentation(true); }} + { "load-reveal", + [] { + loadRevealPresentation(false); + } }, + { "present-timeout", [] { + loadRevealPresentation(true); + } } }; cases.at(argc == 2 ? argv[1] : "")(); return 0; diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 87f43a22..bed06960 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -2,20 +2,21 @@ #include #include +#include #include #include -#include -#include -#include -#include -#include #include #include #include #include +#include #include +#include +#include #include +#include + #if defined(GTK_MAJOR_VERSION) || defined(G_TYPE_OBJECT) || defined(Bool) || defined(None) || defined(signals) #error WebFront.hpp must not expose GTK, GLib or X11 macros #endif @@ -164,8 +165,9 @@ struct NativeClosingFrontend : Frontend { static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { open(address, port, page, policy, webfront::WindowOptions{}); } - static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy, const webfront::WindowOptions& window) { - gtk::Session session(webfront::detail::BoundContentPolicy{webfront::frontend::detail::applicationUrl(address, port, ""), policy}, window); + static void + open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy, const webfront::WindowOptions& window) { + gtk::Session session(webfront::detail::BoundContentPolicy{webfront::frontend::detail::applicationUrl(address, port, ""), policy}, window); session.create(); CloseDuringLoop probe(session); session.run(webfront::frontend::detail::applicationUrl(address, port, page)); @@ -183,21 +185,22 @@ void nativeClose() { struct ScenarioFrontend : Frontend { static inline std::function configure; static inline std::function finished; // Polled; true closes the window. - static void open(std::string_view port, std::string_view page) { + static void open(std::string_view port, std::string_view page) { open("127.0.0.1", port, page, {}); } static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy) { open(address, port, page, policy, webfront::WindowOptions{}); } - static void open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy, const webfront::WindowOptions& window) { + static void + open(std::string_view address, std::string_view port, std::string_view page, const webfront::ContentPolicy& policy, const webfront::WindowOptions& window) { gtk::Session session(webfront::detail::BoundContentPolicy{webfront::frontend::detail::applicationUrl(address, port, ""), policy}, window); session.create(); configure(session); struct Poll { - gtk::Session& session; + gtk::Session& session; std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + std::chrono::seconds(45); - unsigned timer = 0; - std::exception_ptr failure{}; + unsigned timer = 0; + std::exception_ptr failure{}; } poll{session}; poll.timer = session.a.timeoutAdd( 100, @@ -212,7 +215,7 @@ struct ScenarioFrontend : Frontend { done = finished(probe.session); } catch (...) { probe.failure = std::current_exception(); - done = true; + done = true; } if (done || std::chrono::steady_clock::now() >= probe.deadline) { probe.timer = 0; @@ -234,18 +237,22 @@ using ScenarioApp = webfront::BasicWFWithFrontend bool { + ScenarioFrontend::finished = [](gtk::Session&) -> bool { throw std::runtime_error("poll failure"); }; ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); - expectFailure([&] { app.show("no-bridge.html"); }, "poll failure"); + expectFailure( + [&] { + app.show("no-bridge.html"); + }, + "poll failure"); } std::string readFile(const std::filesystem::path& path) { std::ifstream stream(path, std::ios::binary); if (!stream) throw std::runtime_error("Cannot open downloaded file: " + path.string()); - std::string result; + std::string result; std::array buffer; while (stream.read(buffer.data(), buffer.size()) || stream.gcount() != 0) result.append(buffer.data(), static_cast(stream.gcount())); @@ -259,7 +266,7 @@ void download() { const auto folder = parent / "not" / "yet"; // The frontend creates the folder: WebKitGTK writes into an existing one only. std::filesystem::remove_all(parent); std::string destination; - bool done = false; + bool done = false; ScenarioFrontend::configure = [&](gtk::Session& session) { session.downloadDirectory = folder; session.downloadFinished = [&](const std::string& path) { @@ -298,7 +305,7 @@ void downloadUserDirectory() { setenv("XDG_CONFIG_HOME", config.c_str(), 1); setenv("XDG_DOWNLOAD_DIR", decoy.c_str(), 1); std::string destination; - bool done = false; + bool done = false; ScenarioFrontend::configure = [&](gtk::Session& session) { session.downloadFinished = [&](const std::string& path) { destination = path; @@ -389,7 +396,7 @@ void chooseFile(bool cancel) { const FakeClick pointer; if (!pointer.available()) throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); - int ticks = 0; + int ticks = 0; ScenarioFrontend::finished = [&](gtk::Session& session) { const char* current = session.a.viewTitle(session.view); title = current ? current : ""; @@ -401,8 +408,8 @@ void chooseFile(bool cancel) { app.show("file-services.html?choose"); std::filesystem::remove(fixture); if (!asked) - throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + - std::to_string(ticks / 5 + (ticks % 5 == 4)) + " clicks, " + std::to_string(ticks) + " pointer steps)"); + throw std::runtime_error("The file chooser was not requested (page title \"" + title + "\", " + std::to_string(ticks / 5 + (ticks % 5 == 4)) + + " clicks, " + std::to_string(ticks) + " pointer steps)"); const std::string expected = cancel ? "cancelled" : "picked:chosen by the test"; if (title != expected) throw std::runtime_error("Unexpected page state after the chooser: " + title); @@ -416,8 +423,8 @@ void chooseCancel() { /// Closing the window while the system file dialog is open must end cleanly, without waiting for an answer. void closeWithDialog() { - bool opened = false; - int open = 0; // Poll ticks since the dialog opened. + bool opened = false; + int open = 0; // Poll ticks since the dialog opened. ScenarioFrontend::configure = [&](gtk::Session& session) { session.chooserOpened = [&] { opened = true; @@ -427,7 +434,7 @@ void closeWithDialog() { const FakeClick pointer; if (!pointer.available()) throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); - int ticks = 0; + int ticks = 0; ScenarioFrontend::finished = [&](gtk::Session& session) { const char* current = session.a.viewTitle(session.view); title = current ? current : ""; @@ -438,8 +445,8 @@ void closeWithDialog() { ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); app.show("file-services.html?choose"); if (!opened) - throw std::runtime_error("The file dialog was not opened (page title \"" + title + "\", " + - std::to_string(ticks / 5 + (ticks % 5 == 4)) + " clicks, " + std::to_string(ticks) + " pointer steps)"); + throw std::runtime_error("The file dialog was not opened (page title \"" + title + "\", " + std::to_string(ticks / 5 + (ticks % 5 == 4)) + " clicks, " + + std::to_string(ticks) + " pointer steps)"); } /// alert, confirm and prompt reach the injection point and their answers reach the page (issue #452). @@ -471,7 +478,7 @@ void scriptDialogs() { /// Closing the window while WebKitGTK's own script dialog is open must end cleanly, without waiting for an answer. void closeWithScriptDialog() { - using Clock = std::chrono::steady_clock; + using Clock = std::chrono::steady_clock; bool opened = false; Clock::time_point openedAt; ScenarioFrontend::configure = [&](gtk::Session& session) { @@ -524,7 +531,7 @@ int childNamed(std::string_view name) { const auto open = line.find('('), close = line.rfind(')'); if (open == std::string::npos || close == std::string::npos) continue; - int parent = 0; + int parent = 0; std::istringstream rest(line.substr(close + 4)); rest >> parent; if (parent == getpid() && line.substr(open + 1, close - open - 1).starts_with(name.substr(0, 15))) @@ -537,13 +544,13 @@ int childNamed(std::string_view name) { /// process it starts during the session, keeps its own values. void mediaOptOutIsScoped() { setenv("GST_PLUGIN_SYSTEM_PATH_1_0", "/webfront-sentinel", 1); - bool shown = false, checked = false; + bool shown = false, checked = false; std::string failure; - bool exposedAtStart = false; + bool exposedAtStart = false; ScenarioFrontend::configure = [&](gtk::Session& session) { // The documented window: process-wide until the load starts, so the opt-out is visible to the application here. - const auto during = std::getenv("GST_PLUGIN_SYSTEM_PATH_1_0"); - exposedAtStart = during && std::string_view(during) == session.mediaPlugins.string(); + const auto during = std::getenv("GST_PLUGIN_SYSTEM_PATH_1_0"); + exposedAtStart = during && std::string_view(during) == session.mediaPlugins.string(); session.presentation.windowShown = [&] { shown = true; }; @@ -557,7 +564,7 @@ void mediaOptOutIsScoped() { // An unrelated child, started now, inherits the application's value. std::unique_ptr pipe(popen("printenv GST_PLUGIN_SYSTEM_PATH_1_0", "r"), pclose); char buffer[128]{}; - if (pipe && fgets(buffer, sizeof buffer, pipe.get()); std::string_view(buffer).find("/webfront-sentinel") == std::string_view::npos) + if (pipe&& fgets(buffer, sizeof buffer, pipe.get()); std::string_view(buffer).find("/webfront-sentinel") == std::string_view::npos) failure = "An unrelated child did not inherit the application's environment: " + std::string(buffer); // WebKit's web process got the restriction. if (const auto web = childNamed("WebKitWebProces"); web == 0) @@ -567,7 +574,7 @@ void mediaOptOutIsScoped() { std::string found; const auto env = environmentOf(web); for (std::size_t at = 0; at < env.size();) { - const auto end = env.find('\0', at); + const auto end = env.find('\0', at); const auto item = env.substr(at, end == std::string::npos ? std::string::npos : end - at); if (item.starts_with("GST_")) found += item + " "; @@ -582,7 +589,7 @@ void mediaOptOutIsScoped() { }; ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path(), .window = {.media = false}}); app.show("first-frame.html"); - const auto after = std::getenv("GST_PLUGIN_SYSTEM_PATH_1_0"); + const auto after = std::getenv("GST_PLUGIN_SYSTEM_PATH_1_0"); const bool restored = after && std::string_view(after) == "/webfront-sentinel"; unsetenv("GST_PLUGIN_SYSTEM_PATH_1_0"); if (!restored) @@ -607,7 +614,10 @@ void firstFramePresentation(bool noFrame) { ScenarioFrontend::finished = [&](gtk::Session&) { return shown; }; - ScenarioApp app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path(), .window = {.background = "#123456", .media = false}}); // no media: the web process runs without GStreamer plugins + ScenarioApp app(webfront::WebFrontConfig{ + .documentRoot = std::filesystem::current_path(), + .window = {.background = "#123456", .media = false} + }); // no media: the web process runs without GStreamer plugins app.show(noFrame ? "first-frame.html?no-frame" : "first-frame.html"); if (!shown) throw std::runtime_error("The window was never shown"); @@ -645,27 +655,32 @@ void profilePermissions() { void run(std::string_view mode) { const std::map cases{ - {"sandbox-recheck", sandboxRecheck}, - {"sandbox-environment", sandboxEnvironment}, - { "no-display", noDisplay}, - { "worker-thread", workerThread}, - { "repeated-show", repeatedShow}, - { "http-error", httpError}, - { "native-close", nativeClose}, - { "pre-run-failure", preRunFailure}, - { "poll-failure", pollFailure}, - {"profile-permissions", profilePermissions}, - { "window-title", windowTitle}, - { "download", download}, - {"download-user-dir", downloadUserDirectory}, - { "close-with-dialog", closeWithDialog}, - { "choose-file", chooseOne}, - { "cancel-choose", chooseCancel}, - { "script-dialogs", scriptDialogs}, + { "sandbox-recheck",sandboxRecheck }, + { "sandbox-environment", sandboxEnvironment}, + { "no-display", noDisplay}, + { "worker-thread", workerThread}, + { "repeated-show", repeatedShow}, + { "http-error", httpError}, + { "native-close", nativeClose}, + { "pre-run-failure", preRunFailure}, + { "poll-failure", pollFailure}, + { "profile-permissions", profilePermissions}, + { "window-title", windowTitle}, + { "download", download}, + { "download-user-dir", downloadUserDirectory}, + { "close-with-dialog", closeWithDialog}, + { "choose-file", chooseOne}, + { "cancel-choose", chooseCancel}, + { "script-dialogs", scriptDialogs}, {"close-with-script-dialog", closeWithScriptDialog}, - { "media-scoped", mediaOptOutIsScoped}, - { "first-frame", [] { firstFramePresentation(false); }}, - { "present-timeout", [] { firstFramePresentation(true); }} + { "media-scoped", mediaOptOutIsScoped}, + { "first-frame", + [] { + firstFramePresentation(false); + } }, + { "present-timeout", [] { + firstFramePresentation(true); + } } }; const auto selected = cases.find(mode); if (selected == cases.end()) diff --git a/test/web/WebKitGTKTransportBenchmark.cpp b/test/web/WebKitGTKTransportBenchmark.cpp index 51e05be4..112ee2ff 100644 --- a/test/web/WebKitGTKTransportBenchmark.cpp +++ b/test/web/WebKitGTKTransportBenchmark.cpp @@ -131,9 +131,9 @@ class DirectChannel : public std::enable_shared_from_this { // Always called once per evaluation, with an error when the view is destroyed first. static void onEvaluated(Object view, Object result, std::weak_ptr* pending) noexcept { const std::unique_ptr> owned(pending); - const auto& api = DirectApi::shared(); - gtk::Api::Error* error = nullptr; - const auto value = api.evaluateFinish(view, result, &error); + const auto& api = DirectApi::shared(); + gtk::Api::Error* error = nullptr; + const auto value = api.evaluateFinish(view, result, &error); if (const auto self = owned->lock()) return self->completed(value, error); // The window closed first: the channel and its session are gone, the result is only released. @@ -146,8 +146,7 @@ class DirectChannel : public std::enable_shared_from_this { bool echoed = false; try { echoed = value && text(value) == payload; - } catch (...) { - } + } catch (...) {} if (value) session.a.unref(value); if (error) @@ -168,7 +167,7 @@ class DirectChannel : public std::enable_shared_from_this { } public: - explicit DirectChannel(gtk::Session& live) : session(live) { } + explicit DirectChannel(gtk::Session& live) : session(live) {} void attach() { listen("wfecho", onEcho); listen("wfrun", onRun); diff --git a/test/web/WebView2Lifecycle.cpp b/test/web/WebView2Lifecycle.cpp index 58845a8d..5be17ae3 100644 --- a/test/web/WebView2Lifecycle.cpp +++ b/test/web/WebView2Lifecycle.cpp @@ -5,8 +5,8 @@ #include #include -#include #include +#include #include #include #include @@ -164,23 +164,27 @@ int startupCompletion(bool failed) { int firstFramePresentation(bool noFrame) { using namespace webfront::frontend::detail::webview2; webfront::http::Server server("127.0.0.1", "9002", std::filesystem::current_path()); - std::jthread worker([&](std::stop_token stop) { - std::stop_callback cleanup(stop, [&] { server.stop(); }); + std::jthread worker([&](std::stop_token stop) { + std::stop_callback cleanup(stop, [&] { + server.stop(); + }); server.run(); }); - Apartment apartment; - auto session = std::make_shared(); - session->url = noFrame ? L"http://127.0.0.1:9002/first-frame.html?no-frame" : L"http://127.0.0.1:9002/first-frame.html"; + Apartment apartment; + auto session = std::make_shared(); + session->url = noFrame ? L"http://127.0.0.1:9002/first-frame.html?no-frame" : L"http://127.0.0.1:9002/first-frame.html"; session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {}}; webfront::WindowOptions options; options.background = "#123456"; session->createWindow(true, options); BYTE alpha = 0; require(GetLayeredWindowAttributes(session->window, nullptr, &alpha, nullptr) && alpha == 3, "Window was not initially nearly transparent"); - bool messageReceived = false; - bool observed = false; + bool messageReceived = false; + bool observed = false; Actions actions; - actions.onFailure = [&] { session->fail(); }; + actions.onFailure = [&] { + session->fail(); + }; session->viewReady = [&] { Microsoft::WRL::ComPtr controller; check(session->controller.As(&controller), "querying background controller"); @@ -189,19 +193,25 @@ int firstFramePresentation(bool noFrame) { require(color.A == 255 && color.R == 0x12 && color.G == 0x34 && color.B == 0x56, "Background did not reach WebView2"); EventRegistrationToken token{}; check(session->view->add_WebMessageReceived( - Microsoft::WRL::Callback([&](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { - LPWSTR raw = nullptr; - if (SUCCEEDED(args->TryGetWebMessageAsString(&raw)) && raw) { - const std::unique_ptr message(raw, CoTaskMemFree); - if (std::wstring_view{message.get()} == L"webfront:first-frame") messageReceived = true; - } - return S_OK; - }).Get(), &token), "observing first frame"); + Microsoft::WRL::Callback([&](ICoreWebView2*, + ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { + LPWSTR raw = nullptr; + if (SUCCEEDED(args->TryGetWebMessageAsString(&raw)) && raw) { + const std::unique_ptr message(raw, CoTaskMemFree); + if (std::wstring_view{message.get()} == L"webfront:first-frame") + messageReceived = true; + } + return S_OK; + }).Get(), + &token), + "observing first frame"); }; actions.dispatch = [&](UINT) { BYTE current = 0; - if (!GetLayeredWindowAttributes(session->window, nullptr, ¤t, nullptr) || current != 255) return; - if (!noFrame && !messageReceived) return; + if (!GetLayeredWindowAttributes(session->window, nullptr, ¤t, nullptr) || current != 255) + return; + if (!noFrame && !messageReceived) + return; require(!noFrame || !messageReceived, "A suppressed frame unexpectedly arrived"); observed = true; KillTimer(actions.window, 1); @@ -210,7 +220,8 @@ int firstFramePresentation(bool noFrame) { require(SetTimer(actions.window, 1, 10, nullptr) != 0, "Cannot start presentation observer"); session->start(userDataFolder()); session->run(); - if (actions.failure) std::rethrow_exception(actions.failure); + if (actions.failure) + std::rethrow_exception(actions.failure); require(observed, "Window was not revealed"); return 0; } @@ -425,8 +436,8 @@ int scriptDialogs() { }); Apartment apartment; auto session = std::make_shared(); - session->url = L"http://127.0.0.1:9002/script-dialogs.html"; - session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {}}; + session->url = L"http://127.0.0.1:9002/script-dialogs.html"; + session->contentPolicy = webfront::detail::BoundContentPolicy{"http://127.0.0.1:9002", {}}; std::vector seen; session->answerScriptDialog = [&](const webfront::frontend::ScriptDialog& dialog) { using Kind = webfront::frontend::ScriptDialog::Kind; @@ -441,8 +452,8 @@ int scriptDialogs() { session->fail(); }; std::wstring title; - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{30}; - actions.dispatch = [&](UINT) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{30}; + actions.dispatch = [&](UINT) { if (std::chrono::steady_clock::now() >= deadline) throw std::runtime_error("Script dialog scenario timed out"); if (!session->view) @@ -526,7 +537,8 @@ int runtimeReadyBeforePageLoad() { EventRegistrationToken token{}; // The session turns the page's window.close() into a host message (Chromium may ignore the native request). check(session->view->add_WebMessageReceived( - Microsoft::WRL::Callback([&](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { + Microsoft::WRL::Callback([&](ICoreWebView2*, + ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { LPWSTR raw = nullptr; if (SUCCEEDED(args->TryGetWebMessageAsString(&raw)) && raw) { const std::unique_ptr message(raw, CoTaskMemFree); @@ -682,52 +694,58 @@ int run(std::string_view mode) { if (!webView2ClosesServer()) return 1; const std::map> cases{ - {"first-frame", [] { return firstFramePresentation(false); }}, - {"present-timeout", [] { return firstFramePresentation(true); }}, - { "file-choose", + { "first-frame", + [] { + return firstFramePresentation(false); + } }, + { "present-timeout", + [] { + return firstFramePresentation(true); + } }, + { "file-choose", [] { return fileServices("choose"); - } }, - { "file-cancel", + } }, + { "file-cancel", [] { return fileServices("cancel"); - } }, - { "script-dialogs", scriptDialogs}, - { "file-download", + } }, + { "script-dialogs", scriptDialogs}, + { "file-download", [] { return fileServices("download"); - } }, - { "runtime-ready", runtimeReadyBeforePageLoad}, - { "closed-startup-timeout", + } }, + { "runtime-ready", runtimeReadyBeforePageLoad}, + { "closed-startup-timeout", [] { return startupCompletion(false); - } }, - { "failed-startup-timeout", + } }, + { "failed-startup-timeout", [] { return startupCompletion(true); - } }, - {"late-navigation-failure", lateNavigationFailure}, - {"secondary-startup-timeout", secondaryStartupTimeout}, - { "mta", rejectMta}, - { "missing-runtime", + } }, + { "late-navigation-failure", lateNavigationFailure}, + {"secondary-startup-timeout", secondaryStartupTimeout}, + { "mta", rejectMta}, + { "missing-runtime", [] { SetEnvironmentVariableW(L"WEBVIEW2_BROWSER_EXECUTABLE_FOLDER", L"C:\\WebFront-runtime-does-not-exist"); return expectOpenFailure("9002", "Evergreen Runtime"); - } }, - { "repeated-show", + } }, + { "repeated-show", [] { showTwice("rejected-ready.html", false, false); showTwice("encoded path %23.html?x=1#example", false, false); return showTwice("no-bridge.html"); - } }, - { "navigation-diagnostic", + } }, + { "navigation-diagnostic", [] { return expectOpenFailure("0", "navigation failed"); - } }, - { "native-early-close", + } }, + { "native-early-close", [] { return showTwice("no-bridge.html", true); - } }, + } }, }; const auto test = cases.find(mode); return test == cases.end() ? 1 : test->second(); diff --git a/test/web/WebView2TransportBenchmark.cpp b/test/web/WebView2TransportBenchmark.cpp index 393603a3..dfe3d5a4 100644 --- a/test/web/WebView2TransportBenchmark.cpp +++ b/test/web/WebView2TransportBenchmark.cpp @@ -59,7 +59,7 @@ class DirectChannel : public std::enable_shared_from_this { const std::unique_ptr owned(raw, CoTaskMemFree); // "id\nname\ntext" const std::wstring_view message(raw); - const auto idEnd = message.find(L'\n'); + const auto idEnd = message.find(L'\n'); const auto nameEnd = idEnd == message.npos ? idEnd : message.find(L'\n', idEnd + 1); if (nameEnd == message.npos) return; @@ -187,7 +187,7 @@ class DirectChannel : public std::enable_shared_from_this { } public: - DirectChannel(ComPtr browser, ComPtr factory) : view(std::move(browser)), environment(std::move(factory)) { } + DirectChannel(ComPtr browser, ComPtr factory) : view(std::move(browser)), environment(std::move(factory)) {} DirectChannel(const DirectChannel&) = delete; DirectChannel& operator=(const DirectChannel&) = delete; ~DirectChannel() { From 91d7e92bfcae433fe1caeafe82c528caccc15120 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:20:18 +0100 Subject: [PATCH 2/8] Give every C++ source the normalized file header (#653) SPDX, author, creation date, subsystem, role, thread and allocation model and a reading hint, absorbing the former @date, @author and @brief lines. --- cmake/mddlog/Logger.cpp | 10 +++- examples/PortOption.hpp | 9 ++++ examples/hello-world/HelloWorld.cpp | 9 ++++ examples/host-loop/BoingCuda.cu | 9 ++++ examples/host-loop/BoingCuda.hpp | 9 ++++ examples/host-loop/BoingHost.hpp | 9 ++++ examples/host-loop/BoingScene.hpp | 9 ++++ examples/host-loop/HostLoop.cpp | 9 ++++ examples/host-loop/HostLoopCapture.hpp | 9 ++++ examples/host-loop/HostLoopUI.hpp | 9 ++++ examples/life/Life.hpp | 9 ++++ examples/life/LifeConsole.cpp | 9 ++++ examples/life/LifeDeveloper.cpp | 9 ++++ examples/life/LifeDeveloperOptions.hpp | 9 ++++ examples/life/LifeEmbedded.cpp | 9 ++++ examples/life/LifeFrontend.hpp | 9 ++++ examples/life/react/LifeReact.cpp | 9 ++++ examples/life/react/LifeReact.hpp | 9 ++++ examples/pty/main.cpp | 9 ++++ include/webfront/ApplicationOrigin.hpp | 9 ++++ include/webfront/BridgeError.hpp | 10 +++- include/webfront/Broadcast.hpp | 9 +++- include/webfront/Commands.hpp | 14 +++++- include/webfront/ContentPolicy.hpp | 9 ++++ include/webfront/DeferredCalls.hpp | 10 +++- include/webfront/DeveloperApp.hpp | 10 +++- include/webfront/JsFunction.hpp | 12 +++-- include/webfront/JsFunctionSender.hpp | 10 +++- include/webfront/Pty.hpp | 10 +++- include/webfront/PtyPage.hpp | 10 +++- include/webfront/ReadBinding.hpp | 37 ++++++++------ include/webfront/Task.hpp | 10 +++- include/webfront/UISubscribers.hpp | 10 +++- include/webfront/UIThread.hpp | 22 ++++++--- include/webfront/ViewAssociation.hpp | 26 ++++++---- include/webfront/WebFront.hpp | 11 +++-- include/webfront/automation/Binding.hpp | 10 +++- include/webfront/automation/Channel.hpp | 16 +++++-- include/webfront/automation/Contract.hpp | 10 +++- include/webfront/automation/Credentials.hpp | 10 +++- include/webfront/automation/Discovery.hpp | 24 +++++++--- include/webfront/automation/Enable.hpp | 48 +++++++++++-------- include/webfront/automation/Instructions.hpp | 10 +++- include/webfront/automation/Json.hpp | 10 +++- include/webfront/automation/Mcp.hpp | 10 +++- include/webfront/automation/McpHttp.hpp | 28 +++++++---- .../automation/PageAuthentication.hpp | 10 +++- include/webfront/automation/Platform.hpp | 10 +++- include/webfront/automation/Session.hpp | 10 +++- .../webfront/components/forms/Description.hpp | 16 +++++-- include/webfront/components/forms/Form.hpp | 14 +++++- .../webfront/components/forms/Reflection.hpp | 18 +++++-- include/webfront/components/pty/Options.hpp | 9 ++++ include/webfront/components/pty/Unix.hpp | 9 ++++ include/webfront/components/pty/Windows.hpp | 9 ++++ include/webfront/components/react/Store.hpp | 10 +++- include/webfront/details/C++20Support.hpp | 12 +++-- include/webfront/details/C++23Support.hpp | 12 +++-- include/webfront/dom/Document.hpp | 10 +++- include/webfront/frontend/Action.hpp | 9 ++++ include/webfront/frontend/CEF.hpp | 9 ++++ include/webfront/frontend/CEFPaths.hpp | 9 ++++ include/webfront/frontend/Capture.hpp | 10 +++- include/webfront/frontend/CloseRequest.hpp | 22 ++++++--- include/webfront/frontend/DefaultBrowser.hpp | 9 ++++ include/webfront/frontend/Downloads.hpp | 9 ++++ .../webfront/frontend/EmbeddedFrontend.hpp | 11 ++++- include/webfront/frontend/Frontend.hpp | 9 ++++ include/webfront/frontend/NativeWebView.hpp | 9 ++++ include/webfront/frontend/NativeWindow.hpp | 34 ++++++++----- include/webfront/frontend/ProfileLease.hpp | 9 ++++ include/webfront/frontend/ScriptDialogs.hpp | 9 ++++ include/webfront/frontend/StartupTrace.hpp | 13 ++++- include/webfront/frontend/UIExecutor.hpp | 34 ++++++++----- include/webfront/frontend/UILoop.hpp | 26 ++++++---- include/webfront/frontend/Url.hpp | 9 ++++ include/webfront/frontend/WKWebView.hpp | 9 ++++ include/webfront/frontend/WebKitGTK.hpp | 9 ++++ include/webfront/frontend/WebKitGTKPolicy.hpp | 9 ++++ include/webfront/frontend/WebView2.hpp | 9 ++++ include/webfront/frontend/Window.hpp | 9 ++++ include/webfront/frontend/WindowRegistry.hpp | 13 ++++- include/webfront/http/AcceptEncoding.hpp | 10 +++- include/webfront/http/BlockingWorker.hpp | 10 +++- include/webfront/http/BuffersPolicy.hpp | 12 +++-- include/webfront/http/Encodings.hpp | 12 +++-- include/webfront/http/Gzip.hpp | 10 +++- include/webfront/http/GzipCache.hpp | 10 +++- include/webfront/http/GzipExecutor.hpp | 10 +++- include/webfront/http/HTTPServer.hpp | 12 +++-- include/webfront/http/MimeType.hpp | 12 +++-- include/webfront/http/Ranges.hpp | 10 +++- include/webfront/http/WebSocket.hpp | 12 +++-- .../webfront/networking/BasicNetworking.hpp | 12 +++-- .../webfront/networking/NetworkingMock.hpp | 12 +++-- include/webfront/networking/SenderHeaders.hpp | 22 ++++++--- .../networking/TCPNetworkingStdnet.hpp | 20 ++++++-- include/webfront/networking/TCPSockets.hpp | 12 +++-- include/webfront/networking/Tasks.hpp | 10 +++- include/webfront/system/DefaultFS.hpp | 14 +++++- include/webfront/system/DeveloperFS.hpp | 10 +++- include/webfront/system/DeveloperFiles.hpp | 10 +++- include/webfront/system/DeveloperJournal.hpp | 10 +++- include/webfront/system/DeveloperPaths.hpp | 10 +++- include/webfront/system/DeveloperStore.hpp | 10 +++- include/webfront/system/FileSystem.hpp | 12 +++-- include/webfront/system/FontStacks.hpp | 22 ++++++--- include/webfront/system/IndexFS.hpp | 12 +++-- include/webfront/system/MemoryStorage.hpp | 14 +++++- include/webfront/system/NativeFS.hpp | 12 +++-- include/webfront/system/NativeStorage.hpp | 14 +++++- include/webfront/system/SafePath.hpp | 10 +++- include/webfront/system/Storage.hpp | 14 +++++- include/webfront/system/WindowsArguments.hpp | 9 ++++ include/webfront/system/WindowsCompat.hpp | 9 ++++ include/webfront/testing/Bdd.hpp | 48 +++++++++++-------- include/webfront/testing/Capture.hpp | 10 +++- include/webfront/testing/Host.hpp | 10 +++- include/webfront/testing/Jasmine.hpp | 10 +++- include/webfront/testing/Process.hpp | 10 +++- include/webfront/tls/Credentials.hpp | 9 ++++ include/webfront/tls/Server.hpp | 9 ++++ include/webfront/tls/WebFront.hpp | 9 ++++ include/webfront/tls/detail/ChaChaPoly.hpp | 9 ++++ include/webfront/tls/detail/Crypto.hpp | 9 ++++ include/webfront/tls/detail/Curves.hpp | 9 ++++ include/webfront/tls/detail/Field.hpp | 9 ++++ include/webfront/tls/detail/Protocol.hpp | 9 ++++ include/webfront/tls/detail/Wire.hpp | 9 ++++ include/webfront/tooling/HexDump.hpp | 12 +++-- include/webfront/tooling/Logger.hpp | 12 +++-- include/webfront/tooling/LoggerApi.hpp | 15 ++++-- include/webfront/tooling/MddlogLogger.hpp | 12 ++++- include/webfront/tooling/PathUtils.hpp | 22 +++++---- include/webfront/utils/Json.hpp | 14 +++++- include/webfront/utils/Sha256.hpp | 10 +++- include/webfront/utils/TypeErasedFunction.hpp | 12 +++-- include/webfront/weblink/CallFrame.hpp | 9 +++- include/webfront/weblink/DomBatch.hpp | 12 ++++- include/webfront/weblink/Messages.hpp | 12 +++-- include/webfront/weblink/PendingCalls.hpp | 10 +++- include/webfront/weblink/WebLink.hpp | 12 +++-- test/cmake/bdd-consumer/main.cpp | 9 +++- test/cmake/consumer/bdd.cpp | 9 +++- test/cmake/consumer/main.cpp | 10 ++++ test/cmake/module-scan/main.cpp | 9 ++++ test/driver/DriverDeadline.hpp | 9 ++++ test/driver/RequestLog.hpp | 10 ++++ test/driver/TestFrontend.hpp | 9 ++++ test/driver/WebFrontWf.cpp | 10 ++++ test/driver/WfDriver.hpp | 10 ++++ test/fixtures/pty/Probe.cpp | 9 ++++ test/fuzz/GzipDifferential.cpp | 9 ++++ test/fuzz/GzipDifferentialFuzz.cpp | 9 ++++ test/fuzz/GzipFuzz.cpp | 9 ++++ test/fuzz/GzipZlib.hpp | 9 ++++ test/fuzz/HTTPFuzz.cpp | 9 ++++ test/fuzz/MessagesFuzz.cpp | 9 ++++ test/fuzz/TLSFuzz.cpp | 9 ++++ test/fuzz/WebSocketFuzz.cpp | 9 ++++ test/unit/AcceptEncodingTests.cpp | 9 ++++ test/unit/ApplicationTaskTests.cpp | 9 ++++ test/unit/ApplicationUrlTests.cpp | 9 ++++ test/unit/AutomationChannelTests.cpp | 9 ++++ test/unit/AutomationDiscoveryTests.cpp | 9 ++++ test/unit/AutomationDistributionGuard.cpp | 10 ++++ test/unit/AutomationMcpHttpTests.cpp | 10 ++++ test/unit/AutomationTests.cpp | 9 ++++ test/unit/BddDiscoveryProbe.cpp | 9 +++- test/unit/BddSelfTest.cpp | 13 ++++- test/unit/BroadcastTests.cpp | 11 ++++- test/unit/CEFMacrosTests.cpp | 10 ++++ test/unit/CEFPathsTests.cpp | 9 ++++ test/unit/CommandsTests.cpp | 9 ++++ test/unit/ContentPolicyTests.cpp | 9 ++++ test/unit/DefaultFSTests.cpp | 9 ++++ test/unit/DeferredCallTests.cpp | 11 ++++- test/unit/DeveloperTests.cpp | 9 ++++ test/unit/DomBatchTests.cpp | 9 ++++ test/unit/DomDocumentTests.cpp | 9 ++++ test/unit/DownloadsTests.cpp | 9 ++++ test/unit/EmbeddedAssetChecks.hpp | 9 ++++ test/unit/EmbeddedCoreAssetsTests.cpp | 9 ++++ test/unit/EncodingsTests.cpp | 9 ++++ test/unit/FileSystemTests.cpp | 9 ++++ test/unit/FormsDeclaration.cpp | 10 ++++ test/unit/FormsHarness.hpp | 10 ++++ test/unit/FormsReflectionRejects.cpp | 10 ++++ test/unit/FormsReflectionTests.cpp | 10 ++++ test/unit/FormsSettings.hpp | 10 ++++ test/unit/FormsTests.cpp | 9 ++++ test/unit/FrameAllocationTest.cpp | 10 ++++ test/unit/FrontendContractTests.cpp | 9 ++++ test/unit/FrontendUrlTests.cpp | 9 ++++ test/unit/GzipCacheBenchmark.cpp | 10 ++++ test/unit/GzipDecoderBenchmark.cpp | 10 ++++ test/unit/GzipExecutorTests.cpp | 9 ++++ test/unit/GzipTests.cpp | 9 ++++ test/unit/HTTPEncodingTests.cpp | 9 ++++ test/unit/HTTPRangeTests.cpp | 12 ++++- test/unit/HTTPRoutesTests.cpp | 12 ++++- test/unit/HTTPServerTests.cpp | 9 ++++ test/unit/HostLoopTests.cpp | 9 ++++ test/unit/HostTests.cpp | 9 ++++ test/unit/IndexFSTests.cpp | 9 ++++ test/unit/InjectableNetworking.hpp | 10 +++- test/unit/InlineTaskScope.hpp | 10 +++- test/unit/JSFunctionTests.cpp | 9 ++++ test/unit/JasmineConsumerTests.cpp | 9 ++++ test/unit/JsFunctionSenderTests.cpp | 9 ++++ test/unit/LifeTests.cpp | 9 ++++ test/unit/LoggerTests.cpp | 9 ++++ test/unit/Main.cpp | 9 +++- test/unit/MddlogHeaderConsumer.cpp | 10 +++- test/unit/MddlogLoggerTests.cpp | 10 +++- test/unit/MddlogTransportTests.cpp | 10 +++- test/unit/MessagesTests.cpp | 9 ++++ test/unit/MimeTypeTests.cpp | 9 ++++ test/unit/Mocks.hpp | 11 +++-- test/unit/ModuleHTTPServerTests.cpp | 9 ++++ test/unit/NativeFSTests.cpp | 9 ++++ test/unit/NativeStorageTests.cpp | 9 ++++ test/unit/NativeWindowTests.cpp | 11 ++++- test/unit/ProfileLeaseTests.cpp | 9 ++++ test/unit/PtyTests.cpp | 9 ++++ test/unit/ReactStoreTests.cpp | 9 ++++ test/unit/ReadBindingTests.cpp | 11 ++++- test/unit/SafePathTests.cpp | 9 ++++ test/unit/ScenarioIsolation.cpp | 13 ++++- test/unit/StdnetShutdownTests.cpp | 9 ++++ test/unit/StorageTests.cpp | 9 ++++ test/unit/StructuredShutdownTests.cpp | 9 ++++ test/unit/TemporaryDirectory.hpp | 9 ++++ test/unit/TlsConstantTime.cpp | 10 +++- test/unit/TlsTests.cpp | 9 ++++ test/unit/TypeErasedFunctionTests.cpp | 9 ++++ test/unit/UIExecutorTests.cpp | 9 ++++ test/unit/UISubscribersTests.cpp | 9 ++++ test/unit/ViewAssociationTests.cpp | 11 ++++- test/unit/WebFrontTests.cpp | 9 ++++ test/unit/WebKitGTKPolicyTests.cpp | 9 ++++ test/unit/WebLinkTests.cpp | 9 ++++ test/unit/WebSocketTests.cpp | 9 ++++ test/unit/WebView2ControllerMock.hpp | 9 ++++ test/unit/WebView2PolicyMocks.hpp | 9 ++++ test/unit/WebView2Tests.cpp | 9 ++++ test/unit/WfDriverTests.cpp | 9 ++++ test/unit/WindowRegistryTests.cpp | 11 ++++- test/web/AutomationHost.cpp | 10 ++++ test/web/CEFContentPolicy.cpp | 9 ++++ test/web/CEFFileServices.cpp | 10 ++++ test/web/DeveloperTest.cpp | 9 ++++ test/web/FrontendLifecycle.cpp | 9 ++++ test/web/JasmineConsumer.cpp | 9 ++++ test/web/JasmineTest.cpp | 10 ++++ test/web/LifeEmbeddedTest.cpp | 9 ++++ test/web/MultiInstance.cpp | 10 ++++ test/web/NativeIntegrationManual.cpp | 10 ++++ test/web/RejectedWebSocketServer.hpp | 9 ++++ test/web/TlsInterop.cpp | 9 ++++ test/web/TransportBenchmark.hpp | 10 ++++ test/web/WKWebViewClassImages.cpp | 9 ++++ test/web/WKWebViewClassModule.cpp | 9 ++++ test/web/WKWebViewHeaderConsumer.cpp | 9 ++++ test/web/WKWebViewLifecycle.cpp | 9 ++++ test/web/WKWebViewTransportBenchmark.cpp | 10 ++++ test/web/WebKitGTKLifecycle.cpp | 9 ++++ test/web/WebKitGTKTransportBenchmark.cpp | 10 ++++ test/web/WebView2HeaderConsumer.cpp | 10 ++++ test/web/WebView2Lifecycle.cpp | 9 ++++ test/web/WebView2TransportBenchmark.cpp | 10 ++++ test/web/host/HostProbe.cpp | 10 ++++ 272 files changed, 2680 insertions(+), 307 deletions(-) diff --git a/cmake/mddlog/Logger.cpp b/cmake/mddlog/Logger.cpp index 96123a70..328fcbe4 100644 --- a/cmake/mddlog/Logger.cpp +++ b/cmake/mddlog/Logger.cpp @@ -1,4 +1,12 @@ -/** @brief WebFront-owned module-consuming TU; the facade header remains independent of modules. */ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-01 +// +// WebFront — build/mddlog +// Role: WebFront-owned module-consuming translation unit implementing the logger facade over mddlog; the facade header stays independent of modules. +// Thread: thread-safe | Alloc: unrestricted +// LLM: compiled only when modules are available; keep module types out of LoggerApi.hpp + import std; import mddlog.core.loglevel; import mddlog.adapter.textlogger; diff --git a/examples/PortOption.hpp b/examples/PortOption.hpp index 13da9498..c9d5ee2a 100644 --- a/examples/PortOption.hpp +++ b/examples/PortOption.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-20 +// +// WebFront — examples +// Role: Handles `--port ` and `--port=` of an example and makes it the default port of the applications that follow. +// Thread: ui-loop | Alloc: heap-init +// LLM: example support; prints the reason and returns false on an invalid value + #pragma once #include diff --git a/examples/hello-world/HelloWorld.cpp b/examples/hello-world/HelloWorld.cpp index aaa55a73..f7801bb9 100644 --- a/examples/hello-world/HelloWorld.cpp +++ b/examples/hello-world/HelloWorld.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2022-02-03 +// +// WebFront — examples +// Role: Minimal example: a C++ callback called from the browser, served by an embedded page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: smallest complete application; the README quick start must stay in step with it + #include // Switching to an embedded Chromium window only changes this alias (CEF must be enabled at diff --git a/examples/host-loop/BoingCuda.cu b/examples/host-loop/BoingCuda.cu index 5eccd5c3..1d53094b 100644 --- a/examples/host-loop/BoingCuda.cu +++ b/examples/host-loop/BoingCuda.cu @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: CUDA unit of the host-loop example: the ray-traced Boing Ball computed on the device. +// Thread: worker-safe | Alloc: unrestricted +// LLM: optional CUDA build; device memory is allocated lazily and freed by cudaRelease + // The CUDA renderer of the Boing Ball: one thread per pixel runs the same pixel() as the CPU renderer. // Compiled by nvcc at C++17; includes no WebFront header. diff --git a/examples/host-loop/BoingCuda.hpp b/examples/host-loop/BoingCuda.hpp index e05e97c4..53c3abe5 100644 --- a/examples/host-loop/BoingCuda.hpp +++ b/examples/host-loop/BoingCuda.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Interface of the optional CUDA unit: device name, whole-image computation, copy back and release. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: functions return nullptr or the reason of a failure; see docs/HOST_LOOP_EXAMPLE.md + #pragma once // The optional CUDA renderer of the Boing Ball (BoingCuda.cu). Its interface is plain C++ so that the unit nvcc diff --git a/examples/host-loop/BoingHost.hpp b/examples/host-loop/BoingHost.hpp index 43d2a53d..a410e934 100644 --- a/examples/host-loop/BoingHost.hpp +++ b/examples/host-loop/BoingHost.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Host of the Boing Ball example: engines, image quality and the frames the host loop produces for the browser. +// Thread: worker-safe | Alloc: unrestricted +// LLM: example of an application keeping its own loop; see docs/HOST_LOOP_EXAMPLE.md + #pragma once // The host application of the example: it owns the scene, its clock, the renderers and its loop. Nothing here knows diff --git a/examples/host-loop/BoingScene.hpp b/examples/host-loop/BoingScene.hpp index fdd2c916..df106492 100644 --- a/examples/host-loop/BoingScene.hpp +++ b/examples/host-loop/BoingScene.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: The animated Boing Ball scene and its CPU ray tracer, a pure function of time. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: deterministic computation; the CUDA unit must produce the same image + #pragma once // The Boing Ball scene: the colour of one pixel as a function of the scene of a frame. The CPU renderer and the CUDA diff --git a/examples/host-loop/HostLoop.cpp b/examples/host-loop/HostLoop.cpp index bf6a7789..4ba6539e 100644 --- a/examples/host-loop/HostLoop.cpp +++ b/examples/host-loop/HostLoop.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-13 +// +// WebFront — examples +// Role: Host-loop example application: runs the Boing Ball beside a native window or a system browser, or as a benchmark. +// Thread: ui-loop | Alloc: unrestricted +// LLM: example entry point; see docs/HOST_INTEGRATION.md for the three integration paths + #include "../PortOption.hpp" #include "HostLoopCapture.hpp" #include "HostLoopUI.hpp" diff --git a/examples/host-loop/HostLoopCapture.hpp b/examples/host-loop/HostLoopCapture.hpp index 21f73f9f..97b95751 100644 --- a/examples/host-loop/HostLoopCapture.hpp +++ b/examples/host-loop/HostLoopCapture.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Bounded capture options of the host-loop example: frame count, file naming and checked writes. +// Thread: worker-safe | Alloc: heap-init +// LLM: example support; at most 600 frames at a fixed 25 fps scene clock + #pragma once #include diff --git a/examples/host-loop/HostLoopUI.hpp b/examples/host-loop/HostLoopUI.hpp index 2c24cd54..1fa88556 100644 --- a/examples/host-loop/HostLoopUI.hpp +++ b/examples/host-loop/HostLoopUI.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: The page of the host-loop example and the callbacks that connect it to the host. +// Thread: bridge-io | Alloc: unrestricted +// LLM: example UI; the host must outlive the application that registers its callbacks + #pragma once // The interface WebFront adds to the host: four callbacks and one page. The callbacks run on WebFront's server thread diff --git a/examples/life/Life.hpp b/examples/life/Life.hpp index 590cfd5e..3a2777ba 100644 --- a/examples/life/Life.hpp +++ b/examples/life/Life.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Game of Life rules shared by the console, developer and embedded stages. +// Thread: worker-safe | Alloc: heap-init +// LLM: pure computation of the walkthrough; no WebFront dependency + #pragma once #include diff --git a/examples/life/LifeConsole.cpp b/examples/life/LifeConsole.cpp index b65a5672..24100c28 100644 --- a/examples/life/LifeConsole.cpp +++ b/examples/life/LifeConsole.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Console stage of the Game of Life walkthrough. +// Thread: ui-loop | Alloc: unrestricted +// LLM: first stage of the README walkthrough + #include "Life.hpp" #include diff --git a/examples/life/LifeDeveloper.cpp b/examples/life/LifeDeveloper.cpp index 36050432..983f9d58 100644 --- a/examples/life/LifeDeveloper.cpp +++ b/examples/life/LifeDeveloper.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Developer stage of the Game of Life walkthrough: the application opens the developer environment on a project. +// Thread: ui-loop | Alloc: unrestricted +// LLM: uses NativeApp::bootstrap("developer"); options live in LifeDeveloperOptions.hpp + #include "../PortOption.hpp" #include "Life.hpp" #include "LifeDeveloperOptions.hpp" diff --git a/examples/life/LifeDeveloperOptions.hpp b/examples/life/LifeDeveloperOptions.hpp index c9af9c9d..33a14865 100644 --- a/examples/life/LifeDeveloperOptions.hpp +++ b/examples/life/LifeDeveloperOptions.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-25 +// +// WebFront — examples +// Role: Command line of WebFrontLifeDeveloper: project directory and optional pinned environment tarball. +// Thread: ui-loop | Alloc: heap-init +// LLM: example support; no argument selects life-project in the current directory + #pragma once #include diff --git a/examples/life/LifeEmbedded.cpp b/examples/life/LifeEmbedded.cpp index 78509786..3bdfb6c1 100644 --- a/examples/life/LifeEmbedded.cpp +++ b/examples/life/LifeEmbedded.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Embedded stage of the Game of Life walkthrough: the compiled UI served from the embedded provider. +// Thread: ui-loop | Alloc: unrestricted +// LLM: final stage of the README walkthrough; the provider is generated by wf embed + #include #include WEBFRONT_LIFE_ASSETS_HEADER #include "../PortOption.hpp" diff --git a/examples/life/LifeFrontend.hpp b/examples/life/LifeFrontend.hpp index 65909e45..7b10764e 100644 --- a/examples/life/LifeFrontend.hpp +++ b/examples/life/LifeFrontend.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-25 +// +// WebFront — examples +// Role: Selects the frontend of the Game of Life examples. +// Thread: ui-loop | Alloc: zero-hot-path +// LLM: alias only; the examples never select CEF + #pragma once #include diff --git a/examples/life/react/LifeReact.cpp b/examples/life/react/LifeReact.cpp index 41377360..8e11417a 100644 --- a/examples/life/react/LifeReact.cpp +++ b/examples/life/react/LifeReact.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-27 +// +// WebFront — examples +// Role: Game of Life variant with a C++ panel inside a React page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: see docs/REACT.md; entry point of the react variant + #include "LifeReact.hpp" #include "../../PortOption.hpp" diff --git a/examples/life/react/LifeReact.hpp b/examples/life/react/LifeReact.hpp index 99fef398..a9946241 100644 --- a/examples/life/react/LifeReact.hpp +++ b/examples/life/react/LifeReact.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-27 +// +// WebFront — examples +// Role: The C++ side of the React variant: per-browser sessions publishing snapshots through a Store. +// Thread: bridge-io | Alloc: unrestricted +// LLM: example of react::Store; one Session per connected browser + #pragma once #include "../Life.hpp" #include diff --git a/examples/pty/main.cpp b/examples/pty/main.cpp index b27495c9..87046dfc 100644 --- a/examples/pty/main.cpp +++ b/examples/pty/main.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — examples +// Role: Standalone PTY example: a native pseudoterminal shown in an xterm.js page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: has its own CMake entry point; see docs/PTY.md + #include #include #ifdef _WIN32 diff --git a/include/webfront/ApplicationOrigin.hpp b/include/webfront/ApplicationOrigin.hpp index 92e02914..03e07eb5 100644 --- a/include/webfront/ApplicationOrigin.hpp +++ b/include/webfront/ApplicationOrigin.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Canonical application authority (host, port, scheme) shared by the HTTP server and the frontend URL builders. +// Thread: worker-safe | Alloc: heap-init +// LLM: pure string helpers; keep in sync with the origin checks of ContentPolicy.hpp + #pragma once #include diff --git a/include/webfront/BridgeError.hpp b/include/webfront/BridgeError.hpp index 45c17c91..f0edbad3 100644 --- a/include/webfront/BridgeError.hpp +++ b/include/webfront/BridgeError.hpp @@ -1,4 +1,12 @@ -/// @brief The failure of a bridge call, with a code that lets the caller tell failures apart. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-05 +// +// WebFront — core +// Role: The failure of a bridge call, with a code that lets the caller tell failures apart. +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API; reserved `webfront.` codes are part of the wire contract with WebFront.js + #pragma once #include diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index ecabf617..52d7ca85 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -1,5 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B -/// @brief A JavaScript function called on every connected browser (BasicWF::broadcast). +// Author: Ambroise Leclerc +// Created: 2026-10-30 +// +// WebFront — core +// Role: A JavaScript function called on every connected browser (BasicWF::broadcast), with an optional per-browser backlog limit. +// Thread: thread-safe | Alloc: unrestricted +// LLM: public API; read BroadcastOptions before the sender implementation + #pragma once #include "http/WebSocket.hpp" #include "weblink/CallFrame.hpp" diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 7d8cfe6e..cb7e63a3 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -1,5 +1,15 @@ -/// @brief Terminal commands of an application: coroutines that the developer environment's terminal discovers and -/// runs, one browser session at a time, streaming their output and cancelled by Ctrl+C, a disconnection or shutdown. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-22 +// +// WebFront — core +// Role: Terminal commands of an application: coroutines the developer environment's terminal discovers and runs, one browser session at a time. +// Thread: bridge-io | Alloc: unrestricted +// LLM: public API; read the command contract and reserved names before the registration code + +// Terminal commands of an application: coroutines that the developer environment's terminal discovers and +// runs, one browser session at a time, streaming their output and cancelled by Ctrl+C, a disconnection or shutdown. + #pragma once #include "networking/Tasks.hpp" diff --git a/include/webfront/ContentPolicy.hpp b/include/webfront/ContentPolicy.hpp index 2ad1aecd..91f42648 100644 --- a/include/webfront/ContentPolicy.hpp +++ b/include/webfront/ContentPolicy.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Shared per-application content rules (origins, popups, navigation) applied by every frontend. +// Thread: worker-safe | Alloc: heap-init +// LLM: public API; see docs/CONTENT_POLICY.md before changing defaults + #pragma once #include diff --git a/include/webfront/DeferredCalls.hpp b/include/webfront/DeferredCalls.hpp index 5ef9a396..e22ded7a 100644 --- a/include/webfront/DeferredCalls.hpp +++ b/include/webfront/DeferredCalls.hpp @@ -1,4 +1,12 @@ -/// @brief The JavaScript calls a C++ callback has not answered yet, per browser connection. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-05 +// +// WebFront — core +// Role: The JavaScript calls a C++ callback has not answered yet, per browser connection. +// Thread: bridge-io | Alloc: unrestricted +// LLM: internal; completion may come from any thread, keep the per-connection ownership rules intact + #pragma once #include "Task.hpp" diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 47db8f09..ad7bea0e 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -1,4 +1,12 @@ -/// @brief Opt-in developer environment (terminal and wf commands) running in the application window. Downloaded code has project/bridge authority. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — core +// Role: Opt-in developer environment (terminal and wf commands) running in the application window. +// Thread: ui-loop | Alloc: heap-init +// LLM: public API; downloaded code has project and bridge authority, read DeveloperBootstrapOptions first + #pragma once #include "system/DeveloperFS.hpp" diff --git a/include/webfront/JsFunction.hpp b/include/webfront/JsFunction.hpp index 7f58e017..865066bd 100644 --- a/include/webfront/JsFunction.hpp +++ b/include/webfront/JsFunction.hpp @@ -1,6 +1,12 @@ -/// @date 04/02/2022 13:15:27 -/// @author Ambroise Leclerc -/// @brief A functor which invokes a corresponding javascript function +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2022-02-04 +// +// WebFront — core +// Role: A functor that invokes a corresponding JavaScript function, fire-and-forget or returning a std::future. +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API; the untyped form is fire-and-forget, the typed form returns a future + #pragma once #include "http/WebSocket.hpp" #include "tooling/HexDump.hpp" diff --git a/include/webfront/JsFunctionSender.hpp b/include/webfront/JsFunctionSender.hpp index bf26acc5..05b83d76 100644 --- a/include/webfront/JsFunctionSender.hpp +++ b/include/webfront/JsFunctionSender.hpp @@ -1,4 +1,12 @@ -/// @brief Lazy, cancellable C++ to browser calls using C++26 sender completions. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Lazy, cancellable C++ to browser calls using C++26 sender completions. +// Thread: worker-safe | Alloc: unrestricted +// LLM: internal; cancellation is local, a late reply is discarded; see docs/ASYNC_EXECUTION.md + #pragma once #include "http/WebSocket.hpp" #include "weblink/CallFrame.hpp" diff --git a/include/webfront/Pty.hpp b/include/webfront/Pty.hpp index 4ee2b3b6..0ac394e2 100644 --- a/include/webfront/Pty.hpp +++ b/include/webfront/Pty.hpp @@ -1,4 +1,12 @@ -/// @brief Optional native pseudoterminal for an application-selected program. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — core +// Role: Optional native pseudoterminal for an application-selected program, with a bounded output ring. +// Thread: worker-safe | Alloc: unrestricted +// LLM: optional component; one worker thread owns the child, see docs/PTY.md + #pragma once #ifdef _WIN32 diff --git a/include/webfront/PtyPage.hpp b/include/webfront/PtyPage.hpp index fbc1a23c..420c4419 100644 --- a/include/webfront/PtyPage.hpp +++ b/include/webfront/PtyPage.hpp @@ -1,4 +1,12 @@ -/// @brief Registers an application-chosen PTY for the optional xterm.js adapter. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — core +// Role: Registers an application-chosen PTY for the optional xterm.js adapter. +// Thread: bridge-io | Alloc: unrestricted +// LLM: optional component; one session per name, retained across page reloads + #pragma once #include "http/Encodings.hpp" diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index e469ff3e..a04ea269 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -1,18 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B -/// @brief Binds the plain HTTP reads of a page (``, `