diff --git a/cmake/RunWebFrontJasmine.cmake b/cmake/RunWebFrontJasmine.cmake index b7dcbfc5..dc802ff7 100644 --- a/cmake/RunWebFrontJasmine.cmake +++ b/cmake/RunWebFrontJasmine.cmake @@ -1,6 +1,14 @@ # CTest owns this process. Its timeout remains outside the browser, even if JS stops responding. file(REMOVE "${DIRECTORY}/report.json") file(REMOVE_RECURSE "${DIRECTORY}/captures") +# The temporary spaces of the specs never survive into the next run, even if the previous one was killed. +file(REMOVE_RECURSE "${DIRECTORY}/temp") +# An inherited grant must never reach a test that has none: an empty value is read as no grant. +set(host_environment "[==[WEBFRONT_JASMINE_HOST=]==]") +if(HOST) + # The owner's native grant (webfront_add_jasmine_test PROGRAMS); without it the application reads no such file. + set(host_environment "[==[WEBFRONT_JASMINE_HOST=${DIRECTORY}/host-${CONFIG}.json]==]") +endif() file(READ "${DIRECTORY}/arguments-${CONFIG}.json" json) string(JSON count LENGTH "${json}") # Bracket arguments are literal: they keep empty strings and semicolons that a list expansion would lose. @@ -27,12 +35,13 @@ if(NOT CMAKE_HOST_WIN32) set(wrapper "[==[sh]==] ${wrapper}") endif() cmake_language(EVAL CODE "execute_process(COMMAND ${wrapper} [==[${CMAKE_COMMAND}]==] -E env - [==[WEBFRONT_JASMINE_CONFIG=${DIRECTORY}/config.json]==] + [==[WEBFRONT_JASMINE_CONFIG=${DIRECTORY}/config.json]==] ${host_environment} [==[XDG_DATA_HOME=${DIRECTORY}/profile/data]==] [==[XDG_CACHE_HOME=${DIRECTORY}/profile/cache]==] [==[WEBFRONT_TEST_CEF_PROFILE=${DIRECTORY}/profile/cef]==] [==[WEBFRONT_TEST_WEBVIEW2_PROFILE=${DIRECTORY}/profile/webview2]==] ${prefix} [==[${PROGRAM}]==]${arguments} RESULT_VARIABLE status TIMEOUT ${backstop})") +file(REMOVE_RECURSE "${DIRECTORY}/temp") if(status MATCHES "timeout" OR status STREQUAL "124") message(FATAL_ERROR "Jasmine application timed out after ${LIMIT} seconds") endif() diff --git a/cmake/WebFrontJasmine.cmake b/cmake/WebFrontJasmine.cmake index 00a431b7..66b015d3 100644 --- a/cmake/WebFrontJasmine.cmake +++ b/cmake/WebFrontJasmine.cmake @@ -21,12 +21,14 @@ function(_webfront_jasmine_quote value output) endfunction() # webfront_add_jasmine_test(NAME name TARGET application SPECS files... [ARGS ...] -# [FRONTEND engine] [TIMEOUT seconds] [JASMINE path/to/jasmine.js]) +# [FRONTEND engine] [TIMEOUT seconds] [JASMINE path/to/jasmine.js] [PROGRAMS programs...]) # TARGET must retain webfront::testing::JasmineTest before show() in its test-enabled build; the helper defines # WEBFRONT_JASMINE_TESTING on it, and without that macro JasmineTest is inert. ARGS reach the application literally, -# as individual arguments (empty ones, semicolons and '$<' included). +# as individual arguments (empty ones, semicolons and '$<' included). PROGRAMS is the owner's native grant: the absolute +# paths (generator expressions such as $ are fine) that the specs may run through webFrontHost.run, +# without a shell. Without it every webFrontHost call rejects. See docs/CONSUMER_TESTING.md. function(webfront_add_jasmine_test) - cmake_parse_arguments(PARSE_ARGV 0 ARG "" "NAME;TARGET;FRONTEND;TIMEOUT;JASMINE" "SPECS;ARGS") + cmake_parse_arguments(PARSE_ARGV 0 ARG "" "NAME;TARGET;FRONTEND;TIMEOUT;JASMINE" "SPECS;ARGS;PROGRAMS") if(ARG_UNPARSED_ARGUMENTS OR ARG_KEYWORDS_MISSING_VALUES OR NOT ARG_NAME OR NOT ARG_TARGET OR NOT ARG_SPECS) message(FATAL_ERROR "webfront_add_jasmine_test requires NAME, TARGET, SPECS and valid named arguments") endif() @@ -116,7 +118,7 @@ function(webfront_add_jasmine_test) if(argument STREQUAL "ARGS") set(in_args ON) continue() - elseif(argument MATCHES "^(NAME|TARGET|FRONTEND|TIMEOUT|JASMINE|SPECS)$") + elseif(argument MATCHES "^(NAME|TARGET|FRONTEND|TIMEOUT|JASMINE|SPECS|PROGRAMS)$") set(in_args OFF) endif() if(NOT in_args) @@ -132,6 +134,24 @@ function(webfront_add_jasmine_test) math(EXPR index "${index} + 1") endforeach() file(GENERATE OUTPUT "${directory}/arguments-$.json" CONTENT "${arguments}\n") + set(host OFF) + if(ARG_PROGRAMS) + set(host ON) + set(programs "[]") + set(index 0) + foreach(program IN LISTS ARG_PROGRAMS) + if(NOT program MATCHES "^(\\$<|/|[A-Za-z]:[/\\\\])") + message(FATAL_ERROR "A Jasmine PROGRAMS entry must be an absolute path or a generator expression: ${program}") + endif() + _webfront_jasmine_quote("${program}" quoted) + string(JSON programs SET "${programs}" ${index} "${quoted}") + math(EXPR index "${index} + 1") + endforeach() + _webfront_jasmine_quote("${directory}/temp" temporary) + # Generated, not written at configure time: the programs are usually $ of the build. + file(GENERATE OUTPUT "${directory}/host-$.json" + CONTENT "{\"programs\":${programs},\"temporary\":${temporary}}\n") + endif() set(prefix "") if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND ARG_FRONTEND) find_program(_webfront_jasmine_xvfb xvfb-run REQUIRED) @@ -140,7 +160,7 @@ function(webfront_add_jasmine_test) target_compile_definitions("${ARG_TARGET}" PRIVATE WEBFRONT_JASMINE_TESTING=1) add_test(NAME "${ARG_NAME}" COMMAND "${CMAKE_COMMAND}" "-DPROGRAM=$" "-DDIRECTORY=${directory}" "-DCONFIG=$" - "-DPREFIX=${prefix}" "-DLIMIT=${ARG_TIMEOUT}" + "-DPREFIX=${prefix}" "-DLIMIT=${ARG_TIMEOUT}" "-DHOST=${host}" -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/RunWebFrontJasmine.cmake") math(EXPR outer_timeout "${ARG_TIMEOUT} + 15") set_tests_properties("${ARG_NAME}" PROPERTIES TIMEOUT "${outer_timeout}" LABELS "web-integration") diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e56ba834..05be7a82 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Run authorized native programs from the specs of `webfront_add_jasmine_test` (#445): `PROGRAMS` is the owner's grant and + `webFrontHost.run({program, args, cwd, env, inheritEnv, timeoutMs, maxOutputBytes, signal})` starts a listed program + directly, without a shell, with literal arguments, an explicit environment, bounded time and output, and a structured result + (`exited`, `signaled`, `timeout`, `cancelled`, `launchFailed`, stdout/stderr and truncation flags). The program and its + process group (POSIX) or job object (Windows) are killed at the timeout, on cancellation and when the program ends. + `makeTemp`/`withTemp`, `writeFile` and `readFile` give private temporary spaces that are removed after success, failure and + cancellation. Without `PROGRAMS` every call rejects; `webfront::testing::runProcess` and `HostSession` are the C++ API. The wf + scripts keep no process capability. The browser specs are validated on Linux; Windows and macOS run the unit tests of the runner in CI. See `docs/CONSUMER_TESTING.md` for + the XML-to-JSON recipe. + - Automation can set a project up end to end (#466): `init`, `create`, `install`, `restore` and `embed` join the contract of `webfront-agent`, each behind its own `--allow` grant and with plain-name or project-relative arguments (no options, no traversal). `install` takes one package from the configured registry or installs the locked graph; `embed` takes a manifest diff --git a/docs/CONSUMER_TESTING.md b/docs/CONSUMER_TESTING.md index 194252fd..cbf1abce 100644 --- a/docs/CONSUMER_TESTING.md +++ b/docs/CONSUMER_TESTING.md @@ -84,6 +84,117 @@ by numeric index, in bounded chunks, to the newest instrumented connection: a pa or redirects is instrumented again and the earlier connection loses access. One window is supported. No runtime path supplied by a page is opened. Use an isolated CI environment for untrusted projects and remove secrets. +## Native programs and temporary files from the specs + +A consumer's own tools and CLI tests (SiliconForge's `atdf2json`, a test that runs its `siliconforge` binary on a generated +description) need two things the browser lacks: running a program and a private place to write files. They are an explicit +**grant of the test's owner** (`PROGRAMS` in `webfront_add_jasmine_test`), never something a spec, a page or a manifest can ask +for: + +```cmake +webfront_add_jasmine_test(NAME McuTools TARGET SiliconForge + SPECS tests/ui/mcu-tools.spec.js + PROGRAMS "$") # absolute paths or generator expressions +``` + +Without `PROGRAMS` every `webFrontHost` call rejects with "No native capability was granted", and a program that is not listed +is refused with "not authorized": the path in the call must designate the same file as a listed one (a relative name, a shell +or another binary never matches). Existing tests and applications keep their behaviour; a build without +`WEBFRONT_JASMINE_TESTING` has no such code path. + +```js +const [siliconforge] = await webFrontHost.programs(); // the authorized paths, in the order of PROGRAMS +await webFrontHost.withTemp(async dir => { // a new private directory, removed afterwards + await webFrontHost.writeFile(`${dir}/chip.json`, JSON.stringify(description)); + const help = await webFrontHost.run({program: siliconforge, args: ['--mcu-path', dir, '--help']}); + expect(help.status).toBe('exited'); // exited | signaled | timeout | cancelled | launchFailed + expect(help.exitCode).toBe(0); + expect(help.stdout).toContain('atmega328p'); + const bad = await webFrontHost.run({program: siliconforge, args: ['--mcu-file', `${dir}/chip.json`, 'blink.hex'], + cwd: dir, timeoutMs: 20000}); + expect(bad.exitCode).toBe(1); + expect(bad.stderr).toContain('interrupts[2]'); +}); +``` + +| Call | Meaning | +| --- | --- | +| `run({program, args, cwd, env, inheritEnv, timeoutMs, maxOutputBytes, signal})` | Runs the program to its end and resolves with `{status, exitCode, signal, error, stdout, stderr, stdoutTruncated, stderrTruncated, durationMs}`. Unknown options are an error. `signal` is an `AbortSignal`. | +| `programs()` | The authorized program paths. | +| `makeTemp()`, `removeTemp(dir)`, `withTemp(async dir => ...)` | Private directories under the test's `webfront-jasmine//temp/`. | +| `writeFile(path, textOrBytes)`, `readFile(path)`, `readText(path)` | Files inside those directories only (bytes cross the bridge in 48 KiB chunks; 64 MiB at most, for writing and for reading). | + +What is guaranteed, and what is not: + +- **No shell, literal arguments.** The program is started directly with `args` as its `argv`: spaces, quotes, Unicode, `` ;|&$\` `` and + empty strings arrive unchanged (Windows applies the standard `CommandLineToArgvW` quoting). Its standard input is closed. + Paths may contain spaces and Unicode; the program path is the owner's, not the spec's spelling. +- **Signals.** The program starts with default signal dispositions and an empty signal mask (POSIX), whatever the application + ignores or handles. +- **Environment policy.** By default the program sees **only** `env` (plus `SystemRoot` on Windows, which programs there need to + start); `inheritEnv: true` adds the test process's environment under it. Neither changes `TMPDIR`: pass the variables you + want, for example the directory from `makeTemp()`. +- **Working directory.** `cwd` must be inside a temporary space; the default is the test process's directory. +- **Results.** A non-zero exit, a signal (POSIX), a timeout (`timeoutMs`, 30 s by default, 1 ms to 1 h), a cancellation and a program + that cannot start (`launchFailed`, with `error`) are results, not exceptions: assert on them. A refused request (unauthorized + program, bad option, path outside the spaces, too many runs) rejects the Promise. +- **Bounded output.** Each stream keeps its first `maxOutputBytes` (1 MiB by default, 16 MiB at most); the rest is read and + discarded, so a noisy program is never blocked, and `stdoutTruncated`/`stderrTruncated` say so. At most 8 runs are active. + Standard output and error are decoded as UTF-8. +- **Descendants.** On a timeout or cancellation the program **and everything it started in its process group** (POSIX) or job + object (Windows) is killed; the same happens when the program ends by itself with a descendant still running, so nothing a + call started outlives it. A descendant that left the group (`setsid`, a daemon) or escaped the job is not tracked on POSIX; its + inherited pipes are given one second after the program ended, then abandoned. +- **Cleanup.** A temporary space is removed by `withTemp`, by `removeTemp`, when the test process ends normally (also after a + failed or cancelled spec), and the runner deletes `temp/` before and after each run, so an earlier run killed by the deadline + leaves nothing behind for the next. Spaces have unique random names, so concurrent runs and sessions never share one. A + `SIGKILL` of the test process, a power loss or a Windows file still locked by a program leave files in the build tree until + the next run of the same named test (the runner's deletion) or `ctest` cleanup of the build directory. +- **If the test process is killed.** On Linux the program asks the kernel to kill it when the test process dies, so a CTest + deadline (SIGKILL, no destructor) ends the program too; its descendants that were still in its group are not tracked + after that. Other POSIX systems and Windows (the job object closes with the process) are not covered by a test, and macOS has + no equivalent of this request: a program may outlive a killed test there. +- **Removal failures.** `removeTemp` (and `withTemp`) reject when a space cannot be removed, for example a file still in use; + the space stays registered and the session tries again when it ends, then reports the path on stderr. An authorized program + that does not exist (not built yet) is a `launchFailed` result, not an authorization error. +- **Privacy.** The temporary root and its spaces are closed to other users (mode 0700) on POSIX; on Windows they inherit + the build directory's ACL. +- **Status lost.** If the application ignores `SIGCHLD`, the system discards exit statuses: the call still ends at the + timeout, reporting `exited` with an `error` and exit code -1, never a success. +- **Failure.** A spec assertion that is false, a refused or unauthorized call that is not caught, and a program that timed out + or could not start when the spec expects success all fail the test, and so CTest and CI (exit status of the runner). + +This is an authorization, **not a sandbox**: an authorized program runs with the user's authority and sees the filesystem and +the network; the specs and the page are trusted code, as everywhere in this guide. The temporary-space check resolves symbolic +links, but a program can still be told any path it can reach. Treat the grant like handing the test your shell for that one +binary, and use an isolated CI environment without secrets for untrusted projects. The wf scripts of the developer environment +(`wf run`, `wf exec`) still run in a browser Worker with no process capability, and the manifest's permissions cannot add one +(see [the developer environment](DEVELOPER_ENVIRONMENT.md#scripts-wf-run-wf-exec)); a tool that must execute a program is a +spec of this path. + +### Recipe: XML (ATDF) to JSON, then the native tool + +[`test/web/jasmine-consumer/host.spec.js`](../test/web/jasmine-consumer/host.spec.js) holds a complete example run by CTest +(`ConsumerJasmine-host`): it fetches the fixture `atdf-mini.xml` from the document root, converts it with `DOMParser`, +writes the JSON to a private space and runs a native program on it, asserting its output and a failing exit code with its +stderr. `DOMParser` exists in the page the specs run in, unlike the wf Worker; a converter that must run in the Worker needs a +pure-JavaScript XML parser installed with `wf install` from the registry and locked, and cannot start the native tool. To +build the converter as a distributed tool, keep it a TypeScript module compiled by `wf build` and import it from the spec; a +native window is still required to run it. + +To run it in a consumer project: add `PROGRAMS "$"` to the helper call, compile the TS specs to classic +JavaScript beforehand (this path does not compile TypeScript), keep the fixtures next to the spec and read them with `fetch` +from the application's document root. Provisioning is the one configure-time download of the pinned `jasmine-core` (or +`WEBFRONT_JASMINE_ARCHIVE_DIR` offline); the run needs no Node.js, Python or network. Measured on Linux with CEF (Release, this +repository): the twelve specs of `ConsumerJasmine-host` took 5.6 s in total, of which 3.0 s is the deliberate wait proving a +killed descendant stays dead and about 1.3 s the start of the window, which a passing one-spec test also pays. + +Platforms: the browser specs (`ConsumerJasmine-host*`) run on **Linux** (CEF, `xvfb-run`). The process runner and the temporary +spaces (`Process.hpp`, `Host.hpp`) are also compiled and tested by the unit tests (`HostTests.cpp`) in CI on **macOS** +(`posix_spawn`, process group; the descriptor-closing action is glibc-only, so other descriptors rely on `FD_CLOEXEC`) and +**Windows** (`CreateProcessW`, job object, restricted handle inheritance, overlapped pipes). The browser specs have not been +run on those systems: treat the whole path there as unqualified until they are. + ## Screenshots and image sequences A test build can capture the **web content** of the window (without native decorations) as PNG images, for example to diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 472be154..69d43e86 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -308,7 +308,9 @@ A `context` operation outside the permissions rejects with an explicit error. Th API**: the Worker keeps its own capabilities (global `fetch`, `importScripts`, WebSocket...), and nothing here is a security boundary. Node.js modules (`fs`, `child_process`, `node:*`...) are refused while the script is loaded, unless a locked package of that name is a dependency of the importer; `process` does not exist and no polyfill is -provided. +provided. A script cannot run a native program, and no manifest permission can grant that: a test or tool that must run a +program (a CLI under test, a converter's output checked by the binary that reads it) is a spec of the consumer Jasmine path, +where the test's owner authorizes the program ([native programs and temporary files](CONSUMER_TESTING.md#native-programs-and-temporary-files-from-the-specs)). Ctrl+C first aborts `context.signal`; a script still running two seconds later (the grace period) is terminated with `worker.terminate()`, which also stops a loop that never returns to the event loop. The time limit (`--timeout`, diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 703c1f9e..a9e0516d 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -46,7 +46,9 @@ Consumers can explicitly instrument their real application page with `webfront::testing::JasmineTest` and register it through `webfront_add_jasmine_test`. This optional [Jasmine/CTest path](CONSUMER_TESTING.md) supports precompiled classic JavaScript specs and external process deadlines; it does not compile TS or isolate untrusted application code. It can also -write PNG screenshots and image sequences of the web content on WebKitGTK, WKWebView, WebView2 and CEF (#468). +write PNG screenshots and image sequences of the web content on WebKitGTK, WKWebView, WebView2 and CEF (#468), and let the +specs run programs the test's owner authorizes (`PROGRAMS`), with private temporary spaces (#445); its browser specs run on +Linux only (the runner's unit tests also run on Windows and macOS). The CEF-off build and complete CTest commands are in [AGENTS.md](../AGENTS.md). The suite includes deterministic Catch2 regressions, CMake consumer/configuration checks, diff --git a/include/webfront/testing/Capture.hpp b/include/webfront/testing/Capture.hpp index 060f3a4b..37a48510 100644 --- a/include/webfront/testing/Capture.hpp +++ b/include/webfront/testing/Capture.hpp @@ -42,7 +42,7 @@ class CaptureStore { return frontend::capturePng(timeout); }, std::size_t maxImages = maxFrames) - : shared(std::make_shared(std::move(root), std::move(source), maxImages)) { } + : shared(std::make_shared(std::move(root), std::move(source), maxImages)) {} CaptureStore(const CaptureStore&) = delete; CaptureStore& operator=(const CaptureStore&) = delete; @@ -181,8 +181,7 @@ class CaptureStore { private: struct Shared { - Shared(std::filesystem::path root, Source source, std::size_t maxImages) - : directory(std::move(root)), capture(std::move(source)), limit(maxImages) { } + Shared(std::filesystem::path root, Source source, std::size_t maxImages) : directory(std::move(root)), capture(std::move(source)), limit(maxImages) {} std::filesystem::path directory; Source capture; std::size_t limit; diff --git a/include/webfront/testing/Host.hpp b/include/webfront/testing/Host.hpp new file mode 100644 index 00000000..533c7890 --- /dev/null +++ b/include/webfront/testing/Host.hpp @@ -0,0 +1,446 @@ +/// @brief Native capabilities granted by a test's owner to its specs: authorized programs and private temporary spaces. +#pragma once + +#include "../utils/Json.hpp" +#include "Process.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::testing { + +namespace detail { + +/// What the owner of the test (its CMake file, through an environment variable the runner sets) grants the specs. +struct HostConfiguration { + std::vector programs; ///< Absolute paths of the only programs the specs may run. + std::filesystem::path temporary; ///< Directory holding every temporary space of this run. +}; + +inline std::filesystem::path pathFromUtf8(const std::string& text) { + return std::filesystem::path(std::u8string(text.begin(), text.end())); +} + +inline std::string utf8(const std::filesystem::path& path) { + const auto text = path.u8string(); + return {text.begin(), text.end()}; +} + +inline HostConfiguration hostConfiguration(std::string_view text) { + HostConfiguration config; + json::Reader reader{text}; + bool programs = false, temporary = false; + reader.object([&](const std::string& key) { + if (key == "programs" && !std::exchange(programs, true)) + reader.array([&] { + if (config.programs.size() >= 64) + throw std::invalid_argument("At most 64 programs can be authorized"); + auto path = pathFromUtf8(reader.string()); + if (!path.is_absolute()) + throw std::invalid_argument("An authorized program must be an absolute path"); + config.programs.push_back(std::move(path)); + }); + else if (key == "temporary" && !std::exchange(temporary, true)) + config.temporary = pathFromUtf8(reader.string()); + else + throw std::invalid_argument("Unknown or duplicate host configuration field"); + }); + reader.end(); + if (!config.temporary.is_absolute()) + throw std::invalid_argument("The host configuration needs an absolute temporary directory"); + return config; +} + +/// One request from a spec, after validation. +struct HostRunRequest { + std::filesystem::path program; + ProcessSpec spec; +}; + +inline double jsonNumber(json::Reader& reader) { + const auto token = reader.rawValue(); + double value = 0; + const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value); + if (error != std::errc{} || end != token.data() + token.size() || !std::isfinite(value)) + throw std::invalid_argument("A number was expected"); + return value; +} + +inline bool jsonBoolean(json::Reader& reader) { + const auto token = reader.rawValue(); + if (token == "true") + return true; + if (token == "false") + return false; + throw std::invalid_argument("A boolean was expected"); +} + +} // namespace detail + +/** + * @brief The native side of `webFrontHost`: runs only the programs its owner authorized and confines files to temporary + * spaces it created. This is an explicit grant, not a sandbox: an authorized program runs with the user's authority. + * Thread-safe. Destruction cancels and joins every run, then removes every temporary space. + */ +class HostSession { +public: + static constexpr std::size_t chunkSize = 49152; + static constexpr std::size_t maxActiveRuns = 8; + static constexpr std::size_t maxRetainedRuns = 64; + static constexpr std::size_t maxArguments = 256; + static constexpr std::size_t maxOutputLimit = 16 * 1024 * 1024; + static constexpr std::size_t maxFileBytes = 64 * 1024 * 1024; + static constexpr std::chrono::milliseconds maxTimeout{3600 * 1000}; + + explicit HostSession(detail::HostConfiguration configuration) : config(std::move(configuration)) { + std::error_code error; + std::filesystem::create_directories(config.temporary, error); + if (error) + throw std::runtime_error("Cannot create the temporary directory: " + error.message()); + config.temporary = std::filesystem::weakly_canonical(config.temporary); + // Private to this user (POSIX): every space below inherits the closed doorway, whatever the umask. + std::filesystem::permissions(config.temporary, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, error); + } + HostSession(const HostSession&) = delete; + HostSession& operator=(const HostSession&) = delete; + + ~HostSession() { + std::map> remaining; + { + std::scoped_lock lock{mutex}; + remaining.swap(runs); + } + for (auto& [id, run] : remaining) + run->cancel = true; + for (auto& [id, run] : remaining) + if (run->worker.joinable()) + run->worker.join(); + std::set leftover; + { + std::scoped_lock lock{mutex}; + leftover.swap(spaces); + } + for (const auto& space : leftover) + if (!removeTree(space)) + std::cerr << "Jasmine: cannot remove the temporary space " << space.string() << '\n'; + } + + /// The authorized programs, as a JSON array of strings. + [[nodiscard]] std::string programs() const { + std::string text = "["; + for (const auto& program : config.programs) { + if (text.size() > 1) + text += ','; + text += json::quote(detail::utf8(program)); + } + return text + "]"; + } + + /// Creates a new empty directory, private to this run, and returns its absolute path. + [[nodiscard]] std::string makeTemp() { + static std::atomic counter{0}; + std::random_device entropy; + for (int attempt = 0; attempt < 16; ++attempt) { + char name[64]; + std::snprintf(name, sizeof name, "t%08x%08x-%llu", entropy(), entropy(), static_cast(counter++)); + const auto path = config.temporary / name; + std::error_code error; + if (std::filesystem::create_directory(path, error)) { + std::filesystem::permissions(path, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, error); + std::scoped_lock lock{mutex}; + if (spaces.size() >= 256) { + std::filesystem::remove(path, error); + throw std::runtime_error("Too many temporary spaces"); + } + spaces.insert(path); + return detail::utf8(path); + } + if (error) + throw std::runtime_error("Cannot create a temporary space: " + error.message()); + } + throw std::runtime_error("Cannot find a free temporary space name"); + } + + /// Removes a space made by makeTemp() and everything in it. + void removeTemp(const std::string& path) { + const auto space = detail::pathFromUtf8(path); + { + std::scoped_lock lock{mutex}; + if (!spaces.contains(space)) + throw std::invalid_argument("Not a temporary space of this run"); + } + // The space stays registered when it cannot be removed, so that the caller sees the failure and the session + // retries when it ends. + if (!removeTree(space)) + throw std::runtime_error("Cannot remove the temporary space (a file may still be in use): " + path); + std::scoped_lock lock{mutex}; + spaces.erase(space); + } + + /// Writes bytes at `offset` of a file inside a temporary space. Offset 0 truncates; later chunks must continue the file. + void writeFile(const std::string& path, double offset, const std::vector& bytes) { + const auto file = contained(path); + if (!std::isfinite(offset) || offset < 0 || std::floor(offset) != offset + || offset + static_cast(bytes.size()) > static_cast(maxFileBytes)) + throw std::invalid_argument("Invalid file offset"); + const auto start = static_cast(offset); + std::error_code error; + if (start != 0 && (!std::filesystem::is_regular_file(file, error) || std::filesystem::file_size(file, error) != start)) + throw std::invalid_argument("A chunk must continue the file"); + std::ofstream out(file, start == 0 ? std::ios::binary | std::ios::trunc : std::ios::binary | std::ios::app); + out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + out.close(); + if (!out) + throw std::runtime_error("Cannot write the file"); + } + + /// Reads at most one chunk at `offset`; a short (or empty) result is the end of the file. + [[nodiscard]] std::vector readFile(const std::string& path, double offset) { + const auto file = contained(path); + std::error_code sizeError; + if (const auto size = std::filesystem::file_size(file, sizeError); !sizeError && size > maxFileBytes) + throw std::invalid_argument("The file exceeds the 64 MiB limit"); + std::ifstream in(file, std::ios::binary); + if (!in) + throw std::runtime_error("Cannot read the file"); + if (!std::isfinite(offset) || offset < 0 || std::floor(offset) != offset) + throw std::invalid_argument("Invalid file offset"); + in.seekg(static_cast(offset)); + std::vector bytes(chunkSize); + in.read(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + bytes.resize(static_cast(in.gcount())); + return bytes; + } + + /// Validates the request, refuses an unauthorized program, and starts the run on its own thread. + /// Throws for anything refused; otherwise returns the run's id. + [[nodiscard]] double runStart(const std::string& request) { + auto parsed = parse(request); + std::scoped_lock lock{mutex}; + std::size_t active = 0; + for (const auto& [id, run] : runs) + if (!run->finished) + ++active; + if (active >= maxActiveRuns || runs.size() >= maxRetainedRuns) + throw std::runtime_error("Too many runs: collect and release the finished ones"); + auto run = std::make_shared(); + run->id = ++lastId; + run->spec = std::move(parsed.spec); + // A raw pointer would dangle once the session is destroyed: the thread owns a reference. + run->worker = std::thread([run] { + ProcessResult outcome; + try { + outcome = runProcess(run->spec, run->cancel); + } catch (const std::exception& error) { + outcome.error = error.what(); + } + std::scoped_lock done{run->mutex}; + run->result = std::move(outcome); + run->finished = true; + }); + runs.emplace(run->id, run); + return run->id; + } + + /// The run's summary as JSON once it ended, or nothing while it is still running. + [[nodiscard]] std::optional runPoll(double id) { + const auto run = find(id); + std::scoped_lock lock{run->mutex}; + if (!run->finished) + return std::nullopt; + const auto& r = run->result; + std::string text = "{\"status\":" + json::quote(processStatusName(r.status)); + text += ",\"exitCode\":" + std::to_string(r.exitCode) + ",\"signal\":" + std::to_string(r.signal); + text += ",\"error\":" + json::quote(r.error.substr(0, 1024)); + text += ",\"stdoutBytes\":" + std::to_string(r.standardOutput.size()) + ",\"stderrBytes\":" + std::to_string(r.standardError.size()); + text += std::string(",\"stdoutTruncated\":") + (r.outputTruncated ? "true" : "false"); + text += std::string(",\"stderrTruncated\":") + (r.errorTruncated ? "true" : "false"); + text += ",\"durationMs\":" + std::to_string(r.duration.count()) + "}"; + return text; + } + + /// One chunk of a finished run's captured output: stream 1 is standard output, 2 standard error. + [[nodiscard]] std::vector runRead(double id, double stream, double offset) { + const auto run = find(id); + std::scoped_lock lock{run->mutex}; + if (!run->finished) + throw std::logic_error("The run has not ended"); + if (stream != 1 && stream != 2) + throw std::invalid_argument("Invalid stream"); + const auto& text = stream == 1 ? run->result.standardOutput : run->result.standardError; + if (!std::isfinite(offset) || offset < 0 || std::floor(offset) != offset || offset > static_cast(text.size())) + throw std::invalid_argument("Invalid output offset"); + const auto part = std::string_view(text).substr(static_cast(offset), chunkSize); + return {part.begin(), part.end()}; + } + + /// Asks a running program to stop; its kill is prompt and its result says `cancelled`. + void runCancel(double id) { + find(id)->cancel = true; + } + + /// Frees a run's result (cancelling it first if it still runs). + void runRelease(double id) { + std::shared_ptr run; + { + std::scoped_lock lock{mutex}; + const auto found = runs.find(id); + if (found == runs.end()) + throw std::invalid_argument("Unknown run"); + run = found->second; + runs.erase(found); + } + run->cancel = true; + if (run->worker.joinable()) + run->worker.join(); + } + +private: + struct Run { + double id = 0; + ProcessSpec spec; + std::atomic cancel{false}; + std::mutex mutex; + std::atomic finished{false}; + ProcessResult result; + std::thread worker; + }; + + detail::HostRunRequest parse(const std::string& request) { + detail::HostRunRequest parsed; + parsed.spec.timeout = std::chrono::milliseconds{30000}; + std::string program, directory; + double timeout = 30000, output = 1024 * 1024; + bool seenProgram = false; + json::Reader reader{request}; + reader.object([&](const std::string& key) { + if (key == "program") { + program = reader.string(); + seenProgram = true; + } else if (key == "args") + reader.array([&] { + if (parsed.spec.arguments.size() >= maxArguments) + throw std::invalid_argument("Too many arguments"); + parsed.spec.arguments.push_back(reader.string()); + }); + else if (key == "cwd") + directory = reader.string(); + else if (key == "env") + reader.object([&](const std::string& name) { + parsed.spec.environment[name] = reader.string(); + }); + else if (key == "inheritEnv") + parsed.spec.inheritEnvironment = detail::jsonBoolean(reader); + else if (key == "timeoutMs") + timeout = detail::jsonNumber(reader); + else if (key == "maxOutputBytes") + output = detail::jsonNumber(reader); + else + throw std::invalid_argument("Unknown run option: " + key); + }); + reader.end(); + if (!seenProgram) + throw std::invalid_argument("A program is required"); + if (!(timeout >= 1 && timeout <= static_cast(maxTimeout.count())) || std::floor(timeout) != timeout) + throw std::invalid_argument("timeoutMs must be a whole number from 1 to 3600000"); + if (!(output >= 1 && output <= static_cast(maxOutputLimit)) || std::floor(output) != output) + throw std::invalid_argument("maxOutputBytes must be a whole number from 1 to 16777216"); + parsed.spec.timeout = std::chrono::milliseconds{static_cast(timeout)}; + parsed.spec.maxOutputBytes = static_cast(output); + + // Only the owner's list decides; the program that starts is the owner's path, not the spec's spelling. + const auto requested = detail::pathFromUtf8(program); + parsed.spec.program.clear(); + for (const auto& allowed : config.programs) { + if (requested.is_absolute() && sameFile(allowed, requested)) { + parsed.spec.program = allowed; + break; + } + } + if (parsed.spec.program.empty()) + throw std::runtime_error("Program not authorized: " + program); + if (!directory.empty()) + parsed.spec.workingDirectory = contained(directory, true); + detail::validateProcessSpec(parsed.spec); // Refused here, before any run exists. + return parsed; + } + + /// The path, if it lies inside a temporary space of this run (symbolic links resolved). + std::filesystem::path contained(const std::string& path, bool allowSpace = false) { + const auto requested = detail::pathFromUtf8(path); + if (!requested.is_absolute()) + throw std::invalid_argument("A temporary path must be absolute"); + std::error_code error; + const auto resolved = std::filesystem::weakly_canonical(requested, error); + if (error) + throw std::invalid_argument("Invalid path: " + error.message()); + std::scoped_lock lock{mutex}; + for (const auto& space : spaces) { + const auto [spaceEnd, resolvedEnd] = std::mismatch(space.begin(), space.end(), resolved.begin(), resolved.end()); + if (spaceEnd == space.end() && (allowSpace || resolvedEnd != resolved.end())) + return resolved; // Inside; the space itself is a directory, not a file. + } + throw std::invalid_argument("The path is outside the temporary spaces of this run"); + } + + std::shared_ptr find(double id) { + std::scoped_lock lock{mutex}; + const auto found = runs.find(id); + if (found == runs.end()) + throw std::invalid_argument("Unknown run"); + return found->second; + } + + /// The same file, or, when one of them is absent (a program not built or installed), the same location: an authorized + /// program that is missing must be reported as one that cannot start, not as unauthorized. + static bool sameFile(const std::filesystem::path& allowed, const std::filesystem::path& requested) { + std::error_code error; + if (std::filesystem::equivalent(allowed, requested, error) && !error) + return true; + if (!error) + return false; // Both exist and differ. + const auto first = std::filesystem::weakly_canonical(allowed, error); + const auto second = error ? first : std::filesystem::weakly_canonical(requested, error); + return !error && first == second; + } + + /// Windows may hold a file a moment after its process ended. False if the space is still there afterwards. + static bool removeTree(const std::filesystem::path& path) noexcept { + for (int attempt = 0; attempt < 20; ++attempt) { + std::error_code error; + std::filesystem::remove_all(path, error); + if (!error && !std::filesystem::exists(path, error)) + return true; + std::this_thread::sleep_for(std::chrono::milliseconds{50}); + } + return false; + } + + detail::HostConfiguration config; + std::mutex mutex; + std::set spaces; + std::map> runs; + double lastId = 0; +}; + +} // namespace webfront::testing diff --git a/include/webfront/testing/Jasmine.hpp b/include/webfront/testing/Jasmine.hpp index a4e95451..c5c027c9 100644 --- a/include/webfront/testing/Jasmine.hpp +++ b/include/webfront/testing/Jasmine.hpp @@ -4,6 +4,7 @@ #include "../utils/Json.hpp" #include "../WebFront.hpp" #include "Capture.hpp" +#include "Host.hpp" #include #include @@ -72,22 +73,27 @@ inline JasmineConfiguration jasmineConfiguration(std::string_view text) { return config; } -inline std::optional jasmineConfigurationPath() { +/// The value of an environment variable the test runner sets, if it is set and not empty. +inline std::optional jasmineEnvironment(const char* name) { #ifdef _MSC_VER char* raw = nullptr; std::size_t size = 0; - if (_dupenv_s(&raw, &size, "WEBFRONT_JASMINE_CONFIG") != 0) - throw std::runtime_error("Cannot read WEBFRONT_JASMINE_CONFIG"); + if (_dupenv_s(&raw, &size, name) != 0) + throw std::runtime_error(std::string("Cannot read ") + name); std::unique_ptr owned(raw, std::free); if (raw && *raw) return std::string(raw); #else - if (const auto* raw = std::getenv("WEBFRONT_JASMINE_CONFIG"); raw && *raw) + if (const auto* raw = std::getenv(name); raw && *raw) return std::string(raw); #endif return std::nullopt; } +inline std::optional jasmineConfigurationPath() { + return jasmineEnvironment("WEBFRONT_JASMINE_CONFIG"); +} + /// Bytes per bridge read, shared by the page script (injected as CHUNK) and JasmineSession::read. inline constexpr std::size_t jasmineChunkSize = 49152; @@ -114,6 +120,67 @@ void (async () => { return stopRecording(); }; globalThis.webFrontCapture = {screenshot, startRecording, stopRecording, record}; + // Native capabilities the test's owner granted (PROGRAMS in webfront_add_jasmine_test): authorized programs run without a + // shell, and private temporary spaces. Without a grant every call rejects. Bytes cross the bridge in bounded chunks. + const hostChunk = CHUNK, HOST_FILE_LIMIT = 64 * 1024 * 1024; + const bytesOf = data => typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data); + const readAll = async fetchChunk => { + const parts = []; + for (let offset = 0; ; ) { + const part = await fetchChunk(offset); + parts.push(part); + offset += part.length; + if (offset > HOST_FILE_LIMIT) throw new RangeError('A file or output exceeds the 64 MiB limit'); + if (part.length < hostChunk) break; + } + return new Blob(parts).arrayBuffer().then(buffer => new Uint8Array(buffer)); + }; + const host = { + programs: async () => JSON.parse(await call('hostPrograms')), + makeTemp: () => call('hostMakeTemp'), + removeTemp: path => call('hostRemoveTemp', path), + withTemp: async body => { + const path = await call('hostMakeTemp'); + try { return await body(path); } + finally { await call('hostRemoveTemp', path); } + }, + writeFile: async (path, data) => { + const bytes = bytesOf(data); + await call('hostWrite', path, 0, bytes.subarray(0, 0)); + for (let offset = 0; offset < bytes.length; offset += hostChunk) + await call('hostWrite', path, offset, bytes.subarray(offset, offset + hostChunk)); + }, + readFile: path => readAll(offset => call('hostRead', path, offset)), + readText: async path => new TextDecoder().decode(await host.readFile(path)), + run: async (options = {}) => { + const known = ['program', 'args', 'cwd', 'env', 'inheritEnv', 'timeoutMs', 'maxOutputBytes', 'signal']; + // There is no shell option to ask for: an unknown one is a mistake, not something to ignore. + for (const key of Object.keys(options)) if (!known.includes(key)) throw new TypeError('Unknown run option: ' + key); + const {program, args = [], cwd, env, inheritEnv, timeoutMs, maxOutputBytes, signal} = options; + const request = {program, args: args.map(String)}; + for (const [key, value] of Object.entries({cwd, env, inheritEnv, timeoutMs, maxOutputBytes})) + if (value !== undefined) request[key] = value; + signal?.throwIfAborted(); + // The listener exists before the start call: an abort that lands while the program starts is not lost. + let id; + const abort = () => { if (id !== undefined) call('hostRunCancel', id).catch(() => {}); }; + signal?.addEventListener('abort', abort, {once: true}); + try { + id = await call('hostRunStart', JSON.stringify(request)); + if (signal?.aborted) abort(); + let summary = ''; + while (!(summary = await call('hostRunPoll', id))) await new Promise(resolve => setTimeout(resolve, 10)); + const result = JSON.parse(summary); + const text = async stream => new TextDecoder().decode(await readAll(offset => call('hostRunRead', id, stream, offset))); + const {stdoutBytes, stderrBytes, ...rest} = result; + return {...rest, stdout: await text(1), stderr: await text(2)}; + } finally { + signal?.removeEventListener('abort', abort); + if (id !== undefined) await call('hostRunRelease', id); + } + }, + }; + globalThis.webFrontHost = host; const load = async index => { const parts = []; for (let offset = 0; ; offset += CHUNK) { @@ -289,6 +356,12 @@ class JasmineSession { return status; } + /// Throws unless `caller` is the page under test (the native capabilities answer to it only). + void requireCaller(const Caller& caller) { + std::scoped_lock lock{mutex}; + authorize(caller); + } + private: void authorize(const Caller& caller) const { if (!browser || *browser != caller) @@ -336,7 +409,7 @@ class JasmineTest { const auto path = detail::jasmineConfigurationPath(); if (!path) return; - const auto config = detail::jasmineConfiguration(detail::readJasmineFile(*path)); + const auto config = detail::jasmineConfiguration(detail::readJasmineFile(*path)); std::vector contents; for (const auto& file : config.files) contents.push_back(detail::readJasmineFile(file)); @@ -345,9 +418,19 @@ class JasmineTest { store = std::make_shared(config.captures); session = std::make_shared(std::move(contents), config.report, std::move(store)); const auto owned = session; - app.cppFunction("webfront.testing.count", [owned](AppUI ui) { return owned->count(ui); }); - app.cppFunction("webfront.testing.read", [owned](AppUI ui, double index, double offset) { return owned->read(ui, index, offset); }); - app.cppFunction("webfront.testing.result", [owned](AppUI ui, std::string result) { owned->result(ui, result); }); + // Native capabilities exist only when the owner's CMake file granted some (PROGRAMS): the runner then sets this file. + if (const auto hostPath = detail::jasmineEnvironment("WEBFRONT_JASMINE_HOST")) + host = std::make_shared(detail::hostConfiguration(detail::readJasmineFile(*hostPath))); + registerHost(app); + app.cppFunction("webfront.testing.count", [owned](AppUI ui) { + return owned->count(ui); + }); + app.cppFunction("webfront.testing.read", [owned](AppUI ui, double index, double offset) { + return owned->read(ui, index, offset); + }); + app.cppFunction("webfront.testing.result", [owned](AppUI ui, std::string result) { + owned->result(ui, result); + }); app.cppFunction("webfront.testing.screenshotStart", [owned](AppUI ui, std::string name) { owned->screenshotStart(ui, name); }); @@ -374,8 +457,51 @@ class JasmineTest { } private: - std::shared_ptr session; - UISubscription subscription; + /// The page's bridge to HostSession; each call is checked against the page under test, and refused with no grant. + void registerHost(App& app) { + const auto owned = session; + const auto grant = host; + const auto guard = [owned, grant](const AppUI& ui) -> HostSession& { + owned->requireCaller(ui); + if (!grant) + throw std::runtime_error("No native capability was granted to this test: add PROGRAMS to webfront_add_jasmine_test"); + return *grant; + }; + app.cppFunction("webfront.testing.hostPrograms", [guard](AppUI ui) { + return guard(ui).programs(); + }); + app.cppFunction("webfront.testing.hostMakeTemp", [guard](AppUI ui) { + return guard(ui).makeTemp(); + }); + app.cppFunction("webfront.testing.hostRemoveTemp", [guard](AppUI ui, std::string path) { + guard(ui).removeTemp(path); + }); + app.cppFunction("webfront.testing.hostWrite", [guard](AppUI ui, std::string path, double offset, std::vector bytes) { + guard(ui).writeFile(path, offset, bytes); + }); + app.cppFunction("webfront.testing.hostRead", [guard](AppUI ui, std::string path, double offset) { + return guard(ui).readFile(path, offset); + }); + app.cppFunction("webfront.testing.hostRunStart", [guard](AppUI ui, std::string request) { + return guard(ui).runStart(request); + }); + app.cppFunction("webfront.testing.hostRunPoll", [guard](AppUI ui, double id) { + return guard(ui).runPoll(id).value_or(std::string{}); + }); + app.cppFunction("webfront.testing.hostRunRead", [guard](AppUI ui, double id, double stream, double offset) { + return guard(ui).runRead(id, stream, offset); + }); + app.cppFunction("webfront.testing.hostRunCancel", [guard](AppUI ui, double id) { + guard(ui).runCancel(id); + }); + app.cppFunction("webfront.testing.hostRunRelease", [guard](AppUI ui, double id) { + guard(ui).runRelease(id); + }); + } + + std::shared_ptr session; + std::shared_ptr host; + UISubscription subscription; }; } // namespace jasmine_enabled #else diff --git a/include/webfront/testing/Process.hpp b/include/webfront/testing/Process.hpp new file mode 100644 index 00000000..87ea73a1 --- /dev/null +++ b/include/webfront/testing/Process.hpp @@ -0,0 +1,680 @@ +/// @brief Runs one native program for a test, without a shell, with bounded time and output. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include "../system/WindowsCompat.hpp" + + #include + + #include +#else + #include + #include + + #include + #include + #include + #include + #ifdef __linux__ + #include + #include + #endif + #include +extern char** environ; +#endif + +namespace webfront::testing { + +/// What to run. `program` is launched directly with `arguments` as its argv[1...]: no shell ever interprets them. +struct ProcessSpec { + std::filesystem::path program; + std::vector arguments; + std::filesystem::path workingDirectory; ///< Empty: the calling process's directory. + /// The child's whole environment, unless `inheritEnvironment` is set, in which case these entries are added to a copy + /// of the calling process's environment (and win over it). + std::map environment; + bool inheritEnvironment = false; + std::chrono::milliseconds timeout{30000}; + std::size_t maxOutputBytes = 1024 * 1024; ///< Per stream; the rest is read and discarded. +}; + +enum class ProcessStatus { + exited, ///< The program ended by itself; `exitCode` is meaningful (zero or not). + signaled, ///< POSIX: the program was ended by a signal, in `signal`. + timeout, ///< The deadline passed; the program and its process group/job were killed. + cancelled, ///< The caller asked to stop; the program and its process group/job were killed. + launchFailed, ///< The program could not be started; `error` says why. +}; + +struct ProcessResult { + ProcessStatus status = ProcessStatus::launchFailed; + int exitCode = -1; + int signal = 0; + std::string error; + std::string standardOutput, standardError; + bool outputTruncated = false, errorTruncated = false; + std::chrono::milliseconds duration{0}; +}; + +[[nodiscard]] inline const char* processStatusName(ProcessStatus status) noexcept { + switch (status) { + case ProcessStatus::exited: + return "exited"; + case ProcessStatus::signaled: + return "signaled"; + case ProcessStatus::timeout: + return "timeout"; + case ProcessStatus::cancelled: + return "cancelled"; + case ProcessStatus::launchFailed: + break; + } + return "launchFailed"; +} + +namespace detail { + +inline constexpr std::chrono::milliseconds processTick{20}; +/// After the direct child ended, how long its inherited pipes may stay open (a descendant that left the group or job). +inline constexpr std::chrono::milliseconds processDrainGrace{1000}; + +inline void validateProcessSpec(const ProcessSpec& spec) { + const auto clean = [](const std::string& text) { + return text.find('\0') == std::string::npos; + }; + if (spec.program.empty()) + throw std::invalid_argument("A program is required"); + if (!std::ranges::all_of(spec.arguments, clean)) + throw std::invalid_argument("An argument must not contain a NUL character"); + for (const auto& [key, value] : spec.environment) + if (key.empty() || key.find('=') != std::string::npos || !clean(key) || !clean(value)) + throw std::invalid_argument("Invalid environment entry"); + if (spec.timeout.count() <= 0) + throw std::invalid_argument("The timeout must be positive"); +} + +inline void appendBounded(std::string& into, const char* data, std::size_t size, std::size_t limit, bool& truncated) { + const std::size_t room = into.size() < limit ? limit - into.size() : 0; + into.append(data, std::min(size, room)); + if (size > room) + truncated = true; +} + +#ifdef _WIN32 + +inline std::wstring toWide(const std::string& text) { + if (text.empty()) + return {}; + const int size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), nullptr, 0); + if (size <= 0) + throw std::invalid_argument("Text is not valid UTF-8"); + std::wstring wide(static_cast(size), L'\0'); + ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), static_cast(text.size()), wide.data(), size); + return wide; +} + +/// The CommandLineToArgvW / MSVCRT quoting: the program receives exactly the argument. +inline std::wstring quoteWindowsArgument(const std::wstring& argument) { + if (!argument.empty() && argument.find_first_of(L" \t\n\v\"") == std::wstring::npos) + return argument; + std::wstring quoted = L"\""; + for (auto it = argument.begin();; ++it) { + std::size_t backslashes = 0; + while (it != argument.end() && *it == L'\\') { + ++it; + ++backslashes; + } + if (it == argument.end()) { + quoted.append(backslashes * 2, L'\\'); + break; + } + if (*it == L'"') + quoted.append(backslashes * 2 + 1, L'\\'); + else + quoted.append(backslashes, L'\\'); + quoted.push_back(*it); + } + return quoted + L'"'; +} + +struct WindowsHandle { + HANDLE handle = nullptr; + WindowsHandle() = default; + explicit WindowsHandle(HANDLE h) : handle(h == INVALID_HANDLE_VALUE ? nullptr : h) {} + WindowsHandle(const WindowsHandle&) = delete; + WindowsHandle& operator=(const WindowsHandle&) = delete; + ~WindowsHandle() { + reset(); + } + void reset() { + if (handle) + ::CloseHandle(handle); + handle = nullptr; + } + explicit operator bool() const { + return handle != nullptr; + } +}; + +/// A pipe whose read end is opened for overlapped I/O (CreatePipe cannot) and whose write end is inheritable. +inline bool makeOverlappedPipe(WindowsHandle& readEnd, WindowsHandle& writeEnd, SECURITY_ATTRIBUTES& inheritable) { + static std::atomic counter{0}; + const std::wstring name = L"\\\\.\\pipe\\webfront-process-" + std::to_wstring(::GetCurrentProcessId()) + L"-" + std::to_wstring(counter++); + SECURITY_ATTRIBUTES own{sizeof own, nullptr, FALSE}; + readEnd.handle = ::CreateNamedPipeW(name.c_str(), + PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + 1, + 65536, + 65536, + 0, + &own); + if (readEnd.handle == INVALID_HANDLE_VALUE) { + readEnd.handle = nullptr; + return false; + } + writeEnd.handle = ::CreateFileW(name.c_str(), GENERIC_WRITE, 0, &inheritable, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (writeEnd.handle == INVALID_HANDLE_VALUE) { + writeEnd.handle = nullptr; + return false; + } + return true; +} + +inline ProcessResult runProcessWindows(const ProcessSpec& spec, const std::atomic& cancel) { + ProcessResult result; + const auto begin = std::chrono::steady_clock::now(); + try { + std::wstring commandLine = quoteWindowsArgument(spec.program.wstring()); + for (const auto& argument : spec.arguments) + commandLine += L' ' + quoteWindowsArgument(toWide(argument)); + // The environment block: sorted case-insensitively, as CreateProcess requires. + std::map variables{[](const std::wstring& a, const std::wstring& b) { + return ::CompareStringOrdinal(a.c_str(), -1, b.c_str(), -1, TRUE) == CSTR_LESS_THAN; + }}; + if (spec.inheritEnvironment) { + wchar_t* block = ::GetEnvironmentStringsW(); + for (const wchar_t* entry = block; block && *entry; entry += std::wcslen(entry) + 1) { + const std::wstring text{entry}; + if (const auto equals = text.find(L'=', 1); equals != std::wstring::npos) + variables[text.substr(0, equals)] = text.substr(equals + 1); + } + if (block) + ::FreeEnvironmentStringsW(block); + } else { + // A Windows program usually cannot start without its system directory. + wchar_t root[MAX_PATH]; + const DWORD length = ::GetEnvironmentVariableW(L"SystemRoot", root, MAX_PATH); + if (length > 0 && length < MAX_PATH) + variables[L"SystemRoot"] = std::wstring(root, length); + } + for (const auto& [key, value] : spec.environment) + variables[toWide(key)] = toWide(value); + std::wstring environmentBlock; + for (const auto& [key, value] : variables) + environmentBlock += key + L'=' + value + L'\0'; + environmentBlock += L'\0'; + + SECURITY_ATTRIBUTES inheritable{sizeof inheritable, nullptr, TRUE}; + WindowsHandle outRead, outWrite, errRead, errWrite, input; + // The read ends are overlapped, so that a reader blocked on a pipe another process still holds can be cancelled. + if (!makeOverlappedPipe(outRead, outWrite, inheritable) || !makeOverlappedPipe(errRead, errWrite, inheritable)) + throw std::runtime_error("Cannot create a pipe"); + input.handle = ::CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &inheritable, OPEN_EXISTING, 0, nullptr); + if (input.handle == INVALID_HANDLE_VALUE) + input.handle = nullptr; + if (!input) + throw std::runtime_error("Cannot open NUL"); + + // Only these three handles are inherited. + HANDLE inherited[3] = {input.handle, outWrite.handle, errWrite.handle}; + SIZE_T attributeSize = 0; + ::InitializeProcThreadAttributeList(nullptr, 1, 0, &attributeSize); + std::vector attributeStorage(attributeSize); + auto* attributes = reinterpret_cast(attributeStorage.data()); + if (!::InitializeProcThreadAttributeList(attributes, 1, 0, &attributeSize)) + throw std::runtime_error("Cannot prepare the process attributes"); + struct AttributesGuard { + LPPROC_THREAD_ATTRIBUTE_LIST list; + ~AttributesGuard() { + ::DeleteProcThreadAttributeList(list); + } + } attributesGuard{attributes}; + if (!::UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, sizeof inherited, nullptr, nullptr)) + throw std::runtime_error("Cannot restrict the inherited handles"); + + STARTUPINFOEXW startup{}; + startup.StartupInfo.cb = sizeof startup; + startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + startup.StartupInfo.hStdInput = input.handle; + startup.StartupInfo.hStdOutput = outWrite.handle; + startup.StartupInfo.hStdError = errWrite.handle; + startup.lpAttributeList = attributes; + + WindowsHandle job{::CreateJobObjectW(nullptr, nullptr)}; + if (!job) + throw std::runtime_error("Cannot create a job object"); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + ::SetInformationJobObject(job.handle, JobObjectExtendedLimitInformation, &limits, sizeof limits); + + const std::wstring directory = spec.workingDirectory.wstring(); + PROCESS_INFORMATION process{}; + if (!::CreateProcessW(spec.program.c_str(), + commandLine.data(), + nullptr, + nullptr, + TRUE, + CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, + environmentBlock.data(), + directory.empty() ? nullptr : directory.c_str(), + &startup.StartupInfo, + &process)) { + result.error = "CreateProcess failed with error " + std::to_string(::GetLastError()); + return result; + } + WindowsHandle child{process.hProcess}, thread{process.hThread}; + if (!::AssignProcessToJobObject(job.handle, child.handle)) { + ::TerminateProcess(child.handle, 1); + result.error = "Cannot assign the program to its job object"; + return result; + } + ::ResumeThread(thread.handle); + outWrite.reset(); + errWrite.reset(); + input.reset(); + + std::atomic outDone{false}, errDone{false}; + std::atomic stopReading{false}; + const auto reader = [&stopReading](HANDLE pipe, std::string& into, bool& truncated, std::size_t limit, std::atomic& done) { + char buffer[8192]; + WindowsHandle event{::CreateEventW(nullptr, TRUE, FALSE, nullptr)}; + for (;;) { + OVERLAPPED overlapped{}; + overlapped.hEvent = event.handle; + ::ResetEvent(event.handle); + DWORD count = 0; + if (!::ReadFile(pipe, buffer, sizeof buffer, &count, &overlapped)) { + if (::GetLastError() != ERROR_IO_PENDING) + break; // The other end is closed: the end of the stream. + while (::WaitForSingleObject(event.handle, 20) == WAIT_TIMEOUT && !stopReading) {} + if (!HasOverlappedIoCompleted(&overlapped)) + ::CancelIoEx(pipe, &overlapped); + if (!::GetOverlappedResult(pipe, &overlapped, &count, TRUE)) + break; + } + if (count == 0) + break; + appendBounded(into, buffer, count, limit, truncated); + } + done = true; + }; + std::thread outThread{reader, + outRead.handle, + std::ref(result.standardOutput), + std::ref(result.outputTruncated), + spec.maxOutputBytes, + std::ref(outDone)}; + std::thread errThread{reader, errRead.handle, std::ref(result.standardError), std::ref(result.errorTruncated), spec.maxOutputBytes, std::ref(errDone)}; + + const auto deadline = begin + spec.timeout; + bool timedOut = false, cancelled = false; + for (;;) { + if (::WaitForSingleObject(child.handle, static_cast(processTick.count())) == WAIT_OBJECT_0) + break; + if (cancel) { + cancelled = true; + break; + } + if (std::chrono::steady_clock::now() >= deadline) { + timedOut = true; + break; + } + } + // The program, and everything it started, ends here: its descendants do not outlive the call. + ::TerminateJobObject(job.handle, 1); + ::WaitForSingleObject(child.handle, 5000); + const auto drainEnd = std::chrono::steady_clock::now() + processDrainGrace; + while (!(outDone && errDone) && std::chrono::steady_clock::now() < drainEnd) + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + stopReading = true; // A reader still waiting on a pipe another process holds cancels its read and ends. + outThread.join(); + errThread.join(); + DWORD code = 0; + ::GetExitCodeProcess(child.handle, &code); + result.exitCode = static_cast(code); + result.status = timedOut ? ProcessStatus::timeout : cancelled ? ProcessStatus::cancelled : ProcessStatus::exited; + if (result.status != ProcessStatus::exited) + result.exitCode = -1; + } catch (const std::exception& error) { + result.status = ProcessStatus::launchFailed; + result.error = error.what(); + } + result.duration = std::chrono::duration_cast(std::chrono::steady_clock::now() - begin); + return result; +} + +#else + +struct Descriptor { + int fd = -1; + Descriptor() = default; + explicit Descriptor(int value) : fd(value) {} + Descriptor(const Descriptor&) = delete; + Descriptor& operator=(const Descriptor&) = delete; + ~Descriptor() { + reset(); + } + void reset() { + if (fd >= 0) + ::close(fd); + fd = -1; + } +}; + +inline bool makePipe(Descriptor& readEnd, Descriptor& writeEnd) { + int fds[2]; + if (::pipe(fds) != 0) + return false; + readEnd.fd = fds[0]; + writeEnd.fd = fds[1]; + // Above the standard descriptors, whatever the application closed: a pipe end that already was descriptor 1 or 2 would + // keep its close-on-exec flag through dup2 onto itself and vanish at exec, taking the program's output with it. + for (auto* end : {&readEnd, &writeEnd}) { + const int moved = ::fcntl(end->fd, F_DUPFD_CLOEXEC, 3); + if (moved < 0) + return false; + ::close(end->fd); + end->fd = moved; + } + ::fcntl(readEnd.fd, F_SETFL, ::fcntl(readEnd.fd, F_GETFL) | O_NONBLOCK); + return true; +} + +inline ProcessResult runProcessPosix(const ProcessSpec& spec, const std::atomic& cancel) { + ProcessResult result; + const auto begin = std::chrono::steady_clock::now(); + + std::vector environmentStrings; + std::map variables; + if (spec.inheritEnvironment) + for (char** entry = environ; entry && *entry; ++entry) { + const std::string text{*entry}; + if (const auto equals = text.find('='); equals != std::string::npos && equals > 0) + variables[text.substr(0, equals)] = text.substr(equals + 1); + } + for (const auto& [key, value] : spec.environment) + variables[key] = value; + for (const auto& [key, value] : variables) + environmentStrings.push_back(key + '=' + value); + std::vector environmentBlock; + for (auto& entry : environmentStrings) + environmentBlock.push_back(entry.data()); + environmentBlock.push_back(nullptr); + + const std::string program = spec.program.string(); + const std::string directory = spec.workingDirectory.string(); + std::vector argumentStrings{program}; + argumentStrings.insert(argumentStrings.end(), spec.arguments.begin(), spec.arguments.end()); + std::vector argv; + for (auto& argument : argumentStrings) + argv.push_back(argument.data()); + argv.push_back(nullptr); + + Descriptor outRead, outWrite, errRead, errWrite; + if (!makePipe(outRead, outWrite) || !makePipe(errRead, errWrite)) { + result.error = "Cannot create a pipe"; + return result; + } + + #ifdef __linux__ + // fork and exec rather than posix_spawn: the child asks the kernel to kill it when this process dies. A CTest deadline + // ends the application with SIGKILL, which runs no destructor, and the program must not outlive the test. Only + // async-signal-safe calls run between fork and exec. + int report[2]; + if (::pipe2(report, O_CLOEXEC) != 0) { + result.error = "Cannot create a pipe"; + return result; + } + Descriptor reportRead{report[0]}, reportWrite{report[1]}; + // Above the standard descriptors, like the output pipes: the child's open and dup2 must not close or replace the end + // that carries an exec failure, or the parent would take the failed launch for a program that exited with 127. + for (auto* end : {&reportRead, &reportWrite}) { + const int moved = ::fcntl(end->fd, F_DUPFD_CLOEXEC, 3); + if (moved < 0) { + result.error = "Cannot create a pipe"; + return result; + } + ::close(end->fd); + end->fd = moved; + } + const pid_t parent = ::getpid(); + sigset_t none; + sigemptyset(&none); // Unqualified: a macro on macOS. + const pid_t forked = ::fork(); + if (forked == 0) { + ::setpgid(0, 0); // Its own process group: a timeout or cancellation kills it and the descendants that stayed in it. + ::prctl(PR_SET_PDEATHSIG, SIGKILL); + int failure = 0; + if (::getppid() != parent) + failure = ESRCH; + else { + // The program starts with default dispositions, not the application's (ignored SIGPIPE or SIGCHLD, handlers + // that would run in the child before exec), and only then with every signal unblocked. + struct sigaction byDefault{}; + byDefault.sa_handler = SIG_DFL; + for (int signalNumber = 1; signalNumber < NSIG; ++signalNumber) + if (signalNumber != SIGKILL && signalNumber != SIGSTOP) + ::sigaction(signalNumber, &byDefault, nullptr); + ::sigprocmask(SIG_SETMASK, &none, nullptr); + const int input = ::open("/dev/null", O_RDONLY); + if (input < 0 || ::dup2(input, 0) < 0 || ::dup2(outWrite.fd, 1) < 0 || ::dup2(errWrite.fd, 2) < 0) + failure = errno; + // The application's own descriptors (sockets, files) stay out of the program; the report pipe closes on exec. + else if (::syscall(SYS_close_range, 3U, ~0U, 4U /* CLOSE_RANGE_CLOEXEC */) != 0 && errno != ENOSYS && errno != EINVAL) + failure = errno; + else if (!directory.empty() && ::chdir(directory.c_str()) != 0) + failure = errno; + else { + ::execve(program.c_str(), argv.data(), environmentBlock.data()); + failure = errno; + } + } + [[maybe_unused]] const auto written = ::write(reportWrite.fd, &failure, sizeof failure); + ::_exit(127); + } + if (forked < 0) { + result.error = std::string("Cannot start the program: ") + std::strerror(errno); + return result; + } + const pid_t pid = forked; + ::setpgid(pid, pid); // Also from here, so that no kill of the group can come before the child's own call. + reportWrite.reset(); + int failure = 0; + ssize_t reported; + do + reported = ::read(reportRead.fd, &failure, sizeof failure); + while (reported < 0 && errno == EINTR); + if (reported == static_cast(sizeof failure)) { + ::waitpid(pid, nullptr, 0); + result.error = std::string("Cannot start the program: ") + std::strerror(failure); + return result; + } + #else + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + ::posix_spawn_file_actions_init(&actions); + ::posix_spawnattr_init(&attributes); + struct Guard { + posix_spawn_file_actions_t* actions; + posix_spawnattr_t* attributes; + ~Guard() { + ::posix_spawn_file_actions_destroy(actions); + ::posix_spawnattr_destroy(attributes); + } + } guard{&actions, &attributes}; + // Its own process group: a timeout or cancellation kills the program and every descendant that stayed in it. + sigset_t none; + sigemptyset(&none); // Unqualified: a macro on macOS. + ::posix_spawnattr_setpgroup(&attributes, 0); + sigset_t every; + sigfillset(&every); + ::posix_spawnattr_setsigmask(&attributes, &none); + ::posix_spawnattr_setsigdefault(&attributes, &every); // Default dispositions, not the application's. + ::posix_spawnattr_setflags(&attributes, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF); + bool prepared = ::posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) == 0 + && ::posix_spawn_file_actions_adddup2(&actions, outWrite.fd, 1) == 0 && ::posix_spawn_file_actions_adddup2(&actions, errWrite.fd, 2) == 0; + #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 34)) + // The calling application's own descriptors (sockets, files) stay out of the program. + prepared = prepared && ::posix_spawn_file_actions_addclosefrom_np(&actions, 3) == 0; + #endif + if (!directory.empty()) { + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" // macOS 26 prefers the name without _np. + #endif + prepared = prepared && ::posix_spawn_file_actions_addchdir_np(&actions, directory.c_str()) == 0; + #if defined(__clang__) + #pragma clang diagnostic pop + #endif + } + if (!prepared) { + result.error = "Cannot prepare the child process"; + return result; + } + pid_t pid = 0; + if (const int code = ::posix_spawn(&pid, program.c_str(), &actions, &attributes, argv.data(), environmentBlock.data()); code != 0) { + result.error = std::string("Cannot start the program: ") + std::strerror(code); + return result; + } + #endif + outWrite.reset(); + errWrite.reset(); + + bool statusLost = false; + // Only while the program is not reaped: its number, and its group's, are reserved until then. + const auto killGroup = [pid] { + ::kill(-pid, SIGKILL); + ::kill(pid, SIGKILL); + }; + const auto deadline = begin + spec.timeout; + bool exited = false, timedOut = false, cancelled = false; + int waitStatus = 0; + auto drainEnd = std::chrono::steady_clock::time_point::max(); + for (;;) { + pollfd fds[2]; + nfds_t count = 0; + int owners[2]; + for (auto [descriptor, id] : { + std::pair{&outRead, 0}, + std::pair{&errRead, 1} + }) + if (descriptor->fd >= 0) { + fds[count] = {descriptor->fd, POLLIN, 0}; + owners[count] = id; + ++count; + } + if (count) + ::poll(fds, count, static_cast(processTick.count())); + else + std::this_thread::sleep_for(processTick); + for (nfds_t index = 0; index < count; ++index) { + auto& descriptor = owners[index] == 0 ? outRead : errRead; + char buffer[8192]; + // A bounded amount per turn: a program that keeps its pipe full must not starve the other stream, the + // deadline or the cancellation, which are checked after every turn. + for (int reads = 0; reads < 16; ++reads) { + const auto got = ::read(descriptor.fd, buffer, sizeof buffer); + if (got > 0) { + owners[index] == 0 + ? appendBounded(result.standardOutput, buffer, static_cast(got), spec.maxOutputBytes, result.outputTruncated) + : appendBounded(result.standardError, buffer, static_cast(got), spec.maxOutputBytes, result.errorTruncated); + continue; + } + if (got == 0 || (errno != EAGAIN && errno != EINTR)) + descriptor.reset(); + break; + } + } + const auto now = std::chrono::steady_clock::now(); + if (!exited) { + // Look without reaping: the program's number, and its group's, stay reserved while it is a zombie, so the + // group can be killed before any other process may receive them. + siginfo_t info{}; + const int waited = ::waitid(P_PID, static_cast(pid), &info, WEXITED | WNOHANG | WNOWAIT); + if (waited == 0 && info.si_pid == pid) { + ::kill(-pid, SIGKILL); // Whatever the program left running in its group ends with it. + ::waitpid(pid, &waitStatus, 0); + exited = true; + drainEnd = now + processDrainGrace; + } else if (waited < 0 && errno == ECHILD) { + // The application ignores SIGCHLD, so the system reaped the program and kept no status. + statusLost = true; + exited = true; + ::kill(-pid, SIGKILL); + drainEnd = now + processDrainGrace; + } else if (cancel.load() && !cancelled && !timedOut) { + cancelled = true; + killGroup(); + } else if (now >= deadline && !cancelled && !timedOut) { + timedOut = true; + killGroup(); + } + } + if (exited && ((outRead.fd < 0 && errRead.fd < 0) || now >= drainEnd)) + break; + } + if (timedOut) + result.status = ProcessStatus::timeout; + else if (cancelled) + result.status = ProcessStatus::cancelled; + else if (statusLost) { + result.status = ProcessStatus::exited; + result.error = "The exit status is unavailable because the application ignores SIGCHLD"; + } else if (WIFSIGNALED(waitStatus)) { + result.status = ProcessStatus::signaled; + result.signal = WTERMSIG(waitStatus); + } else { + result.status = ProcessStatus::exited; + result.exitCode = WEXITSTATUS(waitStatus); + } + result.duration = std::chrono::duration_cast(std::chrono::steady_clock::now() - begin); + return result; +} + +#endif +} // namespace detail + +/** + * @brief Runs `spec.program` to completion, or until `spec.timeout` or `cancel`, and returns how it ended. + * The program is started directly (never through a shell) with its own standard input closed. Its output is captured up to + * `maxOutputBytes` per stream and the excess is discarded (`outputTruncated`/`errorTruncated`). When it ends, times out or + * is cancelled, the program and its descendants are killed: a POSIX process group (descendants that left it with setsid + * survive), a Windows job object. The call blocks; run it on its own thread. Invalid input throws std::invalid_argument; a + * program that cannot start is a `launchFailed` result. + */ +inline ProcessResult runProcess(const ProcessSpec& spec, const std::atomic& cancel) { + detail::validateProcessSpec(spec); +#ifdef _WIN32 + return detail::runProcessWindows(spec, cancel); +#else + return detail::runProcessPosix(spec, cancel); +#endif +} + +} // namespace webfront::testing diff --git a/test/cmake/consumer/CMakeLists.txt b/test/cmake/consumer/CMakeLists.txt index fb831fcf..2c966d5f 100644 --- a/test/cmake/consumer/CMakeLists.txt +++ b/test/cmake/consumer/CMakeLists.txt @@ -31,6 +31,10 @@ enable_testing() file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/dummy.js" "// configuration fixture\n") webfront_add_jasmine_test(NAME PublicJasmineRegistration TARGET consumer JASMINE "${CMAKE_CURRENT_BINARY_DIR}/dummy.js" SPECS "${CMAKE_CURRENT_BINARY_DIR}/dummy.js") +# The native grant (PROGRAMS) is accepted from a parent project too, with a generator expression for the program. +webfront_add_jasmine_test(NAME PublicJasmineHostRegistration TARGET consumer + JASMINE "${CMAKE_CURRENT_BINARY_DIR}/dummy.js" SPECS "${CMAKE_CURRENT_BINARY_DIR}/dummy.js" + PROGRAMS "$") get_property(engines GLOBAL PROPERTY WEBFRONT_JASMINE_FRONTENDS) if(NOT "WKWebView" IN_LIST engines) message(FATAL_ERROR "Public Jasmine frontend metadata was lost across add_subdirectory") diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 7ea2da1f..6fe85792 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -29,7 +29,7 @@ list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp D list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) -list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) +list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp) list(APPEND TESTS_LIST FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) @@ -47,6 +47,12 @@ if(MSVC) target_compile_options(tests PRIVATE /bigobj) endif() target_compile_definitions(tests PRIVATE WEBFRONT_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +# The native program of the webFrontHost and runProcess tests (also run by the browser specs). +add_executable(host_probe ../web/host/HostProbe.cpp) +target_compile_features(host_probe PRIVATE cxx_std_23) +target_link_libraries(host_probe PRIVATE WebFront_test_hardening WebFront_warnings) +add_dependencies(tests host_probe) +target_compile_definitions(tests PRIVATE WEBFRONT_HOST_PROBE="$") # The heavy units instantiate a full application, and compile four to a file in about half the time of four apart # (docs/BUILD_TIME_STUDY.md). The desktop CI jobs set the batch size; the default keeps one object per test file, which diff --git a/test/unit/HostTests.cpp b/test/unit/HostTests.cpp new file mode 100644 index 00000000..77d02f7c --- /dev/null +++ b/test/unit/HostTests.cpp @@ -0,0 +1,556 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#ifndef _WIN32 + #include + + #include + #include +#endif + +namespace { +using namespace webfront::testing; +using namespace std::chrono_literals; + +const std::filesystem::path probe{WEBFRONT_HOST_PROBE}; + +ProcessSpec probeSpec(std::vector arguments) { + ProcessSpec spec; + spec.program = probe; + spec.arguments = std::move(arguments); + return spec; +} + +ProcessResult run(const ProcessSpec& spec) { + const std::atomic never{false}; + return runProcess(spec, never); +} + +struct TempRoot { + std::filesystem::path path; + explicit TempRoot(const std::string& name) : path(std::filesystem::temp_directory_path() / ("webfront-host-" + name)) { + std::filesystem::remove_all(path); + } + ~TempRoot() { + std::error_code ignored; + std::filesystem::remove_all(path, ignored); + } +}; + +std::string configurationFor(const TempRoot& root, const std::vector& programs) { + std::string text = "{\"programs\":["; + for (const auto& program : programs) + text += (text.size() > 13 ? "," : "") + webfront::json::quote(program.generic_string()); + return text + "],\"temporary\":" + webfront::json::quote(root.path.generic_string()) + "}"; +} + +std::string field(const std::string& json, const std::string& name) { + const auto key = "\"" + name + "\":"; + auto at = json.find(key); + REQUIRE(at != std::string::npos); + at += key.size(); + const auto end = json.find_first_of(",}", at); + auto value = json.substr(at, end - at); + if (value.size() >= 2 && value.front() == '"') + value = value.substr(1, value.size() - 2); + return value; +} + +std::string waitFor(HostSession& host, double id) { + for (int attempt = 0; attempt < 1000; ++attempt) { + if (const auto summary = host.runPoll(id)) + return *summary; + std::this_thread::sleep_for(10ms); + } + FAIL("the run did not end"); + return {}; +} + +std::string text(const std::vector& bytes) { + return {bytes.begin(), bytes.end()}; +} +} // namespace + +SCENARIO("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); + } + } +} + +SCENARIO("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_FALSE(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); + } + } +#endif +} + +SCENARIO("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_FALSE(result.errorTruncated); + } +} + +SCENARIO("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); + } + } +} + +SCENARIO("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_FALSE(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_FALSE(std::filesystem::exists(marker)); + } + } +} + +SCENARIO("Invalid requests are refused before anything starts") { + REQUIRE_THROWS(run(ProcessSpec{})); + auto nul = probeSpec({"args", std::string("a\0b", 3)}); + REQUIRE_THROWS(run(nul)); + auto timeout = probeSpec({"exit"}); + timeout.timeout = 0ms; + REQUIRE_THROWS(run(timeout)); + auto environment = probeSpec({"exit"}); + environment.environment["A=B"] = "x"; + REQUIRE_THROWS(run(environment)); +} + +SCENARIO("The host configuration is strict") { + using webfront::testing::detail::hostConfiguration; + const auto absolute = webfront::json::quote((std::filesystem::temp_directory_path() / "x").generic_string()); + REQUIRE_NOTHROW(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"})"}) + REQUIRE_THROWS(hostConfiguration(bad)); +} + +SCENARIO("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") { + REQUIRE_THROWS_WITH(host.runStart(request("/bin/sh")), Catch::Matchers::ContainsSubstring("not authorized")); + REQUIRE_THROWS_WITH(host.runStart(request("host_probe")), Catch::Matchers::ContainsSubstring("not authorized")); + REQUIRE_THROWS_WITH(host.runStart(request("")), Catch::Matchers::ContainsSubstring("not authorized")); + REQUIRE_THROWS_WITH(host.runStart(request((probe.parent_path() / "missing").generic_string())), Catch::Matchers::ContainsSubstring("not authorized")); + } + THEN("unknown options and out-of-range limits are refused") { + const auto base = webfront::json::quote(probe.generic_string()); + REQUIRE_THROWS(host.runStart("{\"program\":" + base + ",\"shell\":true}")); + REQUIRE_THROWS(host.runStart("{\"program\":" + base + ",\"timeoutMs\":0}")); + REQUIRE_THROWS(host.runStart("{\"program\":" + base + ",\"timeoutMs\":3600001}")); + REQUIRE_THROWS(host.runStart("{\"program\":" + base + ",\"maxOutputBytes\":1.5}")); + REQUIRE_THROWS(host.runStart("{\"program\":" + base + ",\"cwd\":\"/\"}")); + } +} + +SCENARIO("A program authorized by no configuration is never reachable") { + TempRoot root{"empty-grant"}; + HostSession host{webfront::testing::detail::hostConfiguration(configurationFor(root, {}))}; + REQUIRE_THROWS_WITH(host.runStart("{\"program\":" + webfront::json::quote(probe.generic_string()) + "}"), + Catch::Matchers::ContainsSubstring("not authorized")); +} + +SCENARIO("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()); + REQUIRE_THROWS(host.writeFile(file, 5, b)); // A chunk must continue the file. + } + THEN("paths outside the spaces are refused, however they are spelled") { + REQUIRE_THROWS(host.writeFile(root.path.generic_string() + "/loose", 0, {})); + REQUIRE_THROWS(host.writeFile(first + "/../loose", 0, {})); + REQUIRE_THROWS(host.writeFile(first + "/../../escape", 0, {})); + REQUIRE_THROWS(host.writeFile("relative", 0, {})); + REQUIRE_THROWS(host.readFile((std::filesystem::temp_directory_path() / "nothing-here").generic_string(), 0)); + REQUIRE_THROWS(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"); + REQUIRE_THROWS(host.writeFile(first + "/out/webfront-host-escape", 0, {})); + REQUIRE_FALSE(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); + REQUIRE_THROWS(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_FALSE(std::filesystem::exists(webfront::testing::detail::pathFromUtf8(second))); + REQUIRE_THROWS(host.removeTemp(second)); + REQUIRE_THROWS(host.removeTemp(root.path.generic_string())); + } + } + THEN("ending the session removes every space left") { + REQUIRE_FALSE(std::filesystem::exists(webfront::testing::detail::pathFromUtf8(first))); + } +} + +SCENARIO("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); + REQUIRE_THROWS(one.writeFile(b + "/x", 0, {})); +} + +SCENARIO("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_FALSE(host.runPoll(id)); + REQUIRE_THROWS(host.runRead(id, 1, 0)); + host.runCancel(id); + REQUIRE(field(waitFor(host, id), "status") == "cancelled"); + host.runRelease(id); + REQUIRE_THROWS(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)); + REQUIRE_THROWS(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 +SCENARIO("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)); + } +} + +SCENARIO("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); +} + +SCENARIO("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_FALSE(result.error.empty()); +} +#endif + +#ifdef __linux__ +SCENARIO("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_FALSE(std::filesystem::exists(marker)); + } +} +#endif + +SCENARIO("A program that keeps its pipes full cannot hold off the deadline") { + auto spec = probeSpec({"flood"}); + 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 the output stays bounded") { + REQUIRE(result.status == ProcessStatus::timeout); + REQUIRE(std::chrono::steady_clock::now() - begin < 5s); + REQUIRE(result.standardOutput.size() == 1000); + REQUIRE(result.standardError.size() == 1000); + } +} + +SCENARIO("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_FALSE(field(summary, "error").empty()); + } + host.runRelease(id); + REQUIRE_THROWS_WITH(host.runStart("{\"program\":" + webfront::json::quote((absent.parent_path() / "other").generic_string()) + "}"), + Catch::Matchers::ContainsSubstring("not authorized")); +} + +#ifndef _WIN32 +SCENARIO("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") { + REQUIRE_THROWS_WITH(host.removeTemp(name), Catch::Matchers::ContainsSubstring("Cannot remove")); + REQUIRE(fs::exists(space)); + fs::permissions(space / "locked", fs::perms::owner_all, fs::perm_options::replace); + REQUIRE_NOTHROW(host.removeTemp(name)); + REQUIRE_FALSE(fs::exists(space)); + } +} +#endif + +SCENARIO("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()); + REQUIRE_THROWS(host.runStart(base + ",\"env\":{\"A=B\":\"x\"}}")); + REQUIRE_THROWS(host.runStart(base + ",\"env\":{\"\":\"x\"}}")); + REQUIRE_THROWS(host.runStart(base + ",\"args\":[\"a\\u0000b\"]}")); +} + +#ifndef _WIN32 +SCENARIO("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 "); + } +} +#endif + +SCENARIO("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. + REQUIRE_THROWS_WITH(host.readFile(space + "/big.bin", 0), Catch::Matchers::ContainsSubstring("64 MiB")); + std::filesystem::resize_file(file, 10); + REQUIRE(host.readFile(space + "/big.bin", 0).size() == 10); +} + +#ifndef _WIN32 +SCENARIO("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); +} +#endif + +#ifdef __linux__ +SCENARIO("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); +} +#endif diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 42cd5af8..b5f981b9 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -147,6 +147,34 @@ if(_browser_tests_available) endif() set_tests_properties(ConsumerJasmine-${mode} PROPERTIES FIXTURES_SETUP ConsumerJasmineRuns) endforeach() + # Native programs and temporary spaces of the specs (issue #445): the probe is the only program the owner authorizes, + # next to a file that is not executable. + add_dependencies(jasmine_consumer host_probe) + set(_not_executable "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/index.html") + set(_reason_host-unauthorized "${_reason_fail}") + set(_reason_host-timeout "${_reason_fail}") + set(_reason_host-launch "${_reason_fail}") + foreach(mode host host-denied host-unauthorized host-timeout host-launch) + set(programs PROGRAMS "$" "${_not_executable}") + if(mode STREQUAL "host-denied") + set(programs) + elseif(mode STREQUAL "host-launch") + set(programs PROGRAMS "${_not_executable}") + endif() + webfront_add_jasmine_test(NAME ConsumerJasmine-${mode} TARGET jasmine_consumer + FRONTEND "${WEBFRONT_WEBTEST_FRONTEND}" TIMEOUT 60 + SPECS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer/${mode}.spec.js" + ARGS "${CMAKE_CURRENT_SOURCE_DIR}/jasmine-consumer" + ${programs}) + if(mode STREQUAL "host-denied") + # A grant in the inherited environment must not reach a test that has none. + set_tests_properties(ConsumerJasmine-host-denied PROPERTIES ENVIRONMENT + "WEBFRONT_JASMINE_HOST=${CMAKE_CURRENT_BINARY_DIR}/webfront-jasmine/ConsumerJasmine-host/host-$.json") + endif() + if(DEFINED _reason_${mode}) + set_tests_properties(ConsumerJasmine-${mode} PROPERTIES PASS_REGULAR_EXPRESSION "${_reason_${mode}}") + endif() + endforeach() # Window capture (issue #468) is implemented by every embedded frontend. set(WEBFRONT_CAPTURE_FRONTENDS WebKitGTK WKWebView WebView2 CEF) if(WEBFRONT_WEBTEST_FRONTEND IN_LIST WEBFRONT_CAPTURE_FRONTENDS) diff --git a/test/web/host/HostProbe.cpp b/test/web/host/HostProbe.cpp new file mode 100644 index 00000000..70617d91 --- /dev/null +++ b/test/web/host/HostProbe.cpp @@ -0,0 +1,211 @@ +// A tiny native program for the tests of webFrontHost and runProcess: one behaviour per first argument. +#ifdef _WIN32 + #define _CRT_SECURE_NO_WARNINGS + #define NOMINMAX +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include + #include + #include + #include +// clang-format off + #include + // clang-format on + #pragma comment(lib, "shell32.lib") +#else + #include + + #include +extern char** environ; +#endif + +namespace { +#ifdef _WIN32 +// The C runtime hands argv and the environment over in the ANSI code page: read the UTF-16 ones and convert them. +std::string toUtf8(const wchar_t* wide) { + const int size = ::WideCharToMultiByte(CP_UTF8, 0, wide, -1, nullptr, 0, nullptr, nullptr); + std::string text(static_cast(size > 0 ? size - 1 : 0), '\0'); + if (size > 1) + ::WideCharToMultiByte(CP_UTF8, 0, wide, -1, text.data(), size, nullptr, nullptr); + return text; +} + +std::wstring toWide(const char* utf8) { + const int size = ::MultiByteToWideChar(CP_UTF8, 0, utf8, -1, nullptr, 0); + std::wstring text(static_cast(size > 0 ? size - 1 : 0), L'\0'); + if (size > 1) + ::MultiByteToWideChar(CP_UTF8, 0, utf8, -1, text.data(), size); + return text; +} + +bool environmentValue(const char* name, std::string& value) { + const auto key = toWide(name); + const DWORD size = ::GetEnvironmentVariableW(key.c_str(), nullptr, 0); + if (size == 0) + return false; + std::wstring wide(size, L'\0'); + wide.resize(::GetEnvironmentVariableW(key.c_str(), wide.data(), size)); + value = toUtf8(wide.c_str()); + return true; +} +#else +bool environmentValue(const char* name, std::string& value) { + const char* found = std::getenv(name); + if (found) + value = found; + return found != nullptr; +} +#endif + +std::filesystem::path pathOf(const char* utf8) { + return std::filesystem::path(std::u8string(reinterpret_cast(utf8))); +} + +void sleepFor(int milliseconds) { + std::this_thread::sleep_for(std::chrono::milliseconds{milliseconds}); +} + +// Starts this program again with the given mode and arguments, without waiting for it. +void startAgain(const char* self, const char* mode, const char* argument) { +#ifdef _WIN32 + _spawnl(_P_NOWAIT, self, self, mode, argument, nullptr); +#else + if (fork() == 0) { + execl(self, self, mode, argument, static_cast(nullptr)); + _exit(127); + } +#endif +} +} // namespace + +int main(int argc, char** argv) { +#ifdef _WIN32 + // Text mode would turn each '\n' into "\r\n": the tests compare bytes. + _setmode(_fileno(stdout), _O_BINARY); + _setmode(_fileno(stderr), _O_BINARY); + std::vector utf8Arguments; + std::vector utf8Pointers; + { + int count = 0; + wchar_t** wide = ::CommandLineToArgvW(::GetCommandLineW(), &count); + for (int index = 0; wide && index < count; ++index) + utf8Arguments.push_back(toUtf8(wide[index])); + for (auto& argument : utf8Arguments) + utf8Pointers.push_back(argument.data()); + utf8Pointers.push_back(nullptr); + argc = static_cast(utf8Arguments.size()); + argv = utf8Pointers.data(); + } +#endif + const std::string mode = argc > 1 ? argv[1] : ""; + if (mode == "args") { + for (int index = 2; index < argc; ++index) + std::cout << '[' << index - 2 << ']' << argv[index] << '\n'; + return 0; + } + if (mode == "exit") + return argc > 2 ? std::atoi(argv[2]) : 0; + if (mode == "streams") { + std::cout << "to-stdout" << std::flush; + std::cerr << "to-stderr" << std::flush; + return 3; + } + if (mode == "big") { + const auto total = std::strtoull(argv[2], nullptr, 10); + const std::string block(4096, 'x'); + for (unsigned long long written = 0; written < total; written += block.size()) + std::cout.write(block.data(), static_cast(std::min(block.size(), total - written))); + return 0; + } + if (mode == "flood") { // Never stops writing to either stream. + const std::string block(65536, 'f'); + for (;;) { + std::cout.write(block.data(), static_cast(block.size())); + std::cerr.write(block.data(), static_cast(block.size())); + } + } + if (mode == "hang") { + for (;;) + sleepFor(100); + } + if (mode == "env") { + std::string value; + std::cout << (environmentValue(argv[2], value) ? value : std::string("")); + return 0; + } + if (mode == "envcount") { +#ifdef _WIN32 + int count = 0; + for (const wchar_t* entry = GetEnvironmentStringsW(); *entry; entry += wcslen(entry) + 1) + ++count; + std::cout << count; +#else + int count = 0; + for (char** entry = environ; *entry; ++entry) + ++count; + std::cout << count; +#endif + return 0; + } + if (mode == "cwd") { + std::cout << std::filesystem::current_path().generic_string(); + return 0; + } + if (mode == "cat") { + std::ifstream in(pathOf(argv[2]), std::ios::binary); + if (!in) { + std::cerr << "cannot open " << argv[2]; + return 2; + } + std::cout << in.rdbuf(); + return 0; + } + if (mode == "write") { // write FILE TEXT + std::ofstream(pathOf(argv[2]), std::ios::binary) << argv[3]; + return 0; + } + if (mode == "stdin") { + std::cout << std::distance(std::istreambuf_iterator(std::cin), {}); + return 0; + } + if (mode == "write-later") { // After two seconds: proves whether a descendant outlived a timeout. + sleepFor(2000); + std::ofstream(pathOf(argv[2])) << "alive"; + return 0; + } + if (mode == "spawn-later") { + startAgain(argv[0], "write-later", argv[2]); + for (;;) + sleepFor(100); + } + if (mode == "spawn-quick") { // Ends at once and leaves a descendant: it must not outlive the call either. + startAgain(argv[0], "write-later", argv[2]); + return 0; + } +#ifndef _WIN32 + if (mode == "dispositions") { // Whether SIGPIPE and SIGCHLD are ignored in this program. + for (const int number : {SIGPIPE, SIGCHLD}) { + struct sigaction current{}; + sigaction(number, nullptr, ¤t); + std::cout << (current.sa_handler == SIG_IGN ? "ignored" : "default") << ' '; + } + return 0; + } + if (mode == "kill-self") + raise(SIGKILL); +#endif + std::cerr << "unknown mode\n"; + return 64; +} diff --git a/test/web/jasmine-consumer/atdf-mini.xml b/test/web/jasmine-consumer/atdf-mini.xml new file mode 100644 index 00000000..b17e60ff --- /dev/null +++ b/test/web/jasmine-consumer/atdf-mini.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/test/web/jasmine-consumer/host-denied.spec.js b/test/web/jasmine-consumer/host-denied.spec.js new file mode 100644 index 00000000..7a421cfe --- /dev/null +++ b/test/web/jasmine-consumer/host-denied.spec.js @@ -0,0 +1,8 @@ +// Without PROGRAMS in webfront_add_jasmine_test, the page has no native capability, whatever it asks. +describe('A test the owner granted nothing', () => { + it('cannot run a program or create a temporary space', async () => { + await expectAsync(webFrontHost.run({program: '/bin/sh', args: ['-c', 'true']})).toBeRejectedWithError(/No native capability/); + await expectAsync(webFrontHost.makeTemp()).toBeRejectedWithError(/No native capability/); + await expectAsync(webFrontHost.programs()).toBeRejected(); + }); +}); diff --git a/test/web/jasmine-consumer/host-launch.spec.js b/test/web/jasmine-consumer/host-launch.spec.js new file mode 100644 index 00000000..1d6a0cd7 --- /dev/null +++ b/test/web/jasmine-consumer/host-launch.spec.js @@ -0,0 +1,8 @@ +// An authorized program that cannot start is reported, and the spec asserting success fails. +describe('A spec whose program cannot start', () => { + it('fails', async () => { + const [notExecutable] = await webFrontHost.programs(); + const result = await webFrontHost.run({program: notExecutable}); + expect(result.status).toBe('exited'); + }); +}); diff --git a/test/web/jasmine-consumer/host-timeout.spec.js b/test/web/jasmine-consumer/host-timeout.spec.js new file mode 100644 index 00000000..64e21d6e --- /dev/null +++ b/test/web/jasmine-consumer/host-timeout.spec.js @@ -0,0 +1,8 @@ +// A program that hits its timeout is a failing result like any other: the assertion fails the test. +describe('A spec whose program times out', () => { + it('fails', async () => { + const [probe] = await webFrontHost.programs(); + const result = await webFrontHost.run({program: probe, args: ['hang'], timeoutMs: 300}); + expect(result.status).toBe('exited'); + }); +}); diff --git a/test/web/jasmine-consumer/host-unauthorized.spec.js b/test/web/jasmine-consumer/host-unauthorized.spec.js new file mode 100644 index 00000000..6832376f --- /dev/null +++ b/test/web/jasmine-consumer/host-unauthorized.spec.js @@ -0,0 +1,4 @@ +// The run of an unauthorized program is not caught: the test, and so CTest, must fail. +describe('A spec that runs an unauthorized program', () => { + it('fails', async () => { await webFrontHost.run({program: '/bin/sh', args: ['-c', 'true']}); }); +}); diff --git a/test/web/jasmine-consumer/host.spec.js b/test/web/jasmine-consumer/host.spec.js new file mode 100644 index 00000000..c6657fd3 --- /dev/null +++ b/test/web/jasmine-consumer/host.spec.js @@ -0,0 +1,140 @@ +// webFrontHost: authorized native programs and private temporary spaces (issue #445). The only authorized program is the +// test probe; each spec states what the consumer relies on. +describe('A native program run from the specs', () => { + const host = webFrontHost; + let probe; + beforeAll(async () => { [probe] = await host.programs(); }); + const run = (args, options = {}) => host.run({program: probe, args, ...options}); + + it('receives spaces, Unicode and shell metacharacters literally', async () => { + const args = ['two words', '', 'a;b|c&d $HOME `id` $(id) *', '"quoted"', 'back\\slash\\', 'café € \u{1F600}', '--flag=x y']; + const result = await run(['args', ...args]); + expect(result.status).toBe('exited'); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(args.map((arg, index) => `[${index}]${arg}\n`).join('')); + }); + + it('reports a non-zero exit code with both streams', async () => { + const result = await run(['streams']); + expect(result).toEqual(jasmine.objectContaining({status: 'exited', exitCode: 3, stdout: 'to-stdout', stderr: 'to-stderr'})); + expect(result.error).toBe(''); + expect(result.stdoutTruncated).toBeFalse(); + }); + + it('is killed at its timeout and says so', async () => { + const result = await run(['hang'], {timeoutMs: 300}); + expect(result.status).toBe('timeout'); + expect(result.durationMs).toBeLessThan(5000); + }); + + it('is killed on cancellation and says so', async () => { + const controller = new AbortController(); + setTimeout(() => controller.abort(), 200); + const result = await run(['hang'], {signal: controller.signal}); + expect(result.status).toBe('cancelled'); + await expectAsync(run(['exit'], {signal: controller.signal})).withContext('rejection 1').toBeRejected(); + }); + + it('has its output bounded, with the truncation reported', async () => { + const result = await run(['big', '5000000'], {maxOutputBytes: 100000}); + expect(result.status).toBe('exited'); + expect(result.stdout.length).toBe(100000); + expect(result.stdoutTruncated).toBeTrue(); + expect(result.stderrTruncated).toBeFalse(); + const large = await run(['big', '3000000']); // The default bound is 1 MiB. + expect(large.stdout.length).toBe(1048576); + expect(large.stdoutTruncated).toBeTrue(); + }, 30000); + + it('sees only the environment it is given, or the inherited one on request', async () => { + expect((await run(['env', 'CHOSEN'], {env: {CHOSEN: 'café'}})).stdout).toBe('café'); + expect((await run(['env', 'PATH'])).stdout).toBe(''); + expect((await run(['env', 'PATH'], {inheritEnv: true})).stdout).not.toBe(''); + }); + + it('does not outlive a timeout through its descendants', async () => { + await host.withTemp(async dir => { + const marker = `${dir}/descendant.txt`; + expect((await run(['spawn-later', marker], {timeoutMs: 500})).status).toBe('timeout'); + await new Promise(resolve => setTimeout(resolve, 3000)); + expect((await run(['cat', marker])).exitCode).toBe(2); // Never written: the descendant was killed. + }); + }, 20000); + + it('reports an authorized program that cannot start, instead of an exit code', async () => { + const [, data] = await host.programs(); // A file the owner listed that is not executable. + const result = await host.run({program: data}); + expect(result.status).toBe('launchFailed'); + expect(result.error).not.toBe(''); + }); + + it('refuses any program the owner did not authorize', async () => { + for (const program of ['/bin/sh', 'cmd.exe', 'host_probe', '', `${probe}-other`]) + await expectAsync(host.run({program, args: ['-c', 'true']})).withContext('rejection 2').toBeRejectedWithError(/not authorized/); + await expectAsync(host.run({program: probe, shell: true})).withContext('rejection 3').toBeRejectedWithError(/Unknown run option/); + await expectAsync(host.run({program: probe, cwd: '/'})).withContext('rejection 4').toBeRejected(); + }); +}); + +describe('The temporary spaces of the specs', () => { + const host = webFrontHost; + it('are private, hold Unicode names and large files, and are removed', async () => { + let first; + await host.withTemp(async dir => { + first = dir; + const [probe] = await host.programs(); + const text = 'café '.repeat(40000); // Larger than a bridge chunk. + await host.writeFile(`${dir}/espace café.json`, text); + expect(await host.readText(`${dir}/espace café.json`)).toBe(text); + await host.writeFile(`${dir}/empty`, ''); + expect((await host.readFile(`${dir}/empty`)).length).toBe(0); + const echoed = await host.run({program: probe, args: ['cat', `${dir}/espace café.json`], cwd: dir}); + expect(echoed.stdout).toBe(text); + const where = await host.run({program: probe, args: ['cwd'], cwd: dir}); + expect(where.stdout.endsWith(dir.split(/[\\/]/).pop())).toBeTrue(); + await expectAsync(host.writeFile(`${dir}/../escape.txt`, 'x')).withContext('rejection 5').toBeRejected(); + }); + await expectAsync(host.writeFile(`${first}/late.txt`, 'x')).withContext('rejection 6').toBeRejected(); // The space no longer exists. + const [one, two] = await Promise.all([host.makeTemp(), host.makeTemp()]); + expect(one).not.toBe(two); + await host.removeTemp(one); + await host.removeTemp(two); + await expectAsync(host.removeTemp(one)).withContext('rejection 7').toBeRejected(); + }); +}); + +// Recipe: an ATDF (XML) file becomes the JSON description a native tool reads. DOMParser exists in the page the specs +// run in (not in a wf Worker); the result is written to a private space and handed to the native program. +describe('Converting a device description before testing the native tool on it', () => { + const toDescription = xml => { + const document = new DOMParser().parseFromString(xml, 'application/xml'); + if (document.querySelector('parsererror')) throw new Error('Invalid ATDF'); + const device = document.querySelector('device'); + return { + name: device.getAttribute('name'), + architecture: device.getAttribute('architecture'), + vectors: [...device.querySelectorAll('interrupts > interrupt')].map(node => ({ + index: Number(node.getAttribute('index')), name: node.getAttribute('name')})), + }; + }; + + it('writes a fixture-derived JSON file and the native tool reads exactly it', async () => { + const description = toDescription(await (await fetch('/atdf-mini.xml')).text()); + expect(description.vectors.map(vector => vector.name)).toEqual(['RESET', 'INT0', 'INT1']); + const [probe] = await webFrontHost.programs(); + await webFrontHost.withTemp(async dir => { + const file = `${dir}/chip.json`; + await webFrontHost.writeFile(file, JSON.stringify(description)); + const result = await webFrontHost.run({program: probe, args: ['cat', file], cwd: dir}); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual(description); + const missing = await webFrontHost.run({program: probe, args: ['cat', `${dir}/missing.json`]}); + expect(missing.exitCode).toBe(2); // A failing native run is a result, asserted like any other. + expect(missing.stderr).toContain('cannot open'); + }); + }); + + it('rejects an invalid description instead of passing it on', () => { + expect(() => toDescription('')).toThrowError('Invalid ATDF'); + }); +});