diff --git a/.github/docker/linux-ci.Dockerfile b/.github/docker/linux-ci.Dockerfile index 6d071732..5a80f0ba 100644 --- a/.github/docker/linux-ci.Dockerfile +++ b/.github/docker/linux-ci.Dockerfile @@ -5,19 +5,21 @@ FROM ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 LABEL org.opencontainers.image.source="https://github.com/ambroise-leclerc/WebFront" -LABEL org.opencontainers.image.description="WebFront CI: GCC 16, WebKitGTK 6, lcov and Xvfb on Ubuntu 26.04" +LABEL org.opencontainers.image.description="WebFront CI: GCC 16, WebKitGTK 6, OpenSSL, lcov and Xvfb on Ubuntu 26.04" ENV DEBIAN_FRONTEND=noninteractive # sudo: the composite actions of the repository call it, as they do on a hosted runner. build-essential: the CTest # fixtures configure sub-projects with CMake's default generator and compiler, which a hosted runner also provides. +# libssl-dev: the signature verification of the updater tests (OpenSSL libcrypto). +# file: CPackDeb needs it to list the dependencies of the package ApplicationPackageConfiguration builds. # libjson-xs-perl: a recommendation of lcov, which falls back to a pure-Perl parser about eight times slower without it. RUN apt-get update \ && apt-get install -y --no-install-recommends -o Acquire::Retries=3 \ ca-certificates curl git sudo tar xz-utils build-essential \ ninja-build pkg-config python3 \ - gcc-16 g++-16 libwebkitgtk-6.0-dev lcov libjson-xs-perl \ - xvfb xauth time \ + gcc-16 g++-16 libwebkitgtk-6.0-dev libssl-dev lcov libjson-xs-perl \ + xvfb xauth time file \ && rm -rf /var/lib/apt/lists/* # The workspace is mounted from the host runner and owned by another user: let git (and the tests that call it) read it. diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index c4b53030..b124a5fa 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -131,7 +131,7 @@ jobs: build_type: Debug test_env: {WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: '1'} # GCC 16 compiles the optional C++26 reflection layer of the forms (#383): its tests must not be skipped here. - options: -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_ENABLE_COVERAGE=ON -DWEBFRONT_REQUIRE_REFLECTION_TESTS=ON + options: -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_ENABLE_COVERAGE=ON -DWEBFRONT_REQUIRE_REFLECTION_TESTS=ON -DWEBFRONT_REQUIRE_UPDATER_TESTS=ON runs-on: ${{ matrix.os }} # Only the Linux job runs in the prebuilt toolchain image; an empty value means no container. container: ${{ matrix.use_image && fromJSON(format('{{"image":"{0}","credentials":{{"username":"{1}","password":"{2}"}},"options":"--shm-size=1g"}}', needs.linux-image.outputs.image, github.actor, github.token)) || '' }} @@ -279,6 +279,36 @@ jobs: -DREPEAT=${{ (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests) && inputs.desktop_passes || ((github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master')) && '3' || '1') }} '-DLABEL_EXCLUDE=${{ (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests)) && 'none' || (env.WEBFRONT_CONFIGURATION == 'true' && '^(portability|fast)$' || '^(portability|fast|configuration)$') }}' -P test/cmake/RunTestSuite.cmake + # The installer of the embedded Life example (docs/DISTRIBUTION.md), from the provider that the developer journey of the + # tests above wrote with wf embed: built, installed, checked and removed on this runner. + - name: Ensure NSIS + if: runner.os == 'Windows' + shell: pwsh + run: | + if (-not (Test-Path "${env:ProgramFiles(x86)}/NSIS/makensis.exe")) { choco install nsis -y --no-progress } + if (-not (Test-Path "${env:ProgramFiles(x86)}/NSIS/makensis.exe")) { throw 'NSIS is not available' } + - name: Package the Life example, install it and remove it + shell: bash + run: | + set -euo pipefail + # Forward slashes on Windows too. The target `package` runs CMake's cpack (Chocolatey ships another `cpack`). + workspace="$(cygpath -m "$GITHUB_WORKSPACE" 2>/dev/null || pwd)" + cmake -S examples/life/package -B build-life -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DWEBFRONT_LIFE_ASSETS="$workspace/build/jp/generated/LifeUI.hpp" -DENABLE_CACHE=OFF \ + -DCMAKE_CXX_COMPILER_LAUNCHER=sccache ${{ matrix.options }} + cmake --build build-life --parallel 4 + cmake --build build-life --target package + cmake -DPACKAGE_DIR="$workspace/build-life" -P test/cmake/CheckLifeInstaller.cmake + - name: Retain the Life installer + uses: actions/upload-artifact@v4 + with: + name: life-installer-${{ runner.os }} + path: | + build-life/webfront-life-*.deb + build-life/webfront-life-*.dmg + build-life/webfront-life-*.exe + retention-days: 7 + if-no-files-found: error # Nothing consumes the capture of a pull request, which only lists it in its log: it runs on a push to develop or master # and in the full tier. The pull request still builds and runs the instrumented tests. - name: Collect coverage @@ -401,6 +431,65 @@ jobs: shell: bash run: ctest --test-dir build -C Release -L portability --output-on-failure --no-tests=error + # find_package(WebFront) from the vcpkg overlay port and from the Conan recipe (docs/DISTRIBUTION.md): each installs the + # package, with the network it needs for the pinned archives, then a consumer configures and builds Hello World with the + # public network cut. Part of the portability tier. + packages: + if: github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.base_ref == 'master') || (github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests) + name: packages (${{ matrix.manager }}) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + VCPKG_REVISION: 9eec002df1cd109f8f104cd966a763daf9751489 # release 2026.10.16 + strategy: + fail-fast: false + matrix: + manager: [vcpkg, conan] + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/remove-node + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + - name: Install Ninja + run: sudo apt-get update && sudo apt-get install -y ninja-build + - name: Package with vcpkg + if: matrix.manager == 'vcpkg' + run: | + git clone --filter=blob:none https://github.com/microsoft/vcpkg.git "$RUNNER_TEMP/vcpkg" + git -C "$RUNNER_TEMP/vcpkg" checkout --detach "$VCPKG_REVISION" + "$RUNNER_TEMP/vcpkg/bootstrap-vcpkg.sh" -disableMetrics + "$RUNNER_TEMP/vcpkg/vcpkg" install webfront --overlay-ports=cmake/packaging/vcpkg --binarysource=clear + echo "TOOLCHAIN=$RUNNER_TEMP/vcpkg/scripts/buildsystems/vcpkg.cmake" >> "$GITHUB_ENV" + - name: Package with Conan + if: matrix.manager == 'conan' + run: | + python3 -m venv "$RUNNER_TEMP/conan" + "$RUNNER_TEMP/conan/bin/pip" install conan==2.35.0 + conan="$RUNNER_TEMP/conan/bin/conan" + "$conan" profile detect + "$conan" create cmake/packaging/conan -s compiler.cppstd=23 --no-remote + "$conan" install test/cmake/package-consumer -c tools.cmake.cmaketoolchain:user_presets= -s compiler.cppstd=23 -s build_type=Release --no-remote --output-folder="$RUNNER_TEMP/conan-consumer" + echo "TOOLCHAIN=$RUNNER_TEMP/conan-consumer/conan_toolchain.cmake" >> "$GITHUB_ENV" + - name: Cut the public network + run: | + sudo iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + sudo iptables -A OUTPUT ! -o lo -j REJECT + sudo ip6tables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + sudo ip6tables -A OUTPUT ! -o lo -j REJECT + - name: Build Hello World with find_package(WebFront), offline + run: | + cmake -S test/cmake/package-consumer -B build-consumer -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \ + -DHELLO_WORLD_SOURCE="$PWD/examples/hello-world/HelloWorld.cpp" + cmake --build build-consumer --parallel 4 + test -x build-consumer/HelloWorld + - name: Restore the network + if: always() + run: | + sudo iptables -F OUTPUT + sudo ip6tables -F OUTPUT + # GCC 13 on Linux aarch64 (#548): the default compiler of Ubuntu 24.04, JetPack 7.2 and Yocto Scarthgap, on the architecture of # the Jetson boards. It builds the library, the examples and every test with the hosted ubuntu-24.04-arm image, then runs the fast # tier. Warnings are not errors here: libstdc++ 13 reports false -Wnull-dereference positives (#526), so -Werror stays with the diff --git a/AGENTS.md b/AGENTS.md index 803739b4..cfe499d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `include/webfront/weblink/`: bridge message encoding and routing. - `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together). - `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters. +- `docs/DISTRIBUTION.md`: `find_package(WebFront)` (`cmake/WebFrontInstall.cmake`, pins in `cmake/WebFrontDependencies.cmake`), the vcpkg port and Conan recipe in `cmake/packaging/`, `webfront_package()`, the SBOM and the optional updater `include/webfront/components/update/` (ADR-028; never write cryptography there). - `examples/`: the default build includes Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). The standalone [PTY example](docs/PTY.md) has its own CMake entry point. - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. - `js/developer/starters/`: the sources of the `app` starter and `agent-guide.md`, the `AGENTS.md` that `wf create` puts beside a starter and that `webfront_write_agent_guide()` (`cmake/WebFrontAgentGuide.cmake`) writes in a consuming project. diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e7f8edd..f9c796ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -115,8 +115,25 @@ if(WEBFRONT_IS_TOP_LEVEL) include(StaticAnalyzers) endif() -include(CPM) -CPMAddPackage("gh:ambroise-leclerc/stdnet#8005774eabcba7e73188c02d2eeca2ff43c4ee3a") +include(WebFrontDependencies) +# A package build (vcpkg, Conan) or a machine without network access gives the sources of the pinned dependencies; nothing is +# then downloaded, CPM included, unless a downloaded engine (CEF, the WebView2 SDK) is enabled (docs/DISTRIBUTION.md). +set(WEBFRONT_STDNET_SOURCE_DIR "" CACHE PATH "Sources of the pinned stdnet, instead of downloading them") +set(WEBFRONT_STDEXEC_SOURCE_DIR "" CACHE PATH "Sources of the pinned stdexec, instead of downloading them") +if(NOT WEBFRONT_STDNET_SOURCE_DIR OR WEBFRONT_EMBED_CEF OR (WEBFRONT_EMBED_WEBVIEW2 AND NOT WEBFRONT_WEBVIEW2_SDK_DIR)) + include(CPM) +endif() +if(WEBFRONT_STDEXEC_SOURCE_DIR) + set(FETCHCONTENT_SOURCE_DIR_STDEXEC "${WEBFRONT_STDEXEC_SOURCE_DIR}") +endif() +# EXCLUDE_FROM_ALL: the install rules of stdnet would copy its headers beside WebFront's; WebFrontInstall.cmake installs them. +if(WEBFRONT_STDNET_SOURCE_DIR) + add_subdirectory("${WEBFRONT_STDNET_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/stdnet" EXCLUDE_FROM_ALL) + set(stdnet_SOURCE_DIR "${WEBFRONT_STDNET_SOURCE_DIR}") +else() + CPMAddPackage(URI "gh:ambroise-leclerc/stdnet#${WEBFRONT_STDNET_REVISION}" EXCLUDE_FROM_ALL YES) +endif() +set(WEBFRONT_USAGE_TARGET WebFront) webfront_include_frontend_support() include(ModuleScan) @@ -161,6 +178,10 @@ include(WebFrontAgentGuide) webfront_announce_agent_support() # webfront_write_sbom(): an application's SPDX bill of materials (docs/DISTRIBUTION.md). include(WebFrontSbom) +# webfront_package(): an application's installer with CPack (docs/DISTRIBUTION.md). +include(WebFrontPackage) +# webfront_use_updater(): the optional verified updater, outside the core (docs/DISTRIBUTION.md). +include(WebFrontUpdater) if(WEBFRONT_ENABLE_TESTING OR WEBFRONT_ENABLE_FUZZING) include(TestHardening) @@ -185,3 +206,9 @@ endif() if(WEBFRONT_BUILD_EXAMPLES) add_subdirectory(examples) endif() + +# install() and find_package(WebFront): an embedding project owns its own installation (docs/DISTRIBUTION.md). +option(WEBFRONT_INSTALL "Generate the install rules of the WebFront package" ${WEBFRONT_IS_TOP_LEVEL}) +if(WEBFRONT_INSTALL) + include(WebFrontInstall) +endif() diff --git a/README.md b/README.md index be54c8f6..c266a65e 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,8 @@ target_link_libraries(MyApp PRIVATE WebFront::WebFront) As a subproject, examples and tests are off by default and compiler settings do not leak into your targets. `WEBFRONT_BUILD_EXAMPLES=OFF` disables examples in a standalone build too. +An installed WebFront (`cmake --install`, the vcpkg overlay port or the Conan recipe) is used with `find_package(WebFront CONFIG REQUIRED)`. [Distributing an application](docs/DISTRIBUTION.md) covers it, installers (`webfront_package()`), the bill of materials and verified updates. +
GCC 16 and C++ module scanning diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index dcbc2c4d..ff188272 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -7,11 +7,14 @@ endif() if(CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS "13.3") message(FATAL_ERROR "WEBFRONT_EMBED_WKWEBVIEW requires CMAKE_OSX_DEPLOYMENT_TARGET >= 13.3") endif() +if(NOT DEFINED WEBFRONT_USAGE_TARGET) + set(WEBFRONT_USAGE_TARGET WebFront) +endif() find_library(WEBFRONT_COCOA_FRAMEWORK Cocoa REQUIRED) find_library(WEBFRONT_WEBKIT_FRAMEWORK WebKit REQUIRED) -target_compile_definitions(WebFront INTERFACE WEBFRONT_EMBED_WKWEBVIEW) -target_compile_options(WebFront INTERFACE "$<$:-fblocks>") -target_link_libraries(WebFront INTERFACE "${WEBFRONT_COCOA_FRAMEWORK}" "${WEBFRONT_WEBKIT_FRAMEWORK}") +target_compile_definitions(${WEBFRONT_USAGE_TARGET} INTERFACE WEBFRONT_EMBED_WKWEBVIEW) +target_compile_options(${WEBFRONT_USAGE_TARGET} INTERFACE "$<$:-fblocks>") +target_link_libraries(${WEBFRONT_USAGE_TARGET} INTERFACE "${WEBFRONT_COCOA_FRAMEWORK}" "${WEBFRONT_WEBKIT_FRAMEWORK}") function(webfront_add_wkwebview_tests) get_filename_component(webtest_source_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../test/web" ABSOLUTE) diff --git a/cmake/WebFrontAgentGuide.cmake b/cmake/WebFrontAgentGuide.cmake index b73d3dff..d79b34c3 100644 --- a/cmake/WebFrontAgentGuide.cmake +++ b/cmake/WebFrontAgentGuide.cmake @@ -37,6 +37,9 @@ function(webfront_write_agent_guide) cmake_path(NORMAL_PATH CMAKE_CURRENT_FUNCTION_LIST_DIR OUTPUT_VARIABLE here) set(source "${here}/../js/developer/starters/agent-guide.md") cmake_path(NORMAL_PATH source) + if(NOT EXISTS "${source}") # the installed package keeps the guide beside this file + set(source "${here}/agent-guide.md") + endif() set(destination "${ARG_DIRECTORY}/${ARG_NAME}") # EXISTS follows links: a dangling link is a file somebody placed there too. if(EXISTS "${destination}" OR IS_SYMLINK "${destination}") diff --git a/cmake/WebFrontConfig.cmake.in b/cmake/WebFrontConfig.cmake.in new file mode 100644 index 00000000..9b0bdab6 --- /dev/null +++ b/cmake/WebFrontConfig.cmake.in @@ -0,0 +1,210 @@ +# find_package(WebFront): the installed header-only library, its pinned stdnet and stdexec, and the public CMake helpers. +# Nothing is downloaded. Components select an embedded frontend (WebKitGTK, WKWebView, WebView2) on top of the system browser; +# WebView2 needs WEBFRONT_WEBVIEW2_SDK_DIR, an extracted Microsoft.Web.WebView2 NuGet package. CEF is not part of the package. +cmake_minimum_required(VERSION 3.31) + +# CMAKE_INSTALL_INCLUDEDIR of the installation. The prefix is found from this file, whatever directory under it the package +# manager chose for it. +set(_webfront_includedir "@CMAKE_INSTALL_INCLUDEDIR@") +set(_webfront_prefix "${CMAKE_CURRENT_LIST_DIR}") +if(IS_ABSOLUTE "${_webfront_includedir}") + set(_webfront_include "${_webfront_includedir}") + get_filename_component(_webfront_prefix "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE) +else() + foreach(_webfront_level RANGE 8) + if(EXISTS "${_webfront_prefix}/${_webfront_includedir}/webfront/WebFront.hpp") + break() + endif() + get_filename_component(_webfront_prefix "${_webfront_prefix}" DIRECTORY) + endforeach() + set(_webfront_include "${_webfront_prefix}/${_webfront_includedir}") +endif() +if(NOT EXISTS "${_webfront_include}/webfront/WebFront.hpp") + set(WebFront_FOUND FALSE) + set(WebFront_NOT_FOUND_MESSAGE "The headers of WebFront were not found from ${CMAKE_CURRENT_LIST_DIR}") + return() +endif() + +include(CMakeFindDependencyMacro) +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_dependency(Threads) +# The WebFrontBdd package is another component, absent from an installation of the component WebFront alone and from the +# install rules of a project that embeds WebFront: its target is then defined here, from the same headers. +find_package(WebFrontBdd CONFIG QUIET HINTS "${_webfront_prefix}" "${_webfront_prefix}/@CMAKE_INSTALL_LIBDIR@/cmake/WebFrontBdd") +if(NOT TARGET WebFront::Bdd) + add_library(WebFront::Bdd INTERFACE IMPORTED GLOBAL) + target_compile_features(WebFront::Bdd INTERFACE cxx_std_23) + target_include_directories(WebFront::Bdd INTERFACE "${_webfront_include}") + target_link_libraries(WebFront::Bdd INTERFACE Threads::Threads) +endif() +if(NOT COMMAND webfront_bdd_discover_tests) + include("${CMAKE_CURRENT_LIST_DIR}/WebFrontBdd.cmake") +endif() + +if(NOT TARGET WebFront::WebFront) + # stdnet and std::execution, unless the project already provides them. + if(NOT TARGET stdnet::stdnet) + add_library(stdnet::stdnet INTERFACE IMPORTED GLOBAL) + target_include_directories(stdnet::stdnet INTERFACE "${_webfront_include}/webfront-deps/stdnet") + target_compile_features(stdnet::stdnet INTERFACE cxx_std_23) + target_link_libraries(stdnet::stdnet INTERFACE Threads::Threads) + if(WIN32) + target_link_libraries(stdnet::stdnet INTERFACE ws2_32) + endif() + if(MSVC) + target_compile_options(stdnet::stdnet INTERFACE "$<$:/Zc:__cplusplus;/Zc:preprocessor;/EHsc>") + endif() + # Probed in the mode the consumer compiles in: its flag or CMAKE_CXX_STANDARD, at least the C++23 the targets require. + include(CheckCXXSourceCompiles) + include(CMakePushCheckState) + cmake_push_check_state(RESET) + set(_webfront_standard "${CMAKE_CXX_STANDARD}") + if(NOT _webfront_standard AND NOT CMAKE_CXX_FLAGS MATCHES "(^| )[-/]std[=:]") + set(_webfront_standard "${CMAKE_CXX_STANDARD_DEFAULT}") + endif() + set(_webfront_consumer_standard "${CMAKE_CXX_STANDARD}") + if(_webfront_standard MATCHES "^(98|11|14|17|20)$") + set(CMAKE_CXX_STANDARD 23) + endif() + # One result per mode: another one probes again. + string(MD5 _webfront_mode "${CMAKE_CXX_STANDARD};${CMAKE_CXX_FLAGS}") + check_cxx_source_compiles(" +#include +#if !defined(__cpp_lib_senders) +#error no senders +#endif +int main() {}" WEBFRONT_HAS_STD_SENDERS_${_webfront_mode}) + set(CMAKE_CXX_STANDARD "${_webfront_consumer_standard}") + if(_webfront_consumer_standard STREQUAL "") + unset(CMAKE_CXX_STANDARD) + endif() + cmake_pop_check_state() + set(WEBFRONT_HAS_STD_SENDERS "${WEBFRONT_HAS_STD_SENDERS_${_webfront_mode}}") + if(NOT WEBFRONT_HAS_STD_SENDERS) + if(NOT TARGET STDEXEC::stdexec) + if(NOT EXISTS "${_webfront_include}/webfront-deps/stdexec/stdexec/execution.hpp") + set(WebFront_FOUND FALSE) + set(WebFront_NOT_FOUND_MESSAGE + "This WebFront was packaged without stdexec, for a standard library with std::execution, which this compiler lacks") + return() + endif() + add_library(STDEXEC::stdexec INTERFACE IMPORTED GLOBAL) + target_include_directories(STDEXEC::stdexec SYSTEM INTERFACE "${_webfront_include}/webfront-deps/stdexec") + target_compile_features(STDEXEC::stdexec INTERFACE cxx_std_20) + endif() + target_link_libraries(stdnet::stdnet INTERFACE STDEXEC::stdexec) + target_compile_definitions(stdnet::stdnet INTERFACE STDNET_USE_STDEXEC=1) + endif() + endif() + + add_library(WebFront::WebFront INTERFACE IMPORTED GLOBAL) + set_property(GLOBAL PROPERTY WEBFRONT_INSTALLED_TARGET ON) + target_compile_features(WebFront::WebFront INTERFACE cxx_std_23) + target_include_directories(WebFront::WebFront INTERFACE "${_webfront_include}") + target_link_libraries(WebFront::WebFront INTERFACE stdnet::stdnet Threads::Threads ${CMAKE_DL_LIBS}) + if(WIN32) + target_link_libraries(WebFront::WebFront INTERFACE shell32 bcrypt) + if(NOT DEFINED WINVER AND NOT DEFINED _WIN32_WINNT) + target_compile_definitions(WebFront::WebFront INTERFACE WINVER=0x0A00 _WIN32_WINNT=0x0A00) + endif() + if(MSVC) + target_compile_options(WebFront::WebFront INTERFACE "$<$:/bigobj>") + endif() + endif() + if(WEBFRONT_DISTRIBUTION) + target_compile_definitions(WebFront::WebFront INTERFACE WEBFRONT_DISTRIBUTION=1) + endif() +endif() + +# Frontends are set up outside the block above: a later find_package may request one that an earlier call did not. +include("${CMAKE_CURRENT_LIST_DIR}/Frontends.cmake") +get_property(_webfront_ours GLOBAL PROPERTY WEBFRONT_INSTALLED_TARGET) +if(_webfront_ours) + foreach(_webfront_component IN ITEMS WebKitGTK WKWebView WebView2 CEF) + string(TOUPPER "${_webfront_component}" _webfront_upper) + get_property(_webfront_applied GLOBAL PROPERTY WEBFRONT_INSTALLED_FRONTEND_${_webfront_component}) + set(_webfront_requested FALSE) + if(_webfront_component IN_LIST WebFront_FIND_COMPONENTS) + set(_webfront_requested TRUE) + # An optional component that cannot be had here is left alone: it is reported not found below. + if(NOT _webfront_applied AND NOT WebFront_FIND_REQUIRED_${_webfront_component}) + set(_webfront_available OFF) + _webfront_load_frontends() + webfront_frontend_supports_platform(${_webfront_component} _webfront_supported) + if(_webfront_supported AND NOT _webfront_component STREQUAL "CEF") + webfront_probe_native_frontend(${_webfront_component} _webfront_available _webfront_reason) + endif() + if(_webfront_component STREQUAL "WebView2" AND NOT WEBFRONT_WEBVIEW2_SDK_DIR) + set(_webfront_available OFF) + endif() + set(_webfront_requested ${_webfront_available}) + endif() + endif() + if(_webfront_applied OR _webfront_requested) + set(WEBFRONT_EMBED_${_webfront_upper} ON) + endif() + endforeach() + if(WEBFRONT_EMBED_CEF) + unset(WEBFRONT_EMBED_CEF) + set(WebFront_FOUND FALSE) + set(WebFront_NOT_FOUND_MESSAGE "CEF is not part of the installed WebFront package: use add_subdirectory or CPM") + return() + endif() + if(WEBFRONT_EMBED_WEBVIEW2 AND NOT WEBFRONT_WEBVIEW2_SDK_DIR) + unset(WEBFRONT_EMBED_WEBVIEW2) + set(WebFront_FOUND FALSE) + set(WebFront_NOT_FOUND_MESSAGE "WebView2 needs WEBFRONT_WEBVIEW2_SDK_DIR, an extracted Microsoft.Web.WebView2 package") + return() + endif() + webfront_declare_frontend_options() + set(WEBFRONT_USAGE_TARGET WebFront::WebFront) + foreach(_webfront_component IN ITEMS WebKitGTK WKWebView WebView2) + string(TOUPPER "${_webfront_component}" _webfront_upper) + get_property(_webfront_applied GLOBAL PROPERTY WEBFRONT_INSTALLED_FRONTEND_${_webfront_component}) + if(WEBFRONT_EMBED_${_webfront_upper} AND NOT _webfront_applied) + _webfront_load_frontends() + include("${WEBFRONT_FRONTEND_${_webfront_component}_SUPPORT_FILE}") + webfront_validate_frontend_hooks("${_webfront_component}") + set_property(GLOBAL PROPERTY WEBFRONT_INSTALLED_FRONTEND_${_webfront_component} ON) + endif() + endforeach() +endif() +foreach(_webfront_component IN LISTS WebFront_FIND_COMPONENTS) + set(_webfront_set_up FALSE) + if(_webfront_component MATCHES "^(WebKitGTK|WKWebView|WebView2)$") + # A WebFront::WebFront from add_subdirectory has the frontends its own configuration enabled. + get_property(_webfront_applied GLOBAL PROPERTY WEBFRONT_INSTALLED_FRONTEND_${_webfront_component}) + get_property(_webfront_enabled GLOBAL PROPERTY WEBFRONT_FRONTEND_${_webfront_component}_ENABLED) + if(_webfront_applied OR (NOT _webfront_ours AND _webfront_enabled)) + set(_webfront_set_up TRUE) + endif() + endif() + set(WebFront_${_webfront_component}_FOUND ${_webfront_set_up}) + if(NOT _webfront_set_up AND WebFront_FIND_REQUIRED_${_webfront_component}) + set(WebFront_FOUND FALSE) + set(WebFront_NOT_FOUND_MESSAGE "WebFront component '${_webfront_component}' is unknown or not set up") + return() + endif() +endforeach() + +set_property(GLOBAL PROPERTY WEBFRONT_INSTALLED_INCLUDE "${_webfront_include}") +include("${CMAKE_CURRENT_LIST_DIR}/ModuleScan.cmake") +set(WEBFRONT_PARENT_CMP0155 "") +webfront_check_module_scan() +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontEmbedDirectory.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontDistribution.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontAgentGuide.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontPackage.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontUpdater.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontSbom.cmake") +# The installed headers are the sources the build uses: their revisions were recorded at installation. +set(_webfront_sbom_root "${_webfront_include}/webfront" CACHE INTERNAL "The WebFront sources") +set(stdnet_SOURCE_DIR "${_webfront_include}/webfront-deps/stdnet") +set_property(GLOBAL PROPERTY "WEBFRONT_SBOM_REVISION:${_webfront_sbom_root}" "@_webfront_revision@") +set_property(GLOBAL PROPERTY "WEBFRONT_SBOM_REVISION:${stdnet_SOURCE_DIR}" "@_webfront_stdnet_revision@") +set_property(GLOBAL PROPERTY WEBFRONT_SBOM_STDEXEC_SOURCE "") +if(TARGET STDEXEC::stdexec AND EXISTS "${_webfront_include}/webfront-deps/stdexec") + set(_webfront_stdexec "${_webfront_include}/webfront-deps/stdexec") + set_property(GLOBAL PROPERTY WEBFRONT_SBOM_STDEXEC_SOURCE "${_webfront_stdexec}") + set_property(GLOBAL PROPERTY "WEBFRONT_SBOM_REVISION:${_webfront_stdexec}" "@_webfront_stdexec_revision@") +endif() diff --git a/cmake/WebFrontDependencies.cmake b/cmake/WebFrontDependencies.cmake new file mode 100644 index 00000000..f644ce68 --- /dev/null +++ b/cmake/WebFrontDependencies.cmake @@ -0,0 +1,6 @@ +# The pinned revisions of the C++ dependencies of WebFront: the build, the installed package (WebFrontInstall.cmake) and the +# vcpkg port and Conan recipe use these (the PackagePins CTest case checks the latter two). stdexec is the revision that this +# stdnet fetches by default (its STDNET_STDEXEC_TAG); change them together. +include_guard(GLOBAL) +set(WEBFRONT_STDNET_REVISION 8005774eabcba7e73188c02d2eeca2ff43c4ee3a) +set(WEBFRONT_STDEXEC_REVISION 7df6de8eeec667c8adce66fa5a3e17cfd6849e48) diff --git a/cmake/WebFrontEmbedDirectory.cmake b/cmake/WebFrontEmbedDirectory.cmake index 8b0e64da..69d27b5c 100644 --- a/cmake/WebFrontEmbedDirectory.cmake +++ b/cmake/WebFrontEmbedDirectory.cmake @@ -86,7 +86,12 @@ wchar_t;while;xor;xor_eq;") endforeach() set(declared "(class|struct|union|concept|enum)[ \t]+(${names})([^A-Za-z0-9_]|$)") string(APPEND declared "|using[ \t]+(${names})[ \t]*=|namespace[ \t]+([A-Za-z0-9_]+::)*${ARG_CLASS}([^A-Za-z0-9_:]|$)") - file(GLOB_RECURSE headers "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../include/webfront/*.hpp") + # An installed package says where its headers are (WebFrontConfig.cmake). + get_property(include_dir GLOBAL PROPERTY WEBFRONT_INSTALLED_INCLUDE) + if(NOT include_dir) + set(include_dir "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../include") + endif() + file(GLOB_RECURSE headers "${include_dir}/webfront/*.hpp") foreach(header IN LISTS headers) file(STRINGS "${header}" hits REGEX "${declared}" LIMIT_COUNT 1) if(hits) diff --git a/cmake/WebFrontInstall.cmake b/cmake/WebFrontInstall.cmake new file mode 100644 index 00000000..d9f820ed --- /dev/null +++ b/cmake/WebFrontInstall.cmake @@ -0,0 +1,63 @@ +# The install rules of the WebFront package, so that find_package(WebFront) works offline (docs/DISTRIBUTION.md). Included by +# the top-level CMakeLists.txt when WEBFRONT_INSTALL is ON. The headers of the pinned stdnet and stdexec are installed in +# include/webfront-deps/, apart from any copy of them that another package provides. +include_guard(GLOBAL) +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +set(_webfront_cmake_dir "${CMAKE_INSTALL_DATADIR}/cmake/WebFront") +set(_webfront_license_dir "${CMAKE_INSTALL_DATADIR}/doc/WebFront") +set(_webfront_root "${CMAKE_CURRENT_LIST_DIR}/..") + +install(DIRECTORY "${_webfront_root}/include/webfront" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" COMPONENT WebFront + FILES_MATCHING PATTERN "*.hpp" PATTERN "*.h") +install(DIRECTORY "${stdnet_SOURCE_DIR}/include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/webfront-deps/stdnet" COMPONENT WebFront) +install(FILES "${stdnet_SOURCE_DIR}/LICENSE" DESTINATION "${_webfront_license_dir}" RENAME stdnet-LICENSE COMPONENT WebFront) +install(FILES "${_webfront_root}/LICENSE" DESTINATION "${_webfront_license_dir}" COMPONENT WebFront) + +# stdexec is absent when the compiler's standard library has senders: the package then needs such a library too. +set(_webfront_stdexec_source "") +if(TARGET stdnet_stdexec) + include(FetchContent) + FetchContent_GetProperties(stdexec SOURCE_DIR _webfront_stdexec_source) + install(DIRECTORY "${_webfront_stdexec_source}/include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/webfront-deps/stdexec" + COMPONENT WebFront) + install(FILES "${_webfront_stdexec_source}/LICENSE.txt" DESTINATION "${_webfront_license_dir}" RENAME stdexec-LICENSE.txt + COMPONENT WebFront) +endif() + +# What webfront_write_sbom() says of the sources of the installed headers. +_webfront_sbom_revision(_webfront_revision "${_webfront_root}") +_webfront_sbom_revision(_webfront_stdnet_revision "${stdnet_SOURCE_DIR}") +if(_webfront_stdnet_revision STREQUAL "NOASSERTION") + set(_webfront_stdnet_revision "${WEBFRONT_SBOM_STDNET_REVISION}") +endif() +set(_webfront_stdexec_revision NOASSERTION) +if(_webfront_stdexec_source) + _webfront_sbom_revision(_webfront_stdexec_revision "${_webfront_stdexec_source}") + if(_webfront_stdexec_revision STREQUAL "NOASSERTION") + set(_webfront_stdexec_revision "${WEBFRONT_SBOM_STDEXEC_REVISION}") + endif() +endif() +# A package build from source archives has no Git history: it states the revisions of the archives it verified. +if(_webfront_revision STREQUAL "NOASSERTION" AND WEBFRONT_SBOM_REVISION) + set(_webfront_revision "${WEBFRONT_SBOM_REVISION}") +endif() +foreach(_name _webfront_stdnet_revision _webfront_stdexec_revision) + if(NOT ${_name}) + set(${_name} NOASSERTION) + endif() +endforeach() + +configure_file("${CMAKE_CURRENT_LIST_DIR}/WebFrontConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/WebFrontConfig.cmake" @ONLY) +write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/WebFrontConfigVersion.cmake" + VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ARCH_INDEPENDENT) +set(_webfront_modules + Frontends.cmake CEFIntegration.cmake CEFSupport.cmake WebKitGTKSupport.cmake WebView2Support.cmake WKWebViewSupport.cmake + ModuleScan.cmake WebFrontEmbedDirectory.cmake WebFrontEmbedDirectoryRender.cmake WebFrontSbom.cmake + WebFrontDistribution.cmake WebFrontPackage.cmake WebFrontPackageStage.cmake WebFrontUpdater.cmake WebFrontAgentGuide.cmake + WebFrontBdd.cmake) +list(TRANSFORM _webfront_modules PREPEND "${CMAKE_CURRENT_LIST_DIR}/") +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/WebFrontConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/WebFrontConfigVersion.cmake" + ${_webfront_modules} "${_webfront_root}/js/developer/starters/agent-guide.md" + DESTINATION "${_webfront_cmake_dir}" COMPONENT WebFront) diff --git a/cmake/WebFrontPackage.cmake b/cmake/WebFrontPackage.cmake new file mode 100644 index 00000000..99e1ab29 --- /dev/null +++ b/cmake/WebFrontPackage.cmake @@ -0,0 +1,247 @@ +# webfront_package(): an application's installer, produced by CPack (docs/DISTRIBUTION.md). +# +# webfront_package( +# VERSION [NAME ] [DESCRIPTION ] [VENDOR ] [CONTACT ] [IDENTIFIER ] +# [APPARMOR_ABI 4.0] [WEBVIEW2_BOOTSTRAPPER ] +# [DEPENDS ...] [FILES ...] [LICENSE_FILE ] +# [SBOM [SBOM_ARGUMENTS ...]] +# [SIGN_COMMAND [...]]) +# +# Then `cpack` in the build directory writes one installer: a Debian package on Linux, a disk image on macOS, an NSIS +# installer on Windows. Only what this function installs goes in it. Call it once per build tree. +# +# Linux: the executable goes in /usr/bin with a desktop entry. With the WebKitGTK frontend, the application is built for +# distribution (sandbox required), the package depends on the runtime, and APPARMOR_ABI 4.0 adds the profile of +# webfront_generate_webkitgtk_profile(), loaded when the package is installed (Ubuntu 24.04 and later). +# Windows: with the WebView2 frontend, the installer looks for the Evergreen runtime; when it is absent it runs +# WEBVIEW2_BOOTSTRAPPER, a file the application obtains from Microsoft, and otherwise says that it is missing. +# SIGN_COMMAND signs with your own identity and key: it is run on the staged executable (the bundle on macOS), whose path +# is appended, before the installer is built. WebFront holds no key and signs nothing by default. +include_guard(GLOBAL) + +set_property(GLOBAL PROPERTY WEBFRONT_PACKAGE_DIR "${CMAKE_CURRENT_LIST_DIR}") + +# A file name that Debian, NSIS and the file systems accept. +function(_webfront_package_slug out name) + string(TOLOWER "${name}" slug) + string(REGEX REPLACE "[^a-z0-9+.-]+" "-" slug "${slug}") + string(REGEX REPLACE "^[^a-z0-9]+|-+$" "" slug "${slug}") + if(slug STREQUAL "") + message(FATAL_ERROR "webfront_package: NAME '${name}' has no letter or digit") + endif() + set(${out} "${slug}" PARENT_SCOPE) +endfunction() + +# One argument of a desktop entry's Exec key (Desktop Entry Specification): quoted, with `"`, backtick, `$` and `\` +# escaped, those backslashes escaped again as in any string value, and `%` doubled so that it is not a field code. +function(_webfront_desktop_exec out path) + string(REGEX REPLACE "([\"`$\\])" "\\\\\\1" quoted "${path}") + string(REPLACE "\\" "\\\\" quoted "${quoted}") + string(REPLACE "%" "%%" quoted "${quoted}") + set(${out} "\"${quoted}\"" PARENT_SCOPE) +endfunction() + +# NSIS commands run at the end of the installation: find the Evergreen WebView2 runtime, as Microsoft documents it +# (the `pv` value of its client key), and run the application's bootstrapper when it is absent. +function(_webfront_package_webview2_nsis out bootstrapper) + set(client "Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}") + set(script "") + foreach(key "HKLM|SOFTWARE\\WOW6432Node\\" "HKLM|SOFTWARE\\" "HKCU|Software\\") + string(REPLACE "|" ";" key "${key}") + list(GET key 0 hive) + list(GET key 1 prefix) + string(APPEND script " ClearErrors\n ReadRegStr $0 ${hive} \"${prefix}${client}\" \"pv\"\n" + " StrCmp $0 \"\" +2\n StrCmp $0 \"0.0.0.0\" 0 webview2_found\n") + endforeach() + set(missing "The Microsoft Edge WebView2 Runtime is not installed. Install it from https://developer.microsoft.com/microsoft-edge/webview2/ before starting the application.") + if(bootstrapper) + get_filename_component(file "${bootstrapper}" NAME) + string(APPEND script " DetailPrint \"Installing the WebView2 Runtime\"\n" + " ExecWait '\"$INSTDIR\\bin\\${file}\" /silent /install' $1\n" + " IntCmp $1 0 webview2_found\n") + endif() + string(APPEND script " MessageBox MB_OK|MB_ICONEXCLAMATION \"${missing}\" /SD IDOK\n webview2_found:\n") + set(${out} "${script}" PARENT_SCOPE) +endfunction() + +function(webfront_package target) + cmake_parse_arguments(PARSE_ARGV 1 ARG "SBOM" "NAME;VERSION;DESCRIPTION;VENDOR;CONTACT;IDENTIFIER;APPARMOR_ABI;WEBVIEW2_BOOTSTRAPPER;LICENSE_FILE" + "DEPENDS;FILES;SBOM_ARGUMENTS;SIGN_COMMAND") + if(ARG_UNPARSED_ARGUMENTS OR ARG_KEYWORDS_MISSING_VALUES) + message(FATAL_ERROR "webfront_package: invalid arguments (unknown: ${ARG_UNPARSED_ARGUMENTS}; keywords without a value: ${ARG_KEYWORDS_MISSING_VALUES})") + endif() + if(NOT TARGET "${target}") + message(FATAL_ERROR "webfront_package: unknown target '${target}'") + endif() + get_target_property(kind "${target}" TYPE) + if(NOT kind STREQUAL "EXECUTABLE") + message(FATAL_ERROR "webfront_package requires an executable target") + endif() + if(NOT ARG_VERSION MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+$") + message(FATAL_ERROR "webfront_package requires VERSION x.y.z (got '${ARG_VERSION}')") + endif() + get_property(packaged GLOBAL PROPERTY WEBFRONT_PACKAGED_TARGET) + if(packaged) + message(FATAL_ERROR "webfront_package: '${packaged}' is already packaged; one installer per build tree") + endif() + set_property(GLOBAL PROPERTY WEBFRONT_PACKAGED_TARGET "${target}") + get_property(modules GLOBAL PROPERTY WEBFRONT_PACKAGE_DIR) + + if(NOT ARG_NAME) + set(ARG_NAME "${target}") + endif() + _webfront_package_slug(slug "${ARG_NAME}") + if(NOT ARG_DESCRIPTION) + set(ARG_DESCRIPTION "${ARG_NAME}") + endif() + if(NOT ARG_VENDOR) + set(ARG_VENDOR "${ARG_NAME}") + endif() + if(NOT ARG_IDENTIFIER) + set(ARG_IDENTIFIER "local.${slug}") + endif() + get_target_property(output_name "${target}" OUTPUT_NAME) + if(NOT output_name) + set(output_name "${target}") + endif() + if(COMMAND _webfront_load_frontends) # the frontends WebFront's own directory enabled or detected + _webfront_load_frontends() + endif() + set(component webfront_app) + set(staging "${CMAKE_CURRENT_BINARY_DIR}/webfront-package") + + if(APPLE) + set_target_properties("${target}" PROPERTIES MACOSX_BUNDLE TRUE + MACOSX_BUNDLE_GUI_IDENTIFIER "${ARG_IDENTIFIER}" MACOSX_BUNDLE_BUNDLE_NAME "${ARG_NAME}" + MACOSX_BUNDLE_BUNDLE_VERSION "${ARG_VERSION}" MACOSX_BUNDLE_SHORT_VERSION_STRING "${ARG_VERSION}") + install(TARGETS "${target}" BUNDLE DESTINATION . COMPONENT ${component}) + set(documents "${output_name}.app/Contents/Resources") + set(extra "${documents}") + set(signed "${output_name}.app") + set(sbom_directory "${documents}") + elseif(WIN32) + install(TARGETS "${target}" RUNTIME DESTINATION bin COMPONENT ${component}) + set(documents ".") + set(extra "bin") + set(signed "bin/${output_name}.exe") + set(sbom_directory "${documents}") + else() + install(TARGETS "${target}" RUNTIME DESTINATION bin COMPONENT ${component}) + set(documents "share/doc/${slug}") + set(extra "share/${slug}") + # Not with the documents: minimal systems tell dpkg to leave /usr/share/doc out, and the SBOM must stay. + set(sbom_directory "${extra}") + set(signed "bin/${output_name}") + _webfront_desktop_exec(exec "/usr/bin/${output_name}") + file(CONFIGURE OUTPUT "${staging}/${slug}.desktop" CONTENT "[Desktop Entry] +Type=Application +Name=@ARG_NAME@ +Comment=@ARG_DESCRIPTION@ +Exec=@exec@ +Terminal=false +Categories=Utility; +" @ONLY) + install(FILES "${staging}/${slug}.desktop" DESTINATION share/applications COMPONENT ${component}) + endif() + if(ARG_FILES) + install(FILES ${ARG_FILES} DESTINATION "${extra}" COMPONENT ${component}) + endif() + if(ARG_LICENSE_FILE) + get_filename_component(license "${ARG_LICENSE_FILE}" ABSOLUTE) + install(FILES "${license}" DESTINATION "${documents}" COMPONENT ${component}) + endif() + if(ARG_SBOM) + webfront_write_sbom(OUTPUT "${staging}/${slug}.spdx.json" NAME "${ARG_NAME}" VERSION "${ARG_VERSION}" ${ARG_SBOM_ARGUMENTS}) + install(FILES "${staging}/${slug}.spdx.json" DESTINATION "${sbom_directory}" COMPONENT ${component}) + elseif(ARG_SBOM_ARGUMENTS) + message(FATAL_ERROR "webfront_package: SBOM_ARGUMENTS needs SBOM") + endif() + + set(CPACK_PACKAGE_NAME "${slug}") + set(CPACK_PACKAGE_VERSION "${ARG_VERSION}") + set(CPACK_PACKAGE_VENDOR "${ARG_VENDOR}") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${ARG_DESCRIPTION}") + if(ARG_CONTACT) + set(CPACK_PACKAGE_CONTACT "${ARG_CONTACT}") + endif() + set(CPACK_PACKAGE_FILE_NAME "${slug}-${ARG_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") + set(CPACK_PACKAGE_INSTALL_DIRECTORY "${ARG_NAME}") + set(CPACK_VERBATIM_VARIABLES ON) + # Only what is installed above, whatever else the build tree installs. + set(CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_BINARY_DIR};${CMAKE_PROJECT_NAME};${component};/") + + if(APPLE) + set(CPACK_GENERATOR DragNDrop) + elseif(WIN32) + set(CPACK_GENERATOR NSIS) + set(CPACK_NSIS_DISPLAY_NAME "${ARG_NAME}") + set(CPACK_NSIS_PACKAGE_NAME "${ARG_NAME}") + set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON) + set(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\${output_name}.exe") + set(CPACK_PACKAGE_EXECUTABLES "${output_name}" "${ARG_NAME}") + if(WEBFRONT_EMBED_WEBVIEW2) + if(ARG_WEBVIEW2_BOOTSTRAPPER) + get_filename_component(bootstrapper "${ARG_WEBVIEW2_BOOTSTRAPPER}" ABSOLUTE) + if(NOT EXISTS "${bootstrapper}") + message(FATAL_ERROR "webfront_package: WEBVIEW2_BOOTSTRAPPER ${bootstrapper} does not exist") + endif() + install(PROGRAMS "${bootstrapper}" DESTINATION bin COMPONENT ${component}) + else() + set(bootstrapper "") + endif() + _webfront_package_webview2_nsis(CPACK_NSIS_EXTRA_INSTALL_COMMANDS "${bootstrapper}") + endif() + else() + set(CPACK_GENERATOR DEB) + set(CPACK_PACKAGING_INSTALL_PREFIX "/usr") + if(NOT ARG_CONTACT) + set(CPACK_PACKAGE_CONTACT "${ARG_VENDOR}") + endif() + set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) + set(CPACK_DEBIAN_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}.deb") + set(depends ${ARG_DEPENDS}) + if(WEBFRONT_EMBED_WEBKITGTK) + # Loaded with dlopen: the dependency scanner of Debian cannot see it. + list(APPEND depends libwebkitgtk-6.0-4) + webfront_use_distribution("${target}") + endif() + list(JOIN depends ", " CPACK_DEBIAN_PACKAGE_DEPENDS) + if(ARG_APPARMOR_ABI) + if(NOT WEBFRONT_EMBED_WEBKITGTK) + message(STATUS "webfront_package: APPARMOR_ABI is for the WebKitGTK frontend, which is not enabled") + else() + set(profile "webfront-${slug}") + webfront_generate_webkitgtk_profile(APPARMOR_ABI "${ARG_APPARMOR_ABI}" TARGET "${target}" + EXECUTABLE "/usr/bin/${output_name}" OUTPUT "${staging}/${profile}") + install(FILES "${staging}/${profile}" DESTINATION /etc/apparmor.d COMPONENT ${component}) + file(CONFIGURE OUTPUT "${staging}/postinst" CONTENT "#!/bin/sh +set -e +if [ \"$1\" = configure ] && command -v apparmor_parser >/dev/null && [ -d /sys/kernel/security/apparmor ]; then + apparmor_parser -r -T -W /etc/apparmor.d/@profile@ || echo '@profile@: the AppArmor profile was not loaded' >&2 +fi +" @ONLY) + file(CONFIGURE OUTPUT "${staging}/prerm" CONTENT "#!/bin/sh +set -e +if [ \"$1\" = remove ] && command -v apparmor_parser >/dev/null && [ -d /sys/kernel/security/apparmor ]; then + apparmor_parser -R /etc/apparmor.d/@profile@ || true +fi +" @ONLY) + file(CHMOD "${staging}/postinst" "${staging}/prerm" PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) + set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${staging}/postinst;${staging}/prerm") + set(CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION TRUE) + endif() + elseif(WEBFRONT_EMBED_WEBKITGTK) + message(STATUS "webfront_package: no AppArmor profile without APPARMOR_ABI 4.0; where unprivileged user namespaces " + "are restricted (Ubuntu 24.04 and later), the WebKitGTK sandbox then refuses to start (docs/WEBKITGTK.md)") + endif() + endif() + + if(ARG_SIGN_COMMAND) + # Declared after every file: the install rules run in order, so the signature covers the finished tree. + install(CODE "set(WEBFRONT_SIGN_COMMAND [==[${ARG_SIGN_COMMAND}]==]) +set(WEBFRONT_SIGN_PATH \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${signed}\") +include([==[${modules}/WebFrontPackageStage.cmake]==])" COMPONENT ${component}) + endif() + include(CPack) +endfunction() diff --git a/cmake/WebFrontPackageStage.cmake b/cmake/WebFrontPackageStage.cmake new file mode 100644 index 00000000..a2c45e33 --- /dev/null +++ b/cmake/WebFrontPackageStage.cmake @@ -0,0 +1,7 @@ +# Run while the installer's tree is staged: signs the executable (or the bundle) with the command of +# webfront_package(SIGN_COMMAND). A failure stops the packaging: an unsigned installer is never produced silently. +message(STATUS "Signing ${WEBFRONT_SIGN_PATH}") +execute_process(COMMAND ${WEBFRONT_SIGN_COMMAND} "${WEBFRONT_SIGN_PATH}" RESULT_VARIABLE webfront_sign_result) +if(NOT webfront_sign_result EQUAL 0) + message(FATAL_ERROR "The signing command failed (${webfront_sign_result})") +endif() diff --git a/cmake/WebFrontSbom.cmake b/cmake/WebFrontSbom.cmake index 2075a01c..8ab7b9ae 100644 --- a/cmake/WebFrontSbom.cmake +++ b/cmake/WebFrontSbom.cmake @@ -1,12 +1,16 @@ # webfront_write_sbom(): the software bill of materials of an application, in SPDX 2.3 JSON (docs/DISTRIBUTION.md). # -# webfront_write_sbom(OUTPUT NAME VERSION +# webfront_write_sbom(OUTPUT NAME VERSION [LICENSE ] # [LOCK ] -# [PACKAGE ]...) +# [PACKAGE ]... +# [SYSTEM ]... +# [ENGINES ...] +# [LICENSES ]...) # # It lists WebFront, its C++ dependencies (stdnet, stdexec), the packages of a wf lock (every one the lock holds, whether or -# not its code ended up in the bundle) and the packages the application adds. The engine of an embedded frontend and the -# system libraries are not listed: add those you ship with PACKAGE. SOURCE_DATE_EPOCH fixes the creation date. +# not its code ended up in the bundle), the C++ standard library of the compiler, the web engines of the enabled frontends +# (or ENGINES), and the PACKAGE and SYSTEM entries of the application. Licenses are those the sources declare (WebFront, +# stdnet, stdexec, the manifests of the lock) or LICENSES; nothing is concluded. SOURCE_DATE_EPOCH fixes the creation date. include_guard(GLOBAL) function(_webfront_sbom_string out value) @@ -34,6 +38,12 @@ function(_webfront_sbom_stdnet_source out) endfunction() function(_webfront_sbom_stdexec_source out) set(source "") + get_property(installed GLOBAL PROPERTY WEBFRONT_SBOM_STDEXEC_SOURCE SET) + if(installed) # the installed package says where its copy is, if it has one + get_property(source GLOBAL PROPERTY WEBFRONT_SBOM_STDEXEC_SOURCE) + set(${out} "${source}" PARENT_SCOPE) + return() + endif() # stdnet creates this target when it takes stdexec from FetchContent, and not with standard senders or a parent's target. if(TARGET stdnet_stdexec) include(FetchContent) @@ -45,6 +55,12 @@ endfunction() # The commit checked out in `source`, or NOASSERTION: a copy without history says nothing of its revision. function(_webfront_sbom_revision out source) set(revision NOASSERTION) + # An installed package records the revisions its headers were installed from (WebFrontRevisions.cmake). + get_property(recorded GLOBAL PROPERTY "WEBFRONT_SBOM_REVISION:${source}") + if(recorded) + set(${out} "${recorded}" PARENT_SCOPE) + return() + endif() if(EXISTS "${source}/.git") find_program(GIT_EXECUTABLE git) if(GIT_EXECUTABLE) @@ -67,8 +83,53 @@ function(_webfront_sbom_revision out source) set(${out} "${revision}" PARENT_SCOPE) endfunction() -# Appends one package to `packages` and its relationship to `relations` of the caller. -macro(_webfront_sbom_package name version location comment) +# A license the caller's LICENSES names for `name`, else `declared` when it reads as an SPDX expression, else NOASSERTION. +function(_webfront_sbom_license out name declared overrides) + list(FIND overrides "${name}" index) + if(NOT index EQUAL -1) + math(EXPR index "${index} + 1") + list(GET overrides ${index} declared) + endif() + if(NOT declared MATCHES "^[A-Za-z0-9.+() -]+$" OR declared MATCHES "^(SEE |UNLICENSED$)") + set(declared NOASSERTION) + endif() + set(${out} "${declared}" PARENT_SCOPE) +endfunction() + +# The web engines of the enabled frontends: what the application loads at run time, or links statically (the WebView2 loader). +function(_webfront_sbom_enabled_engines out) + if(COMMAND _webfront_load_frontends) + _webfront_load_frontends() + endif() + set(engines "") + foreach(engine WEBKITGTK:WebKitGTK WEBVIEW2:WebView2 WKWEBVIEW:WKWebView CEF:CEF) + string(REPLACE ":" ";" engine "${engine}") + list(GET engine 0 option) + list(GET engine 1 name) + if(WEBFRONT_EMBED_${option}) + list(APPEND engines ${name}) + endif() + endforeach() + set(${out} "${engines}" PARENT_SCOPE) +endfunction() + +function(_webfront_sbom_webkitgtk_version out) + set(version NOASSERTION) + find_package(PkgConfig QUIET) + if(PkgConfig_FOUND) + execute_process(COMMAND "${PKG_CONFIG_EXECUTABLE}" --modversion webkitgtk-6.0 RESULT_VARIABLE failed + OUTPUT_VARIABLE found OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(NOT failed) + set(version "${found}") + endif() + endif() + set(${out} "${version}" PARENT_SCOPE) +endfunction() + +# Appends one package to `packages` and its relationship to `relations` of the caller; `license` is the declared one. +macro(_webfront_sbom_package name version location comment license) + _webfront_sbom_license(_declared "${name}" "${license}" "${ARG_LICENSES}") + _webfront_sbom_string(_declared "${_declared}") math(EXPR _count "${_count} + 1") _webfront_sbom_string(_name "${name}") _webfront_sbom_string(_version "${version}") @@ -76,13 +137,13 @@ macro(_webfront_sbom_package name version location comment) _webfront_sbom_string(_comment "${comment}") string(APPEND _packages ",\n {\"SPDXID\": \"SPDXRef-Package-${_count}\", \"name\": ${_name}, \"versionInfo\": ${_version}," " \"downloadLocation\": ${_location}, \"filesAnalyzed\": false, \"comment\": ${_comment}," - " \"licenseConcluded\": \"NOASSERTION\", \"licenseDeclared\": \"NOASSERTION\", \"copyrightText\": \"NOASSERTION\"}") + " \"licenseConcluded\": \"NOASSERTION\", \"licenseDeclared\": ${_declared}, \"copyrightText\": \"NOASSERTION\"}") string(APPEND _relations ",\n {\"spdxElementId\": \"SPDXRef-Application\", \"relationshipType\": \"DEPENDS_ON\"," " \"relatedSpdxElement\": \"SPDXRef-Package-${_count}\"}") endmacro() function(webfront_write_sbom) - cmake_parse_arguments(PARSE_ARGV 0 ARG "" "OUTPUT;NAME;VERSION;LOCK" "PACKAGE") + cmake_parse_arguments(PARSE_ARGV 0 ARG "" "OUTPUT;NAME;VERSION;LOCK;LICENSE" "PACKAGE;SYSTEM;ENGINES;LICENSES") foreach(required OUTPUT NAME VERSION) if(NOT DEFINED ARG_${required} OR "${ARG_${required}}" STREQUAL "") message(FATAL_ERROR "webfront_write_sbom requires ${required}") @@ -91,20 +152,25 @@ function(webfront_write_sbom) if(ARG_UNPARSED_ARGUMENTS) message(FATAL_ERROR "webfront_write_sbom: unknown arguments ${ARG_UNPARSED_ARGUMENTS}") endif() + list(LENGTH ARG_LICENSES length) + math(EXPR remainder "${length} % 2") + if(remainder) + message(FATAL_ERROR "webfront_write_sbom: LICENSES takes a package name and an SPDX expression") + endif() set(_count 0) set(_packages "") set(_relations "") _webfront_sbom_webfront_source(source) _webfront_sbom_revision(revision "${source}") - _webfront_sbom_package(WebFront "${revision}" "NOASSERTION" "C++ header-only library, https://github.com/BareNative/WebFront") + _webfront_sbom_package(WebFront "${revision}" "NOASSERTION" "C++ header-only library, https://github.com/BareNative/WebFront" "Apache-2.0 OR CECILL-B") _webfront_sbom_stdnet_source(source) _webfront_sbom_revision(revision "${source}") - _webfront_sbom_package(stdnet "${revision}" "NOASSERTION" "C++ header-only dependency of WebFront, https://github.com/ambroise-leclerc/stdnet") + _webfront_sbom_package(stdnet "${revision}" "NOASSERTION" "C++ header-only dependency of WebFront, https://github.com/ambroise-leclerc/stdnet" "Apache-2.0 WITH LLVM-exception") _webfront_sbom_stdexec_source(source) if(source) _webfront_sbom_revision(revision "${source}") - _webfront_sbom_package(stdexec "${revision}" "NOASSERTION" "C++ header-only dependency of stdnet, https://github.com/NVIDIA/stdexec") + _webfront_sbom_package(stdexec "${revision}" "NOASSERTION" "C++ header-only dependency of stdnet, https://github.com/NVIDIA/stdexec" "Apache-2.0 WITH LLVM-exception") endif() if(ARG_LOCK) @@ -121,7 +187,11 @@ function(webfront_write_sbom) string(JSON name GET "${lock}" packages "${id}" name) string(JSON version GET "${lock}" packages "${id}" version) string(JSON integrity GET "${lock}" packages "${id}" integrity) - _webfront_sbom_package("${name}" "${version}" "NOASSERTION" "npm package of the wf lock, integrity ${integrity}") + string(JSON license ERROR_VARIABLE no_license GET "${lock}" packages "${id}" manifest license) + if(no_license) + set(license NOASSERTION) + endif() + _webfront_sbom_package("${name}" "${version}" "NOASSERTION" "npm package of the wf lock, integrity ${integrity}" "${license}") endforeach() endif() endif() @@ -133,11 +203,64 @@ function(webfront_write_sbom) endif() while(ARG_PACKAGE) list(POP_FRONT ARG_PACKAGE name version location) - _webfront_sbom_package("${name}" "${version}" "${location}" "declared by the application") + _webfront_sbom_package("${name}" "${version}" "${location}" "declared by the application" NOASSERTION) + endwhile() + + # Without a compiler (a script), there is no standard library to name. + if(CMAKE_CXX_COMPILER_ID) + _webfront_sbom_package("C++ standard library" "${CMAKE_CXX_COMPILER_VERSION}" "NOASSERTION" + "system library of the ${CMAKE_CXX_COMPILER_ID} toolchain; the version is the compiler's" NOASSERTION) + endif() + if(DEFINED ARG_ENGINES) + set(engines ${ARG_ENGINES}) + list(REMOVE_ITEM engines NONE) + else() + _webfront_sbom_enabled_engines(engines) + endif() + foreach(engine IN LISTS engines) + if(engine STREQUAL "WebKitGTK") + _webfront_sbom_webkitgtk_version(version) + _webfront_sbom_package(WebKitGTK "${version}" "NOASSERTION" + "web engine, a system library loaded at run time; version of the build machine" NOASSERTION) + elseif(engine STREQUAL "WebView2") + _webfront_sbom_package("Microsoft.Web.WebView2" "1.0.3537.50" "https://www.nuget.org/packages/Microsoft.Web.WebView2" + "SDK whose loader is linked statically" NOASSERTION) + _webfront_sbom_package("WebView2 Runtime" "NOASSERTION" "NOASSERTION" + "web engine installed on the user's machine (Evergreen, updated by Microsoft)" NOASSERTION) + elseif(engine STREQUAL "WKWebView") + _webfront_sbom_package("WebKit.framework" "NOASSERTION" "NOASSERTION" "web engine of macOS" NOASSERTION) + elseif(engine STREQUAL "CEF") + if(CEF_VERSION) + set(version "${CEF_VERSION}") + else() + set(version NOASSERTION) + endif() + _webfront_sbom_package(CEF "${version}" "NOASSERTION" "web engine shipped with the application" NOASSERTION) + else() + message(FATAL_ERROR "webfront_write_sbom: unknown engine '${engine}'") + endif() + endforeach() + + # webfront_use_updater(), called before this function, links OpenSSL's libcrypto. + get_property(openssl GLOBAL PROPERTY WEBFRONT_UPDATER_OPENSSL_VERSION) + if(openssl) + _webfront_sbom_package(OpenSSL "${openssl}" "NOASSERTION" "system library of the updater; version of the build machine" NOASSERTION) + endif() + + list(LENGTH ARG_SYSTEM length) + math(EXPR remainder "${length} % 2") + if(remainder) + message(FATAL_ERROR "webfront_write_sbom: SYSTEM takes a name and a version") + endif() + while(ARG_SYSTEM) + list(POP_FRONT ARG_SYSTEM name version) + _webfront_sbom_package("${name}" "${version}" "NOASSERTION" "system library declared by the application" NOASSERTION) endwhile() _webfront_sbom_string(application "${ARG_NAME}") _webfront_sbom_string(application_version "${ARG_VERSION}") + _webfront_sbom_license(license "${ARG_NAME}" "${ARG_LICENSE}" "${ARG_LICENSES}") + _webfront_sbom_string(license "${license}") string(TIMESTAMP created "%Y-%m-%dT%H:%M:%SZ" UTC) string(SHA256 digest "${ARG_NAME} ${ARG_VERSION} ${created} ${_packages}") file(WRITE "${ARG_OUTPUT}" "{ @@ -148,7 +271,7 @@ function(webfront_write_sbom) \"documentNamespace\": \"urn:webfront:sbom:${digest}\", \"creationInfo\": {\"created\": \"${created}\", \"creators\": [\"Tool: webfront_write_sbom\"]}, \"packages\": [ - {\"SPDXID\": \"SPDXRef-Application\", \"name\": ${application}, \"versionInfo\": ${application_version}, \"downloadLocation\": \"NOASSERTION\", \"filesAnalyzed\": false, \"licenseConcluded\": \"NOASSERTION\", \"licenseDeclared\": \"NOASSERTION\", \"copyrightText\": \"NOASSERTION\"}${_packages} + {\"SPDXID\": \"SPDXRef-Application\", \"name\": ${application}, \"versionInfo\": ${application_version}, \"downloadLocation\": \"NOASSERTION\", \"filesAnalyzed\": false, \"licenseConcluded\": \"NOASSERTION\", \"licenseDeclared\": ${license}, \"copyrightText\": \"NOASSERTION\"}${_packages} ], \"relationships\": [ {\"spdxElementId\": \"SPDXRef-DOCUMENT\", \"relationshipType\": \"DESCRIBES\", \"relatedSpdxElement\": \"SPDXRef-Application\"}${_relations} diff --git a/cmake/WebFrontUpdater.cmake b/cmake/WebFrontUpdater.cmake new file mode 100644 index 00000000..7ec13a28 --- /dev/null +++ b/cmake/WebFrontUpdater.cmake @@ -0,0 +1,27 @@ +# webfront_use_updater(...): the optional verified updater, , outside the +# core (ADR-010, docs/DISTRIBUTION.md). It links the signature verification of the operating system: CNG on Windows, +# Security.framework on macOS, OpenSSL's libcrypto elsewhere (3.0 or later). +include_guard(GLOBAL) + +function(webfront_use_updater) + if(NOT ARGC) + message(FATAL_ERROR "webfront_use_updater requires at least one target") + endif() + if(NOT WIN32 AND NOT APPLE) + find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto) + set_property(GLOBAL PROPERTY WEBFRONT_UPDATER_OPENSSL_VERSION "${OPENSSL_VERSION}") + endif() + foreach(target IN LISTS ARGN) + if(NOT TARGET "${target}") + message(FATAL_ERROR "webfront_use_updater: unknown target '${target}'") + endif() + target_link_libraries("${target}" PRIVATE WebFront::WebFront) + if(WIN32) + target_link_libraries("${target}" PRIVATE bcrypt) + elseif(APPLE) + target_link_libraries("${target}" PRIVATE "-framework Security" "-framework CoreFoundation") + else() + target_link_libraries("${target}" PRIVATE OpenSSL::Crypto) + endif() + endforeach() +endfunction() diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index d84141a7..148dc370 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -1,5 +1,8 @@ include_guard(GLOBAL) +if(NOT DEFINED WEBFRONT_USAGE_TARGET) + set(WEBFRONT_USAGE_TARGET WebFront) +endif() find_package(PkgConfig QUIET) if(NOT PkgConfig_FOUND) message(FATAL_ERROR "WEBFRONT_EMBED_WEBKITGTK=ON requires pkg-config and the WebKitGTK 6.0 development packages") @@ -11,13 +14,14 @@ endif() # The imported target verifies the installed SDK and is available to explicit native consumers. # The adapter uses dlopen rather than linking GTK into all executables (including CEF subprocesses). # Do not propagate its SDK include paths or GTK/GLib headers through WebFront. -target_compile_definitions(WebFront INTERFACE WEBFRONT_EMBED_WEBKITGTK) +target_compile_definitions(${WEBFRONT_USAGE_TARGET} INTERFACE WEBFRONT_EMBED_WEBKITGTK) find_program(WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE NAMES bwrap DOC "Bubblewrap path compiled into the target WebKitGTK engine") if(WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE) - target_compile_definitions(WebFront INTERFACE WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE="${WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE}") + target_compile_definitions(${WEBFRONT_USAGE_TARGET} INTERFACE WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE="${WEBFRONT_WEBKITGTK_BWRAP_EXECUTABLE}") endif() -include("${CMAKE_CURRENT_LIST_DIR}/../test/cmake/WebKitGTKTestEnvironment.cmake") +# Only a WebFront checkout has the test helpers: the installed package does not. +include("${CMAKE_CURRENT_LIST_DIR}/../test/cmake/WebKitGTKTestEnvironment.cmake" OPTIONAL) function(webfront_add_webkitgtk_tests) foreach(name IN LISTS ARGN) diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index 81e76eaf..6a981ed0 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -42,6 +42,10 @@ else() message(FATAL_ERROR "WebView2 SDK loader does not support compiler target '${_webview2_target}'") endif() +# WEBFRONT_WEBVIEW2_SDK_DIR: an extracted Microsoft.Web.WebView2 NuGet package, instead of downloading the pinned one. +if(WEBFRONT_WEBVIEW2_SDK_DIR) + set(WebView2SDK_SOURCE_DIR "${WEBFRONT_WEBVIEW2_SDK_DIR}") +else() CPMAddPackage( NAME WebView2SDK VERSION 1.0.3537.50 @@ -49,11 +53,15 @@ CPMAddPackage( URL_HASH SHA256=5ea526bbd728adda0da4d31219267e96460494a427e4894c4e09d9f320f4b9aa DOWNLOAD_ONLY YES ) +endif() +if(NOT DEFINED WEBFRONT_USAGE_TARGET) + set(WEBFRONT_USAGE_TARGET WebFront) +endif() # Static loader: consumers need no WebView2Loader.dll deployment step. -target_include_directories(WebFront SYSTEM INTERFACE "${WebView2SDK_SOURCE_DIR}/build/native/include") -target_compile_definitions(WebFront INTERFACE WEBFRONT_EMBED_WEBVIEW2) -target_link_libraries(WebFront INTERFACE +target_include_directories(${WEBFRONT_USAGE_TARGET} SYSTEM INTERFACE "${WebView2SDK_SOURCE_DIR}/build/native/include") +target_compile_definitions(${WEBFRONT_USAGE_TARGET} INTERFACE WEBFRONT_EMBED_WEBVIEW2) +target_link_libraries(${WEBFRONT_USAGE_TARGET} INTERFACE "${WebView2SDK_SOURCE_DIR}/build/native/${_webview2_arch}/WebView2LoaderStatic.lib" ole32 oleaut32 user32 gdi32 shell32 shlwapi version) diff --git a/cmake/packaging/conan/conanfile.py b/cmake/packaging/conan/conanfile.py new file mode 100644 index 00000000..312a690e --- /dev/null +++ b/cmake/packaging/conan/conanfile.py @@ -0,0 +1,59 @@ +# Recipe of the WebFront checkout it sits in (docs/DISTRIBUTION.md): +# conan create /cmake/packaging/conan +# stdnet and stdexec are the revisions of cmake/WebFrontDependencies.cmake, verified by their archive digests. +import os + +from conan import ConanFile +from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout +from conan.tools.files import copy, get + + +class WebFrontConan(ConanFile): + name = "webfront" + version = "1.3.0" + description = "C++23 header-only library serving a browser UI from a C++ application" + homepage = "https://github.com/BareNative/WebFront" + license = "Apache-2.0 OR CECILL-B" + # The content depends on whether the compiler's standard library has std::execution: the settings stay in the package id. + settings = "os", "arch", "compiler", "build_type" + package_type = "header-library" + + def export_sources(self): + root = os.path.join(self.recipe_folder, "..", "..", "..") + for pattern in ("CMakeLists.txt", "LICENSE", "include/*", "cmake/*", "js/core/*", + "js/developer/starters/agent-guide.md"): + copy(self, pattern, root, self.export_sources_folder, excludes="cmake/packaging/*") + + def layout(self): + cmake_layout(self) + + def source(self): + get(self, "https://github.com/ambroise-leclerc/stdnet/archive/8005774eabcba7e73188c02d2eeca2ff43c4ee3a.tar.gz", + sha256="4be3a2b4ca8710c7e4db36ba7cf6ec91fd5d6136beaca347df71b9b0c084b434", destination="stdnet-source", strip_root=True) + get(self, "https://github.com/NVIDIA/stdexec/archive/7df6de8eeec667c8adce66fa5a3e17cfd6849e48.tar.gz", + sha256="5e31381f9f5fb3fdb4401ac5aab8d93848c2b82932ce45807eab8217d951fd99", destination="stdexec-source", strip_root=True) + + def generate(self): + toolchain = CMakeToolchain(self) + variables = toolchain.cache_variables + variables["WEBFRONT_STDNET_SOURCE_DIR"] = os.path.join(self.source_folder, "stdnet-source").replace("\\", "/") + variables["WEBFRONT_STDEXEC_SOURCE_DIR"] = os.path.join(self.source_folder, "stdexec-source").replace("\\", "/") + variables["WEBFRONT_SBOM_STDNET_REVISION"] = "8005774eabcba7e73188c02d2eeca2ff43c4ee3a" + variables["WEBFRONT_SBOM_STDEXEC_REVISION"] = "7df6de8eeec667c8adce66fa5a3e17cfd6849e48" + for option in ("WEBFRONT_AUTODETECT_NATIVE", "WEBFRONT_BUILD_EXAMPLES", "WEBFRONT_ENABLE_TESTING", "ENABLE_CACHE", + "CMAKE_CXX_SCAN_FOR_MODULES"): + variables[option] = False + toolchain.generate() + + def build(self): + CMake(self).configure() + + def package(self): + CMake(self).install() + + def package_info(self): + # The package brings its own CMake configuration files: CMakeDeps generates none. + self.cpp_info.set_property("cmake_find_mode", "none") + self.cpp_info.builddirs = ["share/cmake/WebFront", "lib/cmake/WebFrontBdd"] + self.cpp_info.bindirs = [] + self.cpp_info.libdirs = [] diff --git a/cmake/packaging/conan/test_package/conanfile.py b/cmake/packaging/conan/test_package/conanfile.py new file mode 100644 index 00000000..6658832b --- /dev/null +++ b/cmake/packaging/conan/test_package/conanfile.py @@ -0,0 +1,28 @@ +# `conan create` builds the consumer project of test/cmake/package-consumer (Hello World) against the new package. +import os + +from conan import ConanFile +from conan.tools.cmake import CMake + + +class WebFrontTestConan(ConanFile): + settings = "os", "arch", "compiler", "build_type" + generators = "CMakeDeps", "CMakeToolchain" + + def requirements(self): + self.requires(self.tested_reference_str) + + def layout(self): + self.folders.build = os.path.join("build", str(self.settings.build_type)) + self.folders.generators = os.path.join(self.folders.build, "generators") + + def build(self): + root = os.path.abspath(os.path.join(self.source_folder, "..", "..", "..", "..")) + cmake = CMake(self) + cmake.configure(variables={"HELLO_WORLD_SOURCE": os.path.join(root, "examples", "hello-world", "HelloWorld.cpp").replace("\\", "/"), + "CMAKE_CXX_SCAN_FOR_MODULES": "OFF"}, + build_script_folder=os.path.join(root, "test", "cmake", "package-consumer")) + cmake.build() + + def test(self): + pass diff --git a/cmake/packaging/vcpkg/webfront/portfile.cmake b/cmake/packaging/vcpkg/webfront/portfile.cmake new file mode 100644 index 00000000..51accd56 --- /dev/null +++ b/cmake/packaging/vcpkg/webfront/portfile.cmake @@ -0,0 +1,33 @@ +# Overlay port of the WebFront checkout it sits in (docs/DISTRIBUTION.md): +# vcpkg install webfront --overlay-ports=/cmake/packaging/vcpkg +# vcpkg's binary cache does not see changes of the checkout: use --binarysource=clear while changing WebFront. +# stdnet and stdexec are the revisions of cmake/WebFrontDependencies.cmake, verified by their archive digests. +set(VCPKG_BUILD_TYPE release) # headers only + +get_filename_component(SOURCE_PATH "${CMAKE_CURRENT_LIST_DIR}/../../../.." ABSOLUTE) +vcpkg_from_github(OUT_SOURCE_PATH STDNET_SOURCE_PATH + REPO ambroise-leclerc/stdnet + REF 8005774eabcba7e73188c02d2eeca2ff43c4ee3a + SHA512 4d20abf76e63846058d306d7652139ddb00fe83c7582a0861b43fbd2939e21cfea65fa76d3da61c16545372720f29f7ade32072e6ec821784f5d83872e657429) +vcpkg_from_github(OUT_SOURCE_PATH STDEXEC_SOURCE_PATH + REPO NVIDIA/stdexec + REF 7df6de8eeec667c8adce66fa5a3e17cfd6849e48 + SHA512 a32aafdf0f1cd7ed24f5f1901386eb6ff2ece86deeddeda07b7a862ec329e01865916c57fd1e694b06d29dd164340b79920e4dadeca2181b324d7f64d4ab06d0) + +vcpkg_cmake_configure(SOURCE_PATH "${SOURCE_PATH}" + OPTIONS + "-DWEBFRONT_STDNET_SOURCE_DIR=${STDNET_SOURCE_PATH}" + "-DWEBFRONT_STDEXEC_SOURCE_DIR=${STDEXEC_SOURCE_PATH}" + -DWEBFRONT_SBOM_STDNET_REVISION=8005774eabcba7e73188c02d2eeca2ff43c4ee3a + -DWEBFRONT_SBOM_STDEXEC_REVISION=7df6de8eeec667c8adce66fa5a3e17cfd6849e48 + -DWEBFRONT_AUTODETECT_NATIVE=OFF + -DWEBFRONT_BUILD_EXAMPLES=OFF + -DWEBFRONT_ENABLE_TESTING=OFF + -DENABLE_CACHE=OFF + -DCMAKE_CXX_SCAN_FOR_MODULES=OFF) +vcpkg_cmake_install() +vcpkg_cmake_config_fixup(PACKAGE_NAME WebFront CONFIG_PATH share/cmake/WebFront DO_NOT_DELETE_PARENT_CONFIG_PATH) +vcpkg_cmake_config_fixup(PACKAGE_NAME WebFrontBdd CONFIG_PATH lib/cmake/WebFrontBdd) +file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/lib" "${CURRENT_PACKAGES_DIR}/debug" "${CURRENT_PACKAGES_DIR}/share/cmake" + "${CURRENT_PACKAGES_DIR}/share/doc") +vcpkg_install_copyright(FILE_LIST "${SOURCE_PATH}/LICENSE" "${STDNET_SOURCE_PATH}/LICENSE" "${STDEXEC_SOURCE_PATH}/LICENSE.txt") diff --git a/cmake/packaging/vcpkg/webfront/vcpkg.json b/cmake/packaging/vcpkg/webfront/vcpkg.json new file mode 100644 index 00000000..14f68091 --- /dev/null +++ b/cmake/packaging/vcpkg/webfront/vcpkg.json @@ -0,0 +1,11 @@ +{ + "name": "webfront", + "version": "1.3.0", + "description": "C++23 header-only library serving a browser UI from a C++ application", + "homepage": "https://github.com/BareNative/WebFront", + "license": "Apache-2.0 OR CECILL-B", + "dependencies": [ + {"name": "vcpkg-cmake", "host": true}, + {"name": "vcpkg-cmake-config", "host": true} + ] +} diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index df302bd3..49617be3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,7 +19,10 @@ these entries stays in the GitHub releases and the Git history. - A type that converts to `std::string_view` without being a string is no longer written as text by `info()`, `fail()` and `checkEqual` (it appears as `{?}` without a `Printer`): specialize `webfront::bdd::isString` (or `Printer`) for it (#739, `docs/BDD.md`). ### Added -- Write the SPDX bill of materials of your application with `webfront_write_sbom()` (#762, ADR-028, `docs/DISTRIBUTION.md`). +- Use an installed WebFront with `find_package(WebFront)`, offline, through `cmake --install`, a vcpkg overlay port or a Conan recipe of the repository (#762, ADR-028, `docs/DISTRIBUTION.md`). +- Build an installer of your application with `webfront_package()`: Debian package with the WebKitGTK profile, macOS disk image or NSIS installer that detects the WebView2 runtime (#762, ADR-028, `docs/DISTRIBUTION.md`). +- Replace an executable with a signed one, with rollback, using the optional `webfront/components/update/Updater.hpp` (#762, ADR-028, `docs/DISTRIBUTION.md`). +- Write the SPDX bill of materials of your application with `webfront_write_sbom()`, with declared licenses, web engines and system libraries (#762, ADR-028, `docs/DISTRIBUTION.md`). - First measurements of image streams to the page: raw frames, JPEG and WebCodecs availability under CEF and WebKitGTK (#769, `docs/IMAGE_STREAMS.md`). - Open an embedded window maximized, full screen, without a frame or with a minimum size (`WindowOptions`), on WebKitGTK and CEF (#764, `docs/FRONTENDS.md`). - `wf dev` applies a change of the stylesheet alone without reloading the page, once an environment with it is published (#763, ADR-014). diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md index 2a12241b..e7e9aaa1 100644 --- a/docs/DISTRIBUTION.md +++ b/docs/DISTRIBUTION.md @@ -1,7 +1,124 @@ # Distributing an application -WebFront does not package, sign or update an application: those remain application work -([ADR-028](adr/ADR-028-distribution.md)). What it provides today is a bill of materials. +Four things help to ship a WebFront application ([ADR-028](adr/ADR-028-distribution.md)): the installed library with its +vcpkg port and Conan recipe, a CPack installer, a bill of materials and an optional verified updater. WebFront publishes no +package, holds no key and runs no server: publishing, signing and serving updates are the application's. + +## Consuming WebFront as a package + +`cmake --install --prefix ` of a top-level WebFront build (`WEBFRONT_INSTALL`, on by default there) installs +the headers, the pinned stdnet and stdexec (apart, in `include/webfront-deps/`), their licenses and the CMake files: + +```cmake +find_package(WebFront CONFIG REQUIRED) # with a frontend: ... COMPONENTS WebKitGTK +add_executable(app main.cpp) +target_link_libraries(app PRIVATE WebFront::WebFront) +``` + +The configuration downloads nothing. It defines `WebFront::WebFront`, `WebFront::Bdd` and the public helpers +(`webfront_use_native_window`, `webfront_embed_directory`, `webfront_write_agent_guide`, `webfront_write_sbom`, +`webfront_package`, `webfront_use_updater`, `webfront_use_distribution`, `webfront_generate_webkitgtk_profile`, +`webfront_bdd_discover_tests`). Differences from `add_subdirectory` or CPM: + +- no frontend is detected: ask for it with a component (`WebKitGTK`, `WKWebView`, `WebView2`) or `-DWEBFRONT_EMBED_...=ON`; +- WebView2 also needs `WEBFRONT_WEBVIEW2_SDK_DIR`, an extracted `Microsoft.Web.WebView2` NuGet package; +- CEF, `webfront_add_jasmine_test` and the `wf` tools are not part of the package; +- a target `stdnet::stdnet` or `STDEXEC::stdexec` that your project already defines is used instead of the bundled headers. + +A WebFront installed with a compiler whose standard library has `std::execution` holds no stdexec, and is refused by a +compiler without it. + +### vcpkg and Conan + +Both recipes are in the repository and build the checkout they sit in. They are not published in the vcpkg or Conan +registries. Their installation step downloads the pinned stdnet and stdexec archives and verifies their digests; afterwards +your project configures with no network. + +```bash +vcpkg install webfront --overlay-ports=/cmake/packaging/vcpkg +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake + +conan create /cmake/packaging/conan -s compiler.cppstd=23 +# conanfile.txt: [requires] webfront/1.3.0, [generators] CMakeDeps CMakeToolchain +conan install . -s compiler.cppstd=23 --output-folder=build +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake +``` + +vcpkg's binary cache does not see changes of the checkout: use `--binarysource=clear` after changing WebFront. + +To build WebFront itself without downloading, give the sources of the pinned dependencies +(`cmake/WebFrontDependencies.cmake`): `-DWEBFRONT_STDNET_SOURCE_DIR=... -DWEBFRONT_STDEXEC_SOURCE_DIR=...`. + +## Installers + +```cmake +webfront_package(app NAME "My App" VERSION 1.2.0 VENDOR "Me" CONTACT "me@example.org" IDENTIFIER org.example.app + APPARMOR_ABI 4.0 LICENSE_FILE LICENSE + SBOM SBOM_ARGUMENTS LOCK "${CMAKE_SOURCE_DIR}/webfront-packages.lock.json" + SIGN_COMMAND codesign --force --sign "My identity") +``` + +Then `cmake --build --target package` (or `cpack` in it) writes one installer of that application only: + +| System | Format | Installs | Removal | +| --- | --- | --- | --- | +| Linux | Debian package | `/usr/bin`, a desktop entry, `/usr/share/` (SBOM, `FILES`), `/usr/share/doc/` (license) | `apt remove` / `dpkg --purge` | +| macOS | disk image (DragNDrop) | the `.app` bundle, copied by the user | deleting the bundle | +| Windows | NSIS installer (NSIS 3 required to build it) | `Program Files`, a start-menu entry | its uninstaller, also in Settings | + +- **WebKitGTK.** The application is built for distribution (the sandbox is required) and the package depends on + `libwebkitgtk-6.0-4`. `APPARMOR_ABI 4.0` adds the [sandbox profile](WEBKITGTK.md) of the installed executable, loaded at + installation, for Ubuntu 24.04 and later; without it, no profile is packaged. RPM and AppImage are not produced. +- **WebView2.** The installer looks for the Evergreen runtime. When it is absent it runs `WEBVIEW2_BOOTSTRAPPER`, the + `MicrosoftEdgeWebview2Setup.exe` you downloaded from Microsoft and ship under its terms; without one it only says so. +- **Signing.** `SIGN_COMMAND` runs on the staged executable, or the macOS bundle, with its path appended: `codesign`, + `signtool sign /fd SHA256 ...`, or your own tool, with your identity. A failure stops the packaging. Signing the installer + itself, notarizing a disk image and signing a Debian repository are done afterwards with the platform's tools; without + them, macOS Gatekeeper and Windows SmartScreen warn or refuse. +- Libraries that the application needs and the system lacks are yours to install (`FILES`, `DEPENDS`). Link the MSVC runtime + statically, as [the Life package](../examples/life/package/CMakeLists.txt) does, or ship its redistributable. + +The CI packages the embedded Game of Life this way on the three systems, installs it, runs `--check` and removes it +(`test/cmake/CheckLifeInstaller.cmake`). It does not open the installed application's window. + +## Verified updates + +`` is optional and outside the core ([ADR-010](adr/ADR-010-composants-et-outils-optionnels.md)). +It replaces one executable file with a candidate whose signature matches the application's public key: + +```cmake +webfront_use_updater(app) # CNG on Windows, Security.framework on macOS, OpenSSL's libcrypto 3 elsewhere +``` + +```cpp +using namespace webfront::update; +Updater updater{executablePath()}; +updater.recover(); // first thing at start-up +// ... download the new executable and its signature, by your own means ... +updater.apply(candidate, signature, PublicKey::fromPem(myPublicKey)); // then restart +// ... in the new version, once it works: +updater.confirm(); +``` + +The signature is ECDSA P-256 with SHA-256 in DER, which the three systems verify natively; WebFront implements no +cryptography. Create the key and sign a release with OpenSSL, and keep the private key off the build and update servers: + +```bash +openssl ecparam -name prime256v1 -genkey -noout -out update-key.pem +openssl ec -in update-key.pem -pubout -out update-key.pub # embed this one +openssl dgst -sha256 -sign update-key.pem -out app.sig app +``` + +- The candidate is copied beside the executable and the copy is verified: a refused signature changes nothing. +- The former executable stays beside it until `confirm()`. `rollback()` restores it; `recover()` restores it too after three + starts without confirmation (`recover(n)` changes the number), or after an interrupted update that left no executable. +- Linux and macOS swap with one atomic rename. **Windows is not atomic**: a running image cannot be replaced, so it is + renamed away and the new file renamed in place. A power cut between the two leaves no executable under its name; `recover()` + restores it, but must then be run by what starts the application (a launcher, a service or the installer). +- The signature says who produced the file, not that it is newer: compare versions, from data you trust, before `apply()`. +- It replaces one file. It does not update a macOS bundle (replacing its executable breaks the bundle's signature), an + application installed where it cannot write (`/usr/bin`, `Program Files` without elevation), or resources beside it. +- One updater at a time works on an executable. ## Bill of materials @@ -10,23 +127,29 @@ webfront_write_sbom( OUTPUT "${CMAKE_BINARY_DIR}/myapp.spdx.json" NAME myapp VERSION 1.2.0 + LICENSE MIT LOCK "${CMAKE_SOURCE_DIR}/webfront-packages.lock.json" - PACKAGE WebView2 1.0.3537.50 https://www.nuget.org/packages/Microsoft.Web.WebView2) + PACKAGE extra 2.0 https://example.org/extra + SYSTEM libfoo 3.1 + LICENSES extra BSD-3-Clause) ``` -The function is defined once WebFront is part of the build (`add_subdirectory` or CPM). It writes SPDX 2.3 JSON at -configure time (and again at the next build when the lock or a Git revision of those sources changes), listing: +It writes SPDX 2.3 JSON at configure time (and again at the next build when the lock or a Git revision of those sources +changes), listing: -- WebFront, stdnet and, when stdnet takes it from FetchContent, stdexec, at the commit checked out in the sources the build - uses (`NOASSERTION` for a copy without Git history). A `STDEXEC::stdexec` of your own is not listed: add it with - `PACKAGE`; -- every package of the `wf` lock given with `LOCK`, with its version and integrity. A lock also holds development +- WebFront, stdnet and, when it is used, stdexec, at the commit of the sources the build uses (`NOASSERTION` for a copy + without Git history; an installed package records the revisions it was built from). A `STDEXEC::stdexec` of your own is not + listed: add it with `PACKAGE`; +- every package of the `wf` lock, with its version, integrity and the license of its manifest. A lock also holds development tools whose code is not in the shipped bundle: the list is an upper bound of the JavaScript you ship; -- what you add with `PACKAGE `. +- the C++ standard library of the compiler, and OpenSSL when `webfront_use_updater()` was called before; +- the web engines of the enabled frontends (WebKitGTK with the version of the build machine, the WebView2 SDK and runtime, + macOS's WebKit, CEF), or those given with `ENGINES` (`NONE` for none); +- your `PACKAGE` and `SYSTEM` entries. -It does not list the compiler's libraries, system libraries or the engine of an embedded frontend, and it declares no -license: add what you ship, and complete the licenses with your own tooling. Set `SOURCE_DATE_EPOCH` for the same bytes -from the same inputs. +Licenses are those the sources declare, or yours (`LICENSE`, `LICENSES`); the others are `NOASSERTION`, and nothing is +concluded. It is not a scan of the binary and not a statement of compliance. Set `SOURCE_DATE_EPOCH` for the same bytes from +the same inputs. ## Elsewhere diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 5ee1f0d0..44fa2e08 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -52,7 +52,10 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer directory, with no build step, is embedded from CMake alone by `webfront_embed_directory()` (identity encoded; see [embedded assets](EMBEDDED_ASSETS.md#embedding-an-interface-directory-from-cmake)). `NativeAppWithAssets` runs without project files, developer callbacks or tool cache. - Native-engine deployment remains application work. The [README walkthrough](../README.md) + `find_package(WebFront)` (with a vcpkg overlay port and a Conan recipe, neither published in a registry), + `webfront_package()` installers and an optional verified updater are described in [distribution](DISTRIBUTION.md); the + installers' CI installs and checks the embedded Life without opening its window, signs nothing, and the updater's swap is + not atomic on Windows. Publication, signing identities and update serving remain application work. The [README walkthrough](../README.md) covers the console, developer and embedded Game of Life stages; Hello World and the host loop (`examples/host-loop/`, a Boing Ball ray-traced by the host on the CPU or with optional CUDA; see [the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are also in the default build. @@ -212,8 +215,8 @@ are retained for investigation; diagnostics alone do not establish a correction. WebView2 runs on any thread that is not already MTA (`webfront::UIThread`). Hidden WKWebView tests require macOS 14+ and a WindowServer session. Automated CEF coverage is Linux/Xvfb; Windows/macOS CEF deployment is not qualified. WebView2 needs its installed Evergreen runtime; - fixed-version runtime packaging, application installers and accessibility remain application work (checks and - measured limits: [accessibility](ACCESSIBILITY.md)). + fixed-version runtime packaging and accessibility remain application work (`webfront_package()` detects the runtime, + [distribution](DISTRIBUTION.md); checks and measured limits: [accessibility](ACCESSIBILITY.md)). - `WebView2Frontend::open()` releases the STA it initialized. When a window is closed while the runtime is still starting, or by a page that closes it on a load failure, the WebView2 runtime (observed with 157.0.4341.46) can keep a COM initialization of its own: the thread is then still in an STA (apartment type 3, qualifier 0) when `open()` returns diff --git a/docs/TEST_TIERS.md b/docs/TEST_TIERS.md index 3927cce8..a14f2c3e 100644 --- a/docs/TEST_TIERS.md +++ b/docs/TEST_TIERS.md @@ -7,7 +7,7 @@ to the standard tier. | --- | --- | --- | --- | | Fast | `fast` | C++ unit tests (`include/webfront/testing/Bdd.hpp`) and the Python tool tests; no browser, no nested build | Locally on demand, and as the first test step of every Linux/Windows/macOS desktop job | | Standard | none, or `web-integration` | Everything but the portability tests: unit tests, real-browser integration, `wf` commands, embedded builds | Every pull request and every push to `develop` or `master` | -| Portability | `portability` | The library consumed from another project: `AddSubdirectoryConsumer`, `BddConsumer` | Weekly, and on every pull request into `master` | +| Portability | `portability` | The library consumed from another project: `AddSubdirectoryConsumer`, `BddConsumer`, `InstalledPackageConsumer` | Weekly, and on every pull request into `master` | ```sh ctest --test-dir build -L fast --parallel 4 # about one second @@ -123,6 +123,9 @@ of the headers can break it. Locally, `ctest -LE configuration` leaves them out. The coverage capture (`lcov`) runs on a push to `develop` or `master` and in the full tier. A pull request still builds and runs the instrumented Linux tests, but nothing reads a pull request's capture. +Every desktop job, after its tests, also packages the embedded Life example (`examples/life/package/`) from the provider the +developer journey generated, installs the installer, runs `--check` and removes it (#762). + ## Advanced checks These run on the weekly schedule (Monday 04:23 UTC), on every pull request whose base is `master`, and on a manual @@ -133,6 +136,9 @@ dispatch with `repeat_desktop_tests`: - the `portability` job: the consumer project configured with Ninja (GCC on Linux, MSVC on Windows, Apple clang on macOS), with Unix Makefiles (Clang 23) and, reported but never blocking until it has run on a hosted runner, the Visual Studio 2026 generator. There is no compiler cache: a new user compiles everything; +- the `packages` job (#762): the vcpkg overlay port and the Conan recipe on Linux, then a consumer building Hello World with + `find_package(WebFront)` and the public network cut; the `InstalledPackageConsumer` portability case does the same from + `cmake --install` on every portability platform; - the `gcc13-arm64` job (#548): GCC 13 on a hosted Linux aarch64 runner (`ubuntu-24.04-arm`), compiling the library, the examples and the tests with warnings that are not errors (libstdc++ 13 reports false `-Wnull-dereference` positives, #526), then running the fast tier, then rebuilding the tests under GCC 13 ASan/UBSan and repeating the fast tier (#525, S2 support). diff --git a/docs/adr/ADR-028-distribution.md b/docs/adr/ADR-028-distribution.md index ecf1ae76..f2fb0774 100644 --- a/docs/adr/ADR-028-distribution.md +++ b/docs/adr/ADR-028-distribution.md @@ -5,48 +5,73 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | | 1.0 | 2026-12-05 | Proposée | Ambroise Leclerc | Périmètre de la distribution : paquets, empaquetage, SBOM et mise à jour ; première livraison, le SBOM (#762). | Branche `762-distribution` | +| 2.0 | 2026-12-05 | Acceptée | Ambroise Leclerc | Formats retenus : paquet CMake installé, port vcpkg et recette Conan, DEB/DMG/NSIS, signature ECDSA P-256 et remplacement avec retour arrière (#762). | Branche `762-packages` | ## État et chronologie -**Proposée.** Décision initiale : **2026-12-05** (version 1.0). +**Acceptée.** Décision initiale : **2026-12-05** (version 1.0) ; acceptée avec ses formats en version 2.0. ## Contexte -WebFront se consomme par `add_subdirectory` ; l'installeur, la signature et la mise à jour d'une application sont à sa -charge. Une application soumise à des exigences de traçabilité doit pourtant énumérer ce qu'elle embarque, dont des -dépendances C++ épinglées par WebFront et des paquets npm que seul le verrou connaît. +WebFront se consommait par `add_subdirectory` ; l'installeur, la signature et la mise à jour d'une application étaient à sa +charge. Une application soumise à des exigences de traçabilité doit énumérer ce qu'elle embarque, dont des dépendances C++ +épinglées par WebFront et des paquets npm que seul le verrou connaît. ## Décision -La distribution se découpe en trois lots indépendants, livrés séparément : - -1. **Paquets.** Les ports vcpkg et Conan viennent après `install()` et `find_package(WebFront)` (#498) ; ils épinglent - stdnet et stdexec aux mêmes révisions que la construction directe. -2. **Empaquetage.** Des aides CPack facultatives ; aucune n'impose un format ni ne signe avec une clé de WebFront. Le - SBOM SPDX est la première aide : `webfront_write_sbom()`, en CMake seul. -3. **Mise à jour.** Un composant facultatif hors du cœur (ADR-010), qui vérifie la signature avec la clé de - l'application avant un remplacement atomique, avec retour arrière. WebFront n'héberge aucun serveur et ne fournit - aucune clé. +1. **Paquets.** `install()` produit un paquet CMake `WebFront` écrit à la main, indépendant de l'architecture. Les en-têtes + des révisions épinglées de stdnet et stdexec sont installés à part (`include/webfront-deps/`) ; une cible du projet de + même nom les remplace. Le port vcpkg (superposé) et la recette Conan, tenus dans `cmake/packaging/`, construisent le + dépôt où ils se trouvent et vérifient les archives des dépendances par leur empreinte. Après leur installation, le projet + consommateur se configure sans réseau. Les frontends système sont des composants ; CEF n'est pas dans le paquet. +2. **Empaquetage.** `webfront_package()` configure CPack, un installeur par système : paquet Debian, image disque macOS + (glisser-déposer) et installeur NSIS. Il ne contient que ce que l'application installe. La signature est une commande + fournie par l'application, exécutée sur l'exécutable (ou le bundle) mis en scène ; WebFront ne signe rien. Le profil + AppArmor de WebKitGTK n'est empaqueté que si l'application déclare l'ABI 4.0 visée. Le runtime WebView2 est détecté ; + son amorceur, s'il est fourni par l'application, est exécuté. +3. **SBOM.** `webfront_write_sbom()`, en CMake seul, énumère ce que la construction connaît, avec les licences que les + sources déclarent, la bibliothèque standard, les moteurs web et les bibliothèques système déclarées. +4. **Mise à jour.** Composant facultatif hors du cœur (ADR-010). Signature **ECDSA P-256 / SHA-256** en DER, vérifiée par + CNG, Security.framework ou la libcrypto d'OpenSSL ; aucune cryptographie n'est écrite par WebFront. La clé publique est + celle de l'application. Le candidat est copié à côté de l'exécutable, la copie est vérifiée, l'ancien exécutable est + conservé jusqu'à confirmation, et un état sur disque permet à `recover()` de réparer une interruption. ## Options écartées et motifs - Générer le SBOM par un outil tiers : il ne connaît ni les révisions récupérées par CMake ni le verrou `wf`. - Un outil d'empaquetage propre à WebFront : CPack et les outils de chaque plateforme existent. +- Dépendre de ports `stdnet`/`stdexec` des gestionnaires : leurs révisions ne seraient pas celles que WebFront teste. +- Ed25519 : CNG ne le fournit pas ; il aurait fallu une bibliothèque tierce ou une implémentation propre sous Windows. +- WiX/MSIX et paquet `.pkg` : outils absents des machines de construction par défaut ou identité de signature requise. +- RPM et AppImage : non vérifiés par la CI ; l'application peut ajouter les générateurs CPack qu'elle teste. ## Conséquences -- **Bénéfice :** la liste des dépendances connues de la construction est produite par la construction. -- **Limite :** le SBOM n'énumère ni les bibliothèques système ni le moteur web, et ne déclare pas de licences ; les - paquets du verrou sont une borne supérieure du JavaScript livré. -- **Reste à faire :** ports, installeurs et mise à jour vérifiée. +- **Bénéfice :** paquets, installeurs et mise à jour sans clé, serveur ni outil propre à WebFront. +- **Limite :** sous Windows le remplacement n'est pas atomique (deux renommages) ; une coupure entre les deux demande que + `recover()` soit lancé par autre chose que l'exécutable absent. +- **Limite :** une signature ne protège pas contre le retour à une ancienne version signée : la comparaison des versions + est à l'application, comme le transport, la rotation et la révocation des clés. +- **Limite :** l'actualisation d'un bundle macOS entier ou d'une installation système n'est pas couverte. +- **Limite :** le SBOM n'analyse pas le binaire et ne conclut aucune licence. +- **Reste à l'application :** publication des ports dans un registre, identités de signature, notarisation, serveur et + protocole de mise à jour. ## Prescriptions d'implémentation et de génération de code - Que les révisions inscrites soient lues dans les sources qu'utilise la construction, jamais supposées d'après l'épinglage ; qu'une révision inconnue soit dite `NOASSERTION`. - Qu'aucune documentation ne présente le SBOM comme une conformité. +- Que le port et la recette épinglent les révisions de `cmake/WebFrontDependencies.cmake` (cas `PackagePins`). +- Que tout état qu'une interruption de la mise à jour peut laisser soit réparé par `recover()` et testé. +- Que WebFront n'implémente aucune primitive cryptographique et n'embarque aucune clé. ## Sources et vérification -- [Guide](../DISTRIBUTION.md), [WebFrontSbom](../../cmake/WebFrontSbom.cmake), test - [CheckSbom](../../test/cmake/CheckSbom.cmake). +- [Guide](../DISTRIBUTION.md), [WebFrontInstall](../../cmake/WebFrontInstall.cmake), + [WebFrontPackage](../../cmake/WebFrontPackage.cmake), [WebFrontSbom](../../cmake/WebFrontSbom.cmake), + [Updater](../../include/webfront/components/update/Updater.hpp). +- Tests [CheckSbom](../../test/cmake/CheckSbom.cmake), [CheckInstalledPackage](../../test/cmake/CheckInstalledPackage.cmake), + [CheckApplicationPackage](../../test/cmake/CheckApplicationPackage.cmake), + [CheckLifeInstaller](../../test/cmake/CheckLifeInstaller.cmake), [UpdaterTests](../../test/unit/UpdaterTests.cpp) ; job + `packages` (vcpkg, Conan) de `BuildAndTest.yml`. diff --git a/docs/adr/README.md b/docs/adr/README.md index f099ad50..2bed93b3 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -70,7 +70,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-025](ADR-025-mcp-http-dans-l-application.md) | The application serves MCP over Streamable HTTP on its own loopback listener, with a session Bearer token, strict Host/Origin checks, per-instance discovery and no automation in distribution builds; the webfront-agent launcher is removed; amends ADR-019 | Accepted (delivery in progress) | 2026-11-21 | 1.4 — 2026-11-28 | | [ADR-026](ADR-026-configuration-mcp-persistante.md) | Stable MCP client configuration with explicit development security modes | Accepted | 2026-11-22 | 1.2 — 2026-11-22 | | [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page, shown in a floating window of the page and, for a detached panel only, in the first container that grants access (a native secondary window, else a system-browser tab); an introspectable registry of the registered C++ functions, of the JavaScript functions C++ calls and of the connected browsers, counted with relaxed atomics and timed only while an inspector reads | Accepted through 1.6; 1.7 proposed | 2026-11-25 | 1.7 — 2026-12-04 | -| [ADR-028](ADR-028-distribution.md) | Distributing an application without imposing a tool, a key or a server | Proposed | 2026-12-05 | 1.0 — 2026-12-05 | +| [ADR-028](ADR-028-distribution.md) | Distributing an application without imposing a tool, a key or a server: an installed CMake package with a vcpkg overlay port and a Conan recipe, CPack installers (Debian, disk image, NSIS) signed only by the application's command, an SPDX bill of materials, and an optional updater verifying ECDSA P-256 with the system's cryptography before a swap with rollback | Accepted | 2026-12-05 | 2.0 — 2026-12-05 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -117,7 +117,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-028**. Retain historical numbers and files. + is **ADR-029**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/examples/life/LifeEmbedded.cpp b/examples/life/LifeEmbedded.cpp index 3bdfb6c1..70156feb 100644 --- a/examples/life/LifeEmbedded.cpp +++ b/examples/life/LifeEmbedded.cpp @@ -14,10 +14,21 @@ #include "LifeFrontend.hpp" #include +#include int main(int argc, char** argv) { + // The check of an installed copy (docs/DISTRIBUTION.md): the embedded interface is there, without a window or a server. + if (argc == 2 && std::string_view{argv[1]} == "--check") { + for (const auto* asset : {"index.html", "app.js", "app.css"}) + if (!webfront::fs::LifeUI::open(asset)) { + std::cerr << "The embedded interface lacks " << asset << '\n'; + return 1; + } + std::cout << "WebFront Life " << webfront::version << ": embedded interface present\n"; + return 0; + } if (!webfront::demo::applyPortOption(argc, argv) || argc != 1) { - std::cerr << "Usage: WebFrontLifeEmbedded [--port ] (WEBFRONT_PORT=0 asks for a free port)\n"; + std::cerr << "Usage: WebFrontLifeEmbedded [--port ] (WEBFRONT_PORT=0 asks for a free port) | --check\n"; return 2; } try { diff --git a/examples/life/package/CMakeLists.txt b/examples/life/package/CMakeLists.txt new file mode 100644 index 00000000..b5fc5aca --- /dev/null +++ b/examples/life/package/CMakeLists.txt @@ -0,0 +1,43 @@ +# The installer of the embedded Game of Life (docs/DISTRIBUTION.md), a project of its own that uses WebFront as an +# application does. WEBFRONT_LIFE_ASSETS names the LifeUI.hpp written by `wf embed` (README, Game of Life walkthrough). +# +# cmake -S examples/life/package -B build-life -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_LIFE_ASSETS= +# cmake --build build-life --config Release +# cd build-life && cpack -C Release +cmake_minimum_required(VERSION 3.31) +project(WebFrontLifePackage LANGUAGES CXX VERSION 1.0.0) + +set(WEBFRONT_LIFE_ASSETS "" CACHE FILEPATH "LifeUI.hpp generated by wf embed") +if(NOT EXISTS "${WEBFRONT_LIFE_ASSETS}") + message(FATAL_ERROR "WEBFRONT_LIFE_ASSETS must name the LifeUI.hpp generated by wf embed") +endif() +# The lock of the project that wrote the provider (its `generated/` directory), for the bill of materials. +cmake_path(GET WEBFRONT_LIFE_ASSETS PARENT_PATH _life_project) +cmake_path(GET _life_project PARENT_PATH _life_project) +set(WEBFRONT_LIFE_LOCK "${_life_project}/webfront-packages.lock.json" CACHE FILEPATH "wf lock of the Life interface") +if(NOT EXISTS "${WEBFRONT_LIFE_LOCK}") + message(FATAL_ERROR "WEBFRONT_LIFE_LOCK must name the webfront-packages.lock.json of the Life project") +endif() +# GCC 16 crashes in stdexec when CMake scans for C++ modules, which nothing here uses. +set(CMAKE_CXX_SCAN_FOR_MODULES OFF) +# The installed application needs no Visual C++ redistributable. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +add_subdirectory(../../.. webfront EXCLUDE_FROM_ALL) + +add_executable(webfront-life ../LifeEmbedded.cpp) +target_link_libraries(webfront-life PRIVATE WebFront::WebFront) +target_compile_definitions(webfront-life PRIVATE WEBFRONT_LIFE_ASSETS_HEADER="${WEBFRONT_LIFE_ASSETS}") +if(MSVC) + target_compile_options(webfront-life PRIVATE /bigobj) +endif() +webfront_use_native_window(webfront-life) + +set(abi "") +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(abi APPARMOR_ABI 4.0) +endif() +webfront_package(webfront-life NAME "WebFront Life" VERSION ${PROJECT_VERSION} + DESCRIPTION "Game of Life served from an embedded interface" VENDOR "WebFront example" + IDENTIFIER org.webfront.example.life CONTACT "WebFront example " + LICENSE_FILE "${CMAKE_CURRENT_SOURCE_DIR}/../../../LICENSE" ${abi} + SBOM SBOM_ARGUMENTS LOCK "${WEBFRONT_LIFE_LOCK}") diff --git a/include/webfront/components/update/Signature.hpp b/include/webfront/components/update/Signature.hpp new file mode 100644 index 00000000..278a15dd --- /dev/null +++ b/include/webfront/components/update/Signature.hpp @@ -0,0 +1,282 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — components/update +// Role: Verifies the ECDSA P-256 / SHA-256 signature of a file with the cryptography of the operating system. +// Thread: worker-safe | Alloc: unrestricted +// LLM: never implement cryptography here: OpenSSL, CNG and Security.framework do it; only encodings are parsed + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif +// clang-format off: bcrypt.h needs the types of windows.h + #include + #include +// clang-format on +#elif defined(__APPLE__) + #include + #include + #include +#else + #include + #include +#endif + +namespace webfront::update { + +enum class Errc { + invalidKey, ///< the public key is not an ECDSA P-256 key + invalidSignature, ///< the signature does not match the file and the key + pending, ///< a previous update is neither confirmed nor rolled back + io, ///< a file could not be read, written or renamed + crypto ///< the operating system's cryptography failed +}; + +class UpdateError : public std::runtime_error { +public: + UpdateError(Errc errorCode, const std::string& what) : std::runtime_error(what), errc(errorCode) { } + [[nodiscard]] Errc code() const noexcept { + return errc; + } + +private: + Errc errc; +}; + +namespace detail { + +// The DER prefix of a SubjectPublicKeyInfo that holds an uncompressed point of the curve prime256v1; the point follows. +inline constexpr std::array p256KeyPrefix{0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, + 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00}; + +[[nodiscard]] inline std::optional> decodeBase64(std::string_view text) { + std::vector bytes; + std::uint32_t buffer = 0; + int bits = 0; + bool padding = false; + for (const char c : text) { + if (c == '\r' || c == '\n' || c == ' ' || c == '\t') + continue; + if (c == '=') { + padding = true; + continue; + } + std::uint32_t value = 0; + if (c >= 'A' && c <= 'Z') + value = static_cast(c - 'A'); + else if (c >= 'a' && c <= 'z') + value = static_cast(c - 'a' + 26); + else if (c >= '0' && c <= '9') + value = static_cast(c - '0' + 52); + else if (c == '+') + value = 62; + else if (c == '/') + value = 63; + else + return std::nullopt; + if (padding) + return std::nullopt; + buffer = ((buffer << 6) | value) & 0xFFFFFF; + bits += 6; + if (bits >= 8) { + bits -= 8; + bytes.push_back(static_cast(buffer >> bits)); + } + } + return bytes; +} + +/// The r||s form (32 bytes each) of a DER ECDSA signature of P-256, or nothing when the encoding is not strict DER. +[[nodiscard]] inline std::optional> rawSignature(std::span der) { + const auto at = [&](std::size_t i) { + return static_cast(der[i]); + }; + if (der.size() < 8 || der.size() > 72 || at(0) != 0x30 || at(1) != der.size() - 2) + return std::nullopt; + std::array raw{}; + std::size_t position = 2; + for (std::size_t part = 0; part < 2; ++part) { + if (position + 2 > der.size() || at(position) != 0x02) + return std::nullopt; + std::size_t length = at(position + 1); + position += 2; + if (length == 0 || length > 33 || position + length > der.size() || (at(position) & 0x80) != 0) + return std::nullopt; + if (at(position) == 0 && length > 1) { + if ((at(position + 1) & 0x80) == 0) + return std::nullopt; // a superfluous leading zero + ++position; + --length; + } + if (length > 32) + return std::nullopt; + for (std::size_t i = 0; i < length; ++i) + raw[part * 32 + 32 - length + i] = at(position + i); + position += length; + } + if (position != der.size()) + return std::nullopt; + return raw; +} + +/// Feeds the file to `update` in blocks. +template +void readBlocks(const std::filesystem::path& file, Update&& update) { + std::ifstream stream(file, std::ios::binary); + if (!stream) + throw UpdateError(Errc::io, "cannot read " + file.string()); + std::vector block(std::size_t{1} << 16); + while (stream) { + stream.read(block.data(), static_cast(block.size())); + if (const auto count = stream.gcount(); count > 0) + update(block.data(), static_cast(count)); + } + if (stream.bad()) + throw UpdateError(Errc::io, "cannot read " + file.string()); +} + +} // namespace detail + +/// An ECDSA P-256 public key: the application's own, embedded in the application. +class PublicKey { +public: + /// From the PEM text that `openssl ec -in key.pem -pubout` writes. + [[nodiscard]] static PublicKey fromPem(std::string_view pem) { + constexpr std::string_view begin = "-----BEGIN PUBLIC KEY-----", end = "-----END PUBLIC KEY-----"; + const auto first = pem.find(begin); + const auto last = pem.find(end); + if (first == std::string_view::npos || last == std::string_view::npos || last < first + begin.size()) + throw UpdateError(Errc::invalidKey, "not a PEM public key"); + const auto der = detail::decodeBase64(pem.substr(first + begin.size(), last - first - begin.size())); + if (!der || der->size() != detail::p256KeyPrefix.size() + 65 || !std::equal(detail::p256KeyPrefix.begin(), detail::p256KeyPrefix.end(), der->begin()) + || (*der)[detail::p256KeyPrefix.size()] != 0x04) + throw UpdateError(Errc::invalidKey, "not an ECDSA P-256 public key (prime256v1, uncompressed)"); + PublicKey key; + std::copy(der->begin() + detail::p256KeyPrefix.size(), der->end(), key.bytes.begin()); + return key; + } + + /// The uncompressed point, 0x04 followed by X and Y. + [[nodiscard]] const std::array& point() const noexcept { + return bytes; + } + +private: + PublicKey() = default; + std::array bytes{}; +}; + +/// True when `signature`, a DER ECDSA signature (`openssl dgst -sha256 -sign key.pem -out app.sig app`), is that of the +/// content of `file` for `key`. Throws UpdateError when the file cannot be read or the system's cryptography fails. +[[nodiscard]] inline bool verifySignature(const std::filesystem::path& file, std::span signature, const PublicKey& key) { + const auto raw = detail::rawSignature(signature); + if (!raw) + return false; +#if defined(_WIN32) + struct Algorithm { + BCRYPT_ALG_HANDLE handle{}; + explicit Algorithm(LPCWSTR name) { + if (BCryptOpenAlgorithmProvider(&handle, name, nullptr, 0) != 0) + throw UpdateError(Errc::crypto, "CNG provider unavailable"); + } + ~Algorithm() { + BCryptCloseAlgorithmProvider(handle, 0); + } + Algorithm(const Algorithm&) = delete; + Algorithm& operator=(const Algorithm&) = delete; + }; + Algorithm sha{BCRYPT_SHA256_ALGORITHM}; + Algorithm ecdsa{BCRYPT_ECDSA_P256_ALGORITHM}; + BCRYPT_HASH_HANDLE hash{}; + if (BCryptCreateHash(sha.handle, &hash, nullptr, 0, nullptr, 0, 0) != 0) + throw UpdateError(Errc::crypto, "CNG hash unavailable"); + const std::unique_ptr hashOwner{hash, &BCryptDestroyHash}; + detail::readBlocks(file, [&](char* data, std::size_t size) { + if (BCryptHashData(hash, reinterpret_cast(data), static_cast(size), 0) != 0) + throw UpdateError(Errc::crypto, "CNG hashing failed"); + }); + std::array digest{}; + if (BCryptFinishHash(hash, digest.data(), static_cast(digest.size()), 0) != 0) + throw UpdateError(Errc::crypto, "CNG hashing failed"); + std::array blob{}; + const BCRYPT_ECCKEY_BLOB header{BCRYPT_ECDSA_PUBLIC_P256_MAGIC, 32}; + std::copy_n(reinterpret_cast(&header), sizeof(header), blob.begin()); + std::copy(key.point().begin() + 1, key.point().end(), blob.begin() + sizeof(header)); + BCRYPT_KEY_HANDLE publicKey{}; + if (BCryptImportKeyPair(ecdsa.handle, nullptr, BCRYPT_ECCPUBLIC_BLOB, &publicKey, blob.data(), static_cast(blob.size()), 0) != 0) + throw UpdateError(Errc::invalidKey, "the point of the public key is not on the curve"); + const std::unique_ptr keyOwner{publicKey, &BCryptDestroyKey}; + auto copy = *raw; + return BCryptVerifySignature(publicKey, nullptr, digest.data(), static_cast(digest.size()), copy.data(), static_cast(copy.size()), 0) == 0; +#elif defined(__APPLE__) + using Owner = std::unique_ptr; + const auto data = [](const void* bytes, std::size_t size) { + auto* value = CFDataCreate(nullptr, static_cast(bytes), static_cast(size)); + if (!value) + throw UpdateError(Errc::crypto, "CFData allocation failed"); + return value; + }; + CC_SHA256_CTX context; + CC_SHA256_Init(&context); + detail::readBlocks(file, [&](char* block, std::size_t size) { + CC_SHA256_Update(&context, block, static_cast(size)); + }); + std::array digest{}; + CC_SHA256_Final(digest.data(), &context); + const int bits = 256; + const Owner size{CFNumberCreate(nullptr, kCFNumberIntType, &bits), &CFRelease}; + const void* names[] = {kSecAttrKeyType, kSecAttrKeyClass, kSecAttrKeySizeInBits}; + const void* values[] = {kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClassPublic, size.get()}; + const Owner attributes{CFDictionaryCreate(nullptr, names, values, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks), &CFRelease}; + const Owner point{data(key.point().data(), key.point().size()), &CFRelease}; + const auto publicKey = SecKeyCreateWithData(static_cast(point.get()), static_cast(attributes.get()), nullptr); + if (!publicKey) + throw UpdateError(Errc::invalidKey, "the point of the public key is not on the curve"); + const Owner keyOwner{publicKey, &CFRelease}; + const Owner digestData{data(digest.data(), digest.size()), &CFRelease}; + const Owner signatureData{data(signature.data(), signature.size()), &CFRelease}; + return SecKeyVerifySignature(publicKey, + kSecKeyAlgorithmECDSASignatureDigestX962SHA256, + static_cast(digestData.get()), + static_cast(signatureData.get()), + nullptr); +#else + std::vector der(detail::p256KeyPrefix.begin(), detail::p256KeyPrefix.end()); + der.insert(der.end(), key.point().begin(), key.point().end()); + const unsigned char* cursor = der.data(); + const std::unique_ptr publicKey{d2i_PUBKEY(nullptr, &cursor, static_cast(der.size())), &EVP_PKEY_free}; + if (!publicKey) + throw UpdateError(Errc::invalidKey, "the point of the public key is not on the curve"); + const std::unique_ptr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!context || EVP_DigestVerifyInit(context.get(), nullptr, EVP_sha256(), nullptr, publicKey.get()) != 1) + throw UpdateError(Errc::crypto, "OpenSSL cannot verify ECDSA P-256"); + detail::readBlocks(file, [&](char* block, std::size_t size) { + if (EVP_DigestVerifyUpdate(context.get(), block, size) != 1) + throw UpdateError(Errc::crypto, "OpenSSL hashing failed"); + }); + return EVP_DigestVerifyFinal(context.get(), reinterpret_cast(signature.data()), signature.size()) == 1; +#endif +} + +} // namespace webfront::update diff --git a/include/webfront/components/update/Updater.hpp b/include/webfront/components/update/Updater.hpp new file mode 100644 index 00000000..09ab1777 --- /dev/null +++ b/include/webfront/components/update/Updater.hpp @@ -0,0 +1,387 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — components/update +// Role: Replaces an executable with a signed one, keeping the former until the new one is confirmed, with rollback. +// Thread: worker-safe | Alloc: unrestricted +// LLM: optional component outside the core (ADR-010, ADR-028); every state a crash can leave must be handled by recover() + +#pragma once + +#include "Signature.hpp" + +#include +#include +#include +#include + +#if !defined(_WIN32) + #include + + #include + #include + #include + #if defined(__APPLE__) + #include + #endif +#endif + +namespace webfront::update { + +/// The points of apply() where a test, or a host, may observe the update. An exception thrown there leaves the files as +/// they are, as a power cut would; recover() then repairs them. +enum class Step { + staged, ///< the candidate is copied beside the executable, not yet verified + verified, ///< the copy has the expected signature + prepared, ///< the former executable is kept and the swap is announced + movedAside, ///< Windows only: the former executable is moved away and the new one not yet in place + swapped ///< the new executable is in place, not yet recorded as pending +}; + +enum class Recovery { + none, ///< nothing to do + abandoned, ///< an interrupted update was dropped: the former executable stays + restored, ///< the executable was missing and the former one is back + pending, ///< the new executable runs and still waits for confirm() + rolledBack ///< the new executable was not confirmed in time: the former one is back +}; + +/// The path of the running executable. +[[nodiscard]] inline std::filesystem::path executablePath() { +#if defined(_WIN32) + std::wstring buffer(512, L'\0'); + for (;;) { + const DWORD length = GetModuleFileNameW(nullptr, buffer.data(), static_cast(buffer.size())); + if (length == 0) + throw UpdateError(Errc::io, "cannot find the running executable"); + if (length < buffer.size()) + return std::filesystem::path{buffer.substr(0, length)}; + buffer.resize(buffer.size() * 2); + } +#elif defined(__APPLE__) + std::uint32_t size = 0; + _NSGetExecutablePath(nullptr, &size); + std::string buffer(size, '\0'); + if (_NSGetExecutablePath(buffer.data(), &size) != 0) + throw UpdateError(Errc::io, "cannot find the running executable"); + return std::filesystem::canonical(buffer.c_str()); +#else + return std::filesystem::read_symlink("/proc/self/exe"); +#endif +} + +/** + * Updates one executable file. Beside `app`, it uses `app.update-new` (the staged candidate), `app.update-old` (the former + * executable), `app.update-state` and, on Windows, `app.update-failed`. + * + * Updater updater{executablePath()}; + * updater.recover(); // at start-up + * updater.apply(download, signature, key); // then restart the application + * updater.confirm(); // in the new version, once it works + * + * On Linux and macOS the swap is one atomic rename. Windows cannot replace a running image: the former executable is renamed + * away and the new one renamed in place; between the two the executable is missing, and recover(), run by whatever starts the + * application, restores it. One updater at a time works on an executable. Fetching the candidate and its signature, version + * comparison (a signature says who built a file, not that it is newer) and restarting are the application's. + */ +class Updater { +public: + using Checkpoint = std::function; + + explicit Updater(std::filesystem::path executableFile, Checkpoint observer = {}) : target(std::move(executableFile)), checkpoint(std::move(observer)) { } + + /// Copies `candidate` beside the executable, verifies the copy and swaps it in. The executable is untouched unless the + /// signature is right. Throws UpdateError. + void apply(const std::filesystem::path& candidate, std::span signature, const PublicKey& key) { + std::error_code error; + if (!std::filesystem::is_regular_file(std::filesystem::symlink_status(target, error))) + throw UpdateError(Errc::io, target.string() + " is not a regular file"); + if (readState()) + throw UpdateError(Errc::pending, "an update of " + target.string() + " is pending: confirm(), rollback() or recover() first"); + const auto staged = stagedPath(), backup = backupPath(); + removeFile(staged); + removeFile(backup); + removeFile(failedPath()); + copyNew(candidate, staged); + notify(Step::staged); + bool valid = false; + try { + valid = verifySignature(staged, signature, key); + } catch (...) { + removeFile(staged); + throw; + } + if (!valid) { + removeFile(staged); + throw UpdateError(Errc::invalidSignature, "the signature of " + candidate.string() + " is not valid"); + } + notify(Step::verified); + std::filesystem::permissions(staged, std::filesystem::status(target).permissions(), error); + if (error) + abandon("cannot set the permissions of " + staged.string() + ": " + error.message()); +#if !defined(_WIN32) + // A second name for the former executable: the swap then replaces the first one without a moment without it. + std::filesystem::create_hard_link(target, backup, error); + if (error) { + copyNew(target, backup); + std::filesystem::permissions(backup, std::filesystem::status(target).permissions(), error); + if (error) + abandon("cannot keep the former executable: " + error.message()); + } +#endif + writeState("swapping"); + notify(Step::prepared); + swapIn(staged); + notify(Step::swapped); + writeState("pending 0"); + } + + /// Records that the new executable works: the former one is dropped. + void confirm() { + std::error_code error; + std::filesystem::remove(statePath(), error); + if (error) + throw UpdateError(Errc::io, "cannot remove " + statePath().string() + ": " + error.message()); + // On Windows the former executable may still be running: the next update or recovery removes it. + removeFile(backupPath()); + removeFile(failedPath()); + } + + /// Puts the former executable back; false when none is kept. + bool rollback() { + std::error_code error; + if (!std::filesystem::exists(backupPath(), error)) + return false; +#if defined(_WIN32) + removeFile(failedPath()); + if (std::filesystem::exists(target, error)) + renameFile(target, failedPath()); + renameFile(backupPath(), target); + removeFile(failedPath()); // refused while it runs: confirm(), recover() or the next apply() removes it +#else + renameFile(backupPath(), target); + syncDirectory(); + removeFile(backupPath()); // rename() keeps both names when they are the same file +#endif + removeFile(stagedPath()); + removeFile(statePath()); + return true; + } + + /** + * Call at start-up: repairs what an interrupted apply() left, and rolls back a new executable that was started + * `allowedStarts` times without confirm(). + */ + Recovery recover(unsigned allowedStarts = 3) { + std::error_code error; + const bool kept = std::filesystem::exists(backupPath(), error); + if (!std::filesystem::exists(target, error) && kept) { + renameFile(backupPath(), target); + removeFile(stagedPath()); + removeFile(statePath()); + return Recovery::restored; + } + const auto state = readState(); + if (!state) { + removeFile(stagedPath()); + removeFile(backupPath()); + removeFile(failedPath()); + return Recovery::none; + } + // A state without a former executable, and no swap left to abandon: rollback() put it back and was interrupted. + if (!kept && std::filesystem::exists(target, error) && !(*state == "swapping" && std::filesystem::exists(stagedPath(), error))) { + removeFile(stagedPath()); + removeFile(failedPath()); + removeFile(statePath()); + return Recovery::rolledBack; + } + unsigned starts = 0; + if (state->starts_with("pending ")) { + for (const char c : state->substr(8)) + if (c >= '0' && c <= '9' && starts < 100000) + starts = starts * 10 + static_cast(c - '0'); + } else if (std::filesystem::exists(stagedPath(), error)) { // the swap did not happen + removeFile(statePath()); + removeFile(stagedPath()); + removeFile(backupPath()); + return Recovery::abandoned; + } + if (starts >= allowedStarts && rollback()) + return Recovery::rolledBack; + writeState("pending " + std::to_string(starts + 1)); + return Recovery::pending; + } + + [[nodiscard]] std::filesystem::path stagedPath() const { + return sibling(".update-new"); + } + [[nodiscard]] std::filesystem::path backupPath() const { + return sibling(".update-old"); + } + [[nodiscard]] std::filesystem::path statePath() const { + return sibling(".update-state"); + } + [[nodiscard]] std::filesystem::path failedPath() const { + return sibling(".update-failed"); + } + +private: + std::filesystem::path target; + Checkpoint checkpoint; + + [[nodiscard]] std::filesystem::path sibling(const char* suffix) const { + auto path = target; + path += suffix; + return path; + } + + void notify(Step step) const { + if (checkpoint) + checkpoint(step); + } + + static void removeFile(const std::filesystem::path& path) noexcept { + std::error_code error; + std::filesystem::remove(path, error); + } + + [[noreturn]] void abandon(const std::string& reason) { + removeFile(statePath()); + removeFile(stagedPath()); + removeFile(backupPath()); + throw UpdateError(Errc::io, reason); + } + + static void renameFile(const std::filesystem::path& from, const std::filesystem::path& to) { +#if defined(_WIN32) + if (!MoveFileExW(from.c_str(), to.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + throw UpdateError(Errc::io, "cannot rename " + from.string() + " (error " + std::to_string(GetLastError()) + ")"); +#else + std::error_code error; + std::filesystem::rename(from, to, error); + if (error) + throw UpdateError(Errc::io, "cannot rename " + from.string() + ": " + error.message()); +#endif + } + + void swapIn(const std::filesystem::path& staged) { +#if defined(_WIN32) + try { + renameFile(target, backupPath()); + } catch (const UpdateError& error) { + abandon(error.what()); + } + notify(Step::movedAside); + try { + renameFile(staged, target); + } catch (const UpdateError& error) { + renameFile(backupPath(), target); + abandon(error.what()); + } +#else + try { + renameFile(staged, target); + } catch (const UpdateError& error) { + abandon(error.what()); + } + syncDirectory(); +#endif + } + + /// Copies `from` into a file that must not exist, and flushes it to the disk. + static void copyNew(const std::filesystem::path& from, const std::filesystem::path& to) { +#if defined(_WIN32) + if (!CopyFileW(from.c_str(), to.c_str(), TRUE)) + throw UpdateError(Errc::io, "cannot copy " + from.string() + " (error " + std::to_string(GetLastError()) + ")"); + // CopyFileW keeps the read-only attribute: clear it to flush, and so that the file can be replaced later. + SetFileAttributesW(to.c_str(), FILE_ATTRIBUTE_NORMAL); + const HANDLE file = CreateFileW(to.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + const bool flushed = file != INVALID_HANDLE_VALUE && FlushFileBuffers(file); + if (file != INVALID_HANDLE_VALUE) + CloseHandle(file); + if (!flushed) { + removeFile(to); + throw UpdateError(Errc::io, "cannot flush " + to.string()); + } +#else + std::ifstream source(from, std::ios::binary); + if (!source) + throw UpdateError(Errc::io, "cannot read " + from.string()); + const int file = ::open(to.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0700); + if (file < 0) + throw UpdateError(Errc::io, "cannot create " + to.string() + ": " + std::generic_category().message(errno)); + bool written = true; + std::vector block(std::size_t{1} << 16); + while (written && source) { + source.read(block.data(), static_cast(block.size())); + auto remaining = static_cast(source.gcount()); + for (const char* data = block.data(); remaining > 0;) { + const auto count = ::write(file, data, remaining); + if (count < 0 && errno == EINTR) + continue; + if (count <= 0) { + written = false; + break; + } + data += count; + remaining -= static_cast(count); + } + } + written = written && !source.bad() && ::fsync(file) == 0; + written = ::close(file) == 0 && written; + if (!written) { + removeFile(to); + throw UpdateError(Errc::io, "cannot write " + to.string()); + } +#endif + } + +#if !defined(_WIN32) + void syncDirectory() const noexcept { + const auto parent = target.parent_path(); + const int directory = ::open(parent.empty() ? "." : parent.c_str(), O_RDONLY | O_CLOEXEC); + if (directory >= 0) { + ::fsync(directory); // some file systems refuse: the rename is still atomic + ::close(directory); + } + } +#endif + + /// Written aside then renamed, so that a state file is never half written. + void writeState(const std::string& state) const { + const auto aside = sibling(".update-state.tmp"); + { + std::ofstream stream(aside, std::ios::binary | std::ios::trunc); + stream << state; + if (!stream.flush()) + throw UpdateError(Errc::io, "cannot write " + aside.string()); + } +#if !defined(_WIN32) + if (const int file = ::open(aside.c_str(), O_RDONLY | O_CLOEXEC); file >= 0) { + ::fsync(file); + ::close(file); + } +#endif + renameFile(aside, statePath()); +#if !defined(_WIN32) + syncDirectory(); +#endif + } + + /// Empty only when there is no state file: one that cannot be read must not pass for none, which drops the backup. + [[nodiscard]] std::optional readState() const { + std::error_code error; + if (std::filesystem::symlink_status(statePath(), error).type() == std::filesystem::file_type::not_found) + return std::nullopt; + std::ifstream stream(statePath(), std::ios::binary); + std::string state; + if (stream) + std::getline(stream, state); + if (!stream.is_open() || stream.bad()) + throw UpdateError(Errc::io, "cannot read " + statePath().string()); + return state; + } +}; + +} // namespace webfront::update diff --git a/include/webfront/weblink/Messages.hpp b/include/webfront/weblink/Messages.hpp index 62229ab3..9372f65b 100644 --- a/include/webfront/weblink/Messages.hpp +++ b/include/webfront/weblink/Messages.hpp @@ -402,21 +402,20 @@ template consteval CodedType numericArrayCode() { using Element = std::remove_cv_t; static_assert(is_numeric_array_element_v, "Unsupported WebFront numeric array element type"); - if (std::is_same_v) + // Chosen at compile time: MSVC /analyze reports a switch on sizeof as a comparison of constants (C6326). + [[maybe_unused]] constexpr bool isSigned = std::is_signed_v; + if constexpr (std::is_same_v) return CodedType::arrayFloat; - if (std::is_same_v) + else if constexpr (std::is_same_v) return CodedType::arrayDouble; - const bool isSigned = std::is_signed_v; - switch (sizeof(Element)) { - case 1: - return isSigned ? CodedType::array8 : CodedType::arrayU8; - case 2: - return isSigned ? CodedType::array16 : CodedType::arrayU16; - case 4: - return isSigned ? CodedType::array32 : CodedType::arrayU32; - default: - return isSigned ? CodedType::array64 : CodedType::arrayU64; - } + else if constexpr (sizeof(Element) == 1) + return isSigned ? CodedType::array8 : CodedType::arrayU8; + else if constexpr (sizeof(Element) == 2) + return isSigned ? CodedType::array16 : CodedType::arrayU16; + else if constexpr (sizeof(Element) == 4) + return isSigned ? CodedType::array32 : CodedType::arrayU32; + else + return isSigned ? CodedType::array64 : CodedType::arrayU64; } template @@ -459,9 +458,11 @@ class Handshake : public MessageBase { // Message sent by WebFront to acknoledge a Handshake message class Ack : public MessageBase { + // Compared at compile time: MSVC /analyze reports a comparison of constants made while running (C6326). + static constexpr JSEndian nativeEndian = std::endian::native == std::endian::little ? JSEndian::little : JSEndian::big; struct Header { Command command = Command::ack; - JSEndian endian = std::endian::native == std::endian::little ? JSEndian::little : JSEndian::big; + JSEndian endian = nativeEndian; } head; static_assert(sizeof(Header) == 2, "Ack header has to be 2 bytes long"); friend class MessageBase; @@ -667,10 +668,15 @@ class FunctionCallBase : public MessageBase { if (elementCount > std::numeric_limits::max() / sizeof(Element)) throw std::length_error("WebFront array byte size overflow"); - if (numericArrayCode() == CodedType::arrayU8 && elementCount < 256) - encodeTypeHeader(CodedType::smallArrayU8, static_cast(elementCount), frame); - else - encodeTypeHeader(numericArrayCode(), static_cast(elementCount), frame); + // The element's code is tested at compile time: MSVC /analyze reports a comparison of constants (C6326). + constexpr CodedType code = numericArrayCode(); + if constexpr (code == CodedType::arrayU8) { + if (elementCount < 256) + encodeTypeHeader(CodedType::smallArrayU8, static_cast(elementCount), frame); + else + encodeTypeHeader(code, static_cast(elementCount), frame); + } else + encodeTypeHeader(code, static_cast(elementCount), frame); const auto byteCount = elementCount * sizeof(Element); reservePayload(byteCount); // its header was counted by encodeTypeHeader @@ -1459,10 +1465,13 @@ class FunctionCallBase : public MessageBase { /// Validates the header against the element type Array holds and reports where its payload starts. template static NumericArrayLayout readNumericArrayHeader(std::span data) { - using Element = std::remove_cv_t>; - const auto type = static_cast(data.front()); - const bool smallUint8 = type == CodedType::smallArrayU8; - const bool matches = smallUint8 ? numericArrayCode() == CodedType::arrayU8 : type == numericArrayCode(); + using Element = std::remove_cv_t>; + const auto type = static_cast(data.front()); + const bool smallUint8 = type == CodedType::smallArrayU8; + constexpr CodedType code = numericArrayCode(); + bool matches = type == code; + if constexpr (code == CodedType::arrayU8) + matches = matches || smallUint8; if (!matches) throw std::runtime_error("Typed array element type does not match its wire type"); diff --git a/test/cmake/CheckApplicationPackage.cmake b/test/cmake/CheckApplicationPackage.cmake new file mode 100644 index 00000000..c50db01f --- /dev/null +++ b/test/cmake/CheckApplicationPackage.cmake @@ -0,0 +1,119 @@ +# webfront_package(): refused arguments, the installer's configuration of this platform, what is staged, and the signing +# command run on the staged executable. The application is built; no installer is produced (CI does that for Life). +# cmake -DROOT= -DWORK= -DTEST_GENERATOR= -DTEST_CXX_COMPILER= -DDEPENDENCY_ARGS= +# -DCPM_MODULE= -P CheckApplicationPackage.cmake +cmake_minimum_required(VERSION 3.31) +file(REMOVE_RECURSE "${WORK}") +function(configure directory expected_error) + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/application-package" -B "${directory}" + -G "${TEST_GENERATOR}" "-DCMAKE_CXX_COMPILER=${TEST_CXX_COMPILER}" -DCMAKE_BUILD_TYPE=Release + "-DWEBFRONT_SOURCE_DIR=${ROOT}" "-DCPM_MODULE=${CPM_MODULE}" ${DEPENDENCY_ARGS} -DENABLE_CACHE=OFF + -DWEBFRONT_AUTODETECT_NATIVE=OFF ${ARGN} + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE output) + if(expected_error STREQUAL "") + if(NOT result EQUAL 0) + message(FATAL_ERROR "Configuration failed:\n${output}") + endif() + elseif(result EQUAL 0 OR NOT output MATCHES "${expected_error}") + message(FATAL_ERROR "Expected '${expected_error}', got (${result}):\n${output}") + endif() +endfunction() +function(expect_match content pattern) + if(NOT "${content}" MATCHES "${pattern}") + message(FATAL_ERROR "Missing '${pattern}' in:\n${content}") + endif() +endfunction() + +configure("${WORK}/bad-version" "requires VERSION x.y.z" -DPACKAGE_VERSION_UNDER_TEST=1.0) +configure("${WORK}/twice" "already" -DPACKAGE_VERSION_UNDER_TEST=1.0.0 -DPACKAGE_TWICE=ON) + +set(build "${WORK}/build") +configure("${build}" "" -DPACKAGE_VERSION_UNDER_TEST=1.2.3) +file(READ "${build}/CPackConfig.cmake" cpack) +expect_match("${cpack}" "CPACK_PACKAGE_NAME \"demo-app\"") +expect_match("${cpack}" "CPACK_PACKAGE_VERSION \"1.2.3\"") +expect_match("${cpack}" "webfront_app") +if(CMAKE_HOST_WIN32) + expect_match("${cpack}" "CPACK_GENERATOR \"NSIS\"") + set(executable "bin/demo-app.exe") + set(sbom "demo-app.spdx.json") +elseif(CMAKE_HOST_APPLE) + expect_match("${cpack}" "CPACK_GENERATOR \"DragNDrop\"") + set(executable "demo-app.app/Contents/MacOS/demo-app") + set(sbom "demo-app.app/Contents/Resources/demo-app.spdx.json") +else() + expect_match("${cpack}" "CPACK_GENERATOR \"DEB\"") + set(executable "bin/demo-app") + set(sbom "share/demo-app/demo-app.spdx.json") +endif() +execute_process(COMMAND "${CMAKE_COMMAND}" --build "${build}" --config Release --target demo-app COMMAND_ERROR_IS_FATAL ANY + OUTPUT_QUIET) +execute_process(COMMAND "${CMAKE_COMMAND}" --install "${build}" --config Release --component webfront_app --prefix "${WORK}/stage" + COMMAND_ERROR_IS_FATAL ANY OUTPUT_QUIET) +foreach(file "${executable}" "${sbom}") + if(NOT EXISTS "${WORK}/stage/${file}") + message(FATAL_ERROR "The staged tree lacks ${file}") + endif() +endforeach() +file(READ "${build}/signed.txt" signed) +if(CMAKE_HOST_APPLE) + expect_match("${signed}" "demo-app\\.app$") +else() + expect_match("${signed}" "demo-app(\\.exe)?$") +endif() +# Nothing of WebFront itself goes in an application's package. +if(EXISTS "${WORK}/stage/include") + message(FATAL_ERROR "The package holds WebFront's headers") +endif() + +# The desktop entry quotes the executable and escapes it as the Desktop Entry Specification asks. +if(NOT CMAKE_HOST_WIN32 AND NOT CMAKE_HOST_APPLE) + configure("${WORK}/spaces" "" -DPACKAGE_VERSION_UNDER_TEST=1.0.0 [[-DOUTPUT_NAME_UNDER_TEST=Demo App $x 100%]]) + file(STRINGS "${WORK}/spaces/webfront-package/demo-app.desktop" exec REGEX "^Exec=") + set(expected [[Exec="/usr/bin/Demo App \\$x 100%%"]]) + if(NOT exec STREQUAL expected) + message(FATAL_ERROR "Expected ${expected}, got ${exec}") + endif() +endif() + +# With the WebKitGTK engine, the package depends on it and carries the sandbox profile. Where its development files are +# absent, a stand-in is enough: the application of this test includes nothing of it. +if(NOT CMAKE_HOST_WIN32 AND NOT CMAKE_HOST_APPLE) + find_package(PkgConfig QUIET) + if(PkgConfig_FOUND) + pkg_check_modules(webkit QUIET webkitgtk-6.0) + if(NOT webkit_FOUND) + file(WRITE "${WORK}/pkgconfig/webkitgtk-6.0.pc" "Name: webkitgtk-6.0\nDescription: stand-in\nVersion: 2.0\n") + set(ENV{PKG_CONFIG_PATH} "${WORK}/pkgconfig") + endif() + configure("${WORK}/gtk" "" -DPACKAGE_VERSION_UNDER_TEST=1.0.0 -DWEBFRONT_EMBED_WEBKITGTK=ON -DAPPARMOR=ON) + file(READ "${WORK}/gtk/CPackConfig.cmake" cpack) + expect_match("${cpack}" "libwebkitgtk-6.0-4") + expect_match("${cpack}" "postinst") + file(GLOB profile "${WORK}/gtk/webfront-package/webfront-demo-app") + file(READ "${profile}" profile) + expect_match("${profile}" "\"/usr/bin/demo-app\"") + + # The built package holds the profile: nothing is installed on this machine. + find_program(dpkg_deb dpkg-deb) + find_program(dpkg_shlibdeps dpkg-shlibdeps) + find_program(file_utility file) # CPackDeb needs it for SHLIBDEPS: the CI container lacks it + if(dpkg_deb AND dpkg_shlibdeps AND file_utility) + execute_process(COMMAND "${CMAKE_COMMAND}" --build "${WORK}/gtk" --target demo-app COMMAND_ERROR_IS_FATAL ANY + OUTPUT_QUIET) + execute_process(COMMAND "${CMAKE_CPACK_COMMAND}" WORKING_DIRECTORY "${WORK}/gtk" RESULT_VARIABLE result + OUTPUT_VARIABLE output ERROR_VARIABLE output) + if(NOT result EQUAL 0) + message(FATAL_ERROR "cpack failed:\n${output}") + endif() + file(GLOB package "${WORK}/gtk/*.deb") + execute_process(COMMAND "${dpkg_deb}" --contents "${package}" OUTPUT_VARIABLE contents COMMAND_ERROR_IS_FATAL ANY) + foreach(file "etc/apparmor\\.d/webfront-demo-app" "usr/bin/demo-app" "usr/share/applications/demo-app\\.desktop" + "usr/share/demo-app/demo-app\\.spdx\\.json") + expect_match("${contents}" " \\./${file}\n") + endforeach() + else() + message(STATUS "The Debian package is not built: dpkg-deb, dpkg-shlibdeps or file is missing") + endif() + endif() +endif() diff --git a/test/cmake/CheckInstalledLayout.cmake b/test/cmake/CheckInstalledLayout.cmake new file mode 100644 index 00000000..4b6dd02d --- /dev/null +++ b/test/cmake/CheckInstalledLayout.cmake @@ -0,0 +1,164 @@ +# find_package(WebFront) on an installation with a non-default CMAKE_INSTALL_INCLUDEDIR, and a second find_package that adds +# a frontend component after a first one without it. Header-only: WebFront is configured and installed, nothing is compiled. +# cmake -DROOT= -DWORK= -DSTDNET_SOURCE= -DSTDEXEC_SOURCE= +# -DTEST_GENERATOR= -DTEST_CXX_COMPILER= -P CheckInstalledLayout.cmake +cmake_minimum_required(VERSION 3.31) +file(REMOVE_RECURSE "${WORK}") +set(prefix "${WORK}/prefix") +function(run) + execute_process(COMMAND ${ARGN} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE output) + if(NOT result EQUAL 0) + message(FATAL_ERROR "${ARGN} failed (${result}):\n${output}") + endif() +endfunction() +if(TEST_CXX_COMPILER MATCHES "cl(\\.exe)?$") + set(MSVC_COMPILER TRUE) +endif() +set(common -G "${TEST_GENERATOR}" "-DCMAKE_CXX_COMPILER=${TEST_CXX_COMPILER}" -DCMAKE_BUILD_TYPE=Release + -DCMAKE_CXX_SCAN_FOR_MODULES=OFF) +run("${CMAKE_COMMAND}" -S "${ROOT}" -B "${WORK}/webfront" ${common} -DCMAKE_INSTALL_INCLUDEDIR=headers/wf + "-DWEBFRONT_STDNET_SOURCE_DIR=${STDNET_SOURCE}" "-DWEBFRONT_STDEXEC_SOURCE_DIR=${STDEXEC_SOURCE}" + -DWEBFRONT_AUTODETECT_NATIVE=OFF -DWEBFRONT_BUILD_EXAMPLES=OFF -DWEBFRONT_ENABLE_TESTING=OFF -DENABLE_CACHE=OFF) +foreach(component WebFront WebFrontBdd) + run("${CMAKE_COMMAND}" --install "${WORK}/webfront" --prefix "${prefix}" --component ${component} --config Release) +endforeach() +if(NOT EXISTS "${prefix}/headers/wf/webfront/WebFront.hpp") + message(FATAL_ERROR "The headers were not installed in CMAKE_INSTALL_INCLUDEDIR") +endif() + +# The engine of this platform, with stand-ins for its development files where only paths and definitions are at stake. +set(component "") +set(engine_args "") +if(CMAKE_HOST_WIN32) + set(component WebView2) + set(engine_args "-DSDK=${WORK}/sdk") + file(MAKE_DIRECTORY "${WORK}/sdk/build/native/include") +elseif(CMAKE_HOST_APPLE) + set(component WKWebView) +else() + find_program(pkg_config pkg-config) + if(pkg_config) + set(component WebKitGTK) + file(WRITE "${WORK}/pkgconfig/webkitgtk-6.0.pc" "Name: webkitgtk-6.0\nDescription: stand-in\nVersion: 2.0\n") + set(ENV{PKG_CONFIG_LIBDIR} "${WORK}/pkgconfig") + endif() +endif() +file(CONFIGURE OUTPUT "${WORK}/consumer/CMakeLists.txt" CONTENT [=[ +cmake_minimum_required(VERSION 3.31) +project(Layout LANGUAGES CXX) +# Components that cannot be had here leave the package found when they are optional. +set(unavailable CEF) +if(APPLE OR WIN32) + list(APPEND unavailable WebKitGTK) +else() + list(APPEND unavailable WKWebView) +endif() +if(SDK) + list(APPEND unavailable WebView2) +elseif(NOT COMPONENT STREQUAL "WebKitGTK" AND UNIX AND NOT APPLE) + list(APPEND unavailable WebKitGTK) +endif() +if(NOT SDK AND UNIX AND NOT APPLE) + # No development files of WebKitGTK for this call. + set(pkg_config_libdir "$ENV{PKG_CONFIG_LIBDIR}") + set(ENV{PKG_CONFIG_LIBDIR} "${CMAKE_CURRENT_BINARY_DIR}/none") + list(APPEND unavailable WebKitGTK) + list(REMOVE_DUPLICATES unavailable) +endif() +find_package(WebFront CONFIG OPTIONAL_COMPONENTS ${unavailable}) +if(NOT WebFront_FOUND) + message(FATAL_ERROR "Unavailable optional components hid the package: ${WebFront_NOT_FOUND_MESSAGE}") +endif() +foreach(name IN LISTS unavailable) + if(WebFront_${name}_FOUND) + message(FATAL_ERROR "${name} was reported found") + endif() +endforeach() +if(DEFINED pkg_config_libdir) + set(ENV{PKG_CONFIG_LIBDIR} "${pkg_config_libdir}") +endif() +# Required, the same fail. +find_package(WebFront CONFIG QUIET COMPONENTS CEF) +if(WebFront_FOUND) + message(FATAL_ERROR "CEF was accepted as a required component") +endif() +find_package(WebFront CONFIG REQUIRED) +if(COMPONENT) + if(SDK) + # Without the SDK of WebView2, a later request must fail rather than report the component found. + find_package(WebFront CONFIG QUIET COMPONENTS ${COMPONENT}) + if(WebFront_FOUND) + message(FATAL_ERROR "WebView2 was reported found without its SDK") + endif() + set(WEBFRONT_WEBVIEW2_SDK_DIR "${SDK}") + endif() + find_package(WebFront CONFIG REQUIRED COMPONENTS ${COMPONENT}) + string(TOUPPER "${COMPONENT}" upper) + get_target_property(definitions WebFront::WebFront INTERFACE_COMPILE_DEFINITIONS) + if(NOT "WEBFRONT_EMBED_${upper}" IN_LIST definitions OR NOT WEBFRONT_EMBED_${upper}) + message(FATAL_ERROR "The second find_package did not set up ${COMPONENT}: ${definitions}") + endif() + # A third one does not add it twice. + find_package(WebFront CONFIG REQUIRED COMPONENTS ${COMPONENT}) + get_target_property(definitions WebFront::WebFront INTERFACE_COMPILE_DEFINITIONS) + list(FILTER definitions INCLUDE REGEX "^WEBFRONT_EMBED_${upper}$") + list(LENGTH definitions count) + if(NOT count EQUAL 1) + message(FATAL_ERROR "${COMPONENT} was set up ${count} times") + endif() +endif() +if(NOT COMMAND webfront_bdd_discover_tests) + message(FATAL_ERROR "webfront_bdd_discover_tests() is missing") +endif() +if(STANDARD) + # The stand-in below gives the standard library senders after C++23 only. + get_target_property(links stdnet::stdnet INTERFACE_LINK_LIBRARIES) + if(STANDARD GREATER 23 AND "STDEXEC::stdexec" IN_LIST links) + message(FATAL_ERROR "The senders of C++${STANDARD} were not seen: stdexec is linked") + elseif(STANDARD EQUAL 23 AND NOT "STDEXEC::stdexec" IN_LIST links) + message(FATAL_ERROR "stdexec is missing in C++23") + endif() +endif() +add_executable(app "${CMAKE_CURRENT_BINARY_DIR}/main.cpp") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp" "int main() {}\n") +target_link_libraries(app PRIVATE WebFront::WebFront WebFront::Bdd) +]=] @ONLY) +run("${CMAKE_COMMAND}" -S "${WORK}/consumer" -B "${WORK}/consumer-build" ${common} "-DCMAKE_PREFIX_PATH=${prefix}" + "-DCOMPONENT=${component}" ${engine_args}) + +# The probe of std::execution compiles in the consumer's mode, given by CMAKE_CXX_STANDARD or by a flag. +set(stand_in "${WORK}/senders.hpp") +file(WRITE "${stand_in}" "#include \n#if defined(_MSVC_LANG)\n#if _MSVC_LANG > 202302L\n#define __cpp_lib_senders 202406L\n#endif\n#elif __cplusplus > 202302L\n#define __cpp_lib_senders 202406L\n#endif\n") +if(MSVC_COMPILER) + set(include_flag "/FI") + set(latest "/std:c++latest") +else() + set(include_flag "-include ") + set(latest "-std=c++26") +endif() +function(consume name) + run("${CMAKE_COMMAND}" -S "${WORK}/consumer" -B "${WORK}/${name}" ${common} ${ARGN}) +endfunction() +if(NOT MSVC_COMPILER) + foreach(standard 23 26) + consume(standard-${standard} "-DCMAKE_PREFIX_PATH=${prefix}" -DCMAKE_CXX_STANDARD=${standard} -DSTANDARD=${standard} + "-DCMAKE_CXX_FLAGS=${include_flag}${stand_in}") + endforeach() + consume(standard-flag "-DCMAKE_PREFIX_PATH=${prefix}" -DSTANDARD=26 "-DCMAKE_CXX_FLAGS=${latest} ${include_flag}${stand_in}") +endif() + +# The component WebFront alone is a complete package. +run("${CMAKE_COMMAND}" --install "${WORK}/webfront" --prefix "${WORK}/only" --component WebFront --config Release) +consume(only-component "-DCMAKE_PREFIX_PATH=${WORK}/only") + +# So is the installation of a project that embeds WebFront and asks for its install rules. +file(CONFIGURE OUTPUT "${WORK}/parent/CMakeLists.txt" CONTENT [=[ +cmake_minimum_required(VERSION 3.31) +project(Parent LANGUAGES CXX) +add_subdirectory("@ROOT@" webfront) +]=] @ONLY) +run("${CMAKE_COMMAND}" -S "${WORK}/parent" -B "${WORK}/parent-build" ${common} -DWEBFRONT_INSTALL=ON + -DCMAKE_INSTALL_INCLUDEDIR=include "-DWEBFRONT_STDNET_SOURCE_DIR=${STDNET_SOURCE}" + "-DWEBFRONT_STDEXEC_SOURCE_DIR=${STDEXEC_SOURCE}" -DWEBFRONT_AUTODETECT_NATIVE=OFF -DENABLE_CACHE=OFF) +run("${CMAKE_COMMAND}" --install "${WORK}/parent-build" --prefix "${WORK}/embedded" --config Release) +consume(embedded "-DCMAKE_PREFIX_PATH=${WORK}/embedded") diff --git a/test/cmake/CheckInstalledPackage.cmake b/test/cmake/CheckInstalledPackage.cmake new file mode 100644 index 00000000..4018874a --- /dev/null +++ b/test/cmake/CheckInstalledPackage.cmake @@ -0,0 +1,50 @@ +# Installs WebFront from a configured build, then configures and builds the consumer project of +# test/cmake/package-consumer against that installation alone, with every proxy pointing at a closed port and +# FetchContent disconnected: nothing may be downloaded. +# cmake -DROOT= -DBUILD= -DCONFIG= -DWORK= -DTEST_GENERATOR= +# -DTEST_CXX_COMPILER= -P CheckInstalledPackage.cmake +cmake_minimum_required(VERSION 3.31) +file(REMOVE_RECURSE "${WORK}") +set(prefix "${WORK}/prefix") +set(config_args "") +if(CONFIG) + set(config_args --config "${CONFIG}") +endif() +function(run) + execute_process(COMMAND ${ARGN} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE output) + if(NOT result EQUAL 0) + message(FATAL_ERROR "${ARGN} failed (${result}):\n${output}") + endif() +endfunction() +foreach(component WebFront WebFrontBdd) + run("${CMAKE_COMMAND}" --install "${BUILD}" --prefix "${prefix}" --component ${component} ${config_args}) +endforeach() +foreach(expected include/webfront/WebFront.hpp include/webfront-deps/stdnet/network share/cmake/WebFront/WebFrontConfig.cmake) + if(NOT EXISTS "${prefix}/${expected}") + message(FATAL_ERROR "The installation lacks ${expected}") + endif() +endforeach() +# The dependencies are apart: nothing of theirs lands where another package would install it. +if(EXISTS "${prefix}/include/network" OR EXISTS "${prefix}/include/stdexec") + message(FATAL_ERROR "The installation holds dependency headers outside include/webfront-deps") +endif() + +foreach(proxy http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY) + set(ENV{${proxy}} "http://127.0.0.1:9") +endforeach() +set(ENV{CPM_SOURCE_CACHE} "") +set(consumer "${WORK}/consumer") +run("${CMAKE_COMMAND}" -S "${ROOT}/test/cmake/package-consumer" -B "${consumer}" -G "${TEST_GENERATOR}" + "-DCMAKE_CXX_COMPILER=${TEST_CXX_COMPILER}" -DCMAKE_BUILD_TYPE=Release "-DCMAKE_PREFIX_PATH=${prefix}" + -DFETCHCONTENT_FULLY_DISCONNECTED=ON -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + "-DHELLO_WORLD_SOURCE=${ROOT}/examples/hello-world/HelloWorld.cpp") +if(EXISTS "${consumer}/_deps") + message(FATAL_ERROR "The consumer fetched dependencies") +endif() +run("${CMAKE_COMMAND}" --build "${consumer}" --config Release --parallel 2) +file(READ "${consumer}/consumer.spdx.json" sbom) +foreach(name WebFront stdnet) + if(NOT sbom MATCHES "\"name\": \"${name}\"") + message(FATAL_ERROR "The consumer's SBOM lacks ${name}:\n${sbom}") + endif() +endforeach() diff --git a/test/cmake/CheckLifeInstaller.cmake b/test/cmake/CheckLifeInstaller.cmake new file mode 100644 index 00000000..b8072a64 --- /dev/null +++ b/test/cmake/CheckLifeInstaller.cmake @@ -0,0 +1,82 @@ +# Installs the installer that cpack wrote for examples/life/package, runs the installed application's own check and removes +# it again (docs/DISTRIBUTION.md). It changes the machine: CI runs it on its disposable runners (Linux as root). +# cmake -DPACKAGE_DIR= -P CheckLifeInstaller.cmake +cmake_minimum_required(VERSION 3.31) +if(NOT "$ENV{CI}" STREQUAL "true") + message(FATAL_ERROR "CheckLifeInstaller installs software: it only runs in CI (CI=true)") +endif() +function(run) + execute_process(COMMAND ${ARGN} RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE output TIMEOUT 300) + message(STATUS "${output}") + if(NOT result EQUAL 0) + message(FATAL_ERROR "${ARGN} failed: ${result}") + endif() + set(run_output "${output}" PARENT_SCOPE) +endfunction() +function(check_installed executable sbom engine) + run("${executable}" --check) + if(NOT run_output MATCHES "embedded interface present") + message(FATAL_ERROR "The installed application did not check itself") + endif() + file(READ "${sbom}" content) + foreach(name WebFront stdnet react "${engine}") + if(NOT content MATCHES "\"name\": \"${name}\"") + message(FATAL_ERROR "The installed SBOM lacks ${name}") + endif() + endforeach() +endfunction() +function(check_removed) + foreach(path IN LISTS ARGN) + if(EXISTS "${path}") + message(FATAL_ERROR "${path} remains after removal") + endif() + endforeach() +endfunction() + +if(CMAKE_HOST_WIN32) + file(GLOB installer "${PACKAGE_DIR}/webfront-life-*.exe") +else() + if(CMAKE_HOST_APPLE) + file(GLOB installer "${PACKAGE_DIR}/webfront-life-*.dmg") + else() + file(GLOB installer "${PACKAGE_DIR}/webfront-life-*.deb") + endif() +endif() +list(LENGTH installer count) +if(NOT count EQUAL 1) + message(FATAL_ERROR "Expected one installer in ${PACKAGE_DIR}, found: ${installer}") +endif() + +if(CMAKE_HOST_WIN32) + # NSIS takes /D= and _?= last and unquoted: a directory without spaces. + file(TO_CMAKE_PATH "$ENV{RUNNER_TEMP}" temp) + set(directory "${temp}/webfront-life-installed") + file(TO_NATIVE_PATH "${directory}" native) + run("${installer}" /S "/D=${native}") + check_installed("${directory}/bin/webfront-life.exe" "${directory}/webfront-life.spdx.json" "Microsoft.Web.WebView2") + run("${directory}/Uninstall.exe" /S "_?=${native}") + check_removed("${directory}/bin/webfront-life.exe" "${directory}/webfront-life.spdx.json") +elseif(CMAKE_HOST_APPLE) + set(volume "${PACKAGE_DIR}/volume") + set(application "/Applications/webfront-life.app") + check_removed("${application}") + run(hdiutil attach "${installer}" -nobrowse -readonly -mountpoint "${volume}") + run(ditto "${volume}/webfront-life.app" "${application}") + run(hdiutil detach "${volume}") + check_installed("${application}/Contents/MacOS/webfront-life" "${application}/Contents/Resources/webfront-life.spdx.json" + "WebKit.framework") + # An application installed from a disk image is removed by deleting its bundle. + file(REMOVE_RECURSE "${application}") + check_removed("${application}") +else() + run(dpkg -i "${installer}") + check_installed(/usr/bin/webfront-life /usr/share/webfront-life/webfront-life.spdx.json WebKitGTK) + foreach(file /usr/share/applications/webfront-life.desktop /etc/apparmor.d/webfront-webfront-life) + if(NOT EXISTS "${file}") + message(FATAL_ERROR "The package did not install ${file}") + endif() + endforeach() + run(dpkg --purge webfront-life) + check_removed(/usr/bin/webfront-life /usr/share/applications/webfront-life.desktop /etc/apparmor.d/webfront-webfront-life + /usr/share/webfront-life /usr/share/doc/webfront-life) +endif() diff --git a/test/cmake/CheckPackagePins.cmake b/test/cmake/CheckPackagePins.cmake new file mode 100644 index 00000000..2e8a1310 --- /dev/null +++ b/test/cmake/CheckPackagePins.cmake @@ -0,0 +1,23 @@ +# The vcpkg port and the Conan recipe build the same dependencies as the build: the revisions of +# cmake/WebFrontDependencies.cmake, and the version of WebFront. +# cmake -DROOT= -P CheckPackagePins.cmake +cmake_minimum_required(VERSION 3.31) +include("${ROOT}/cmake/WebFrontDependencies.cmake") +file(STRINGS "${ROOT}/include/webfront/WebFront.hpp" version REGEX "inline constexpr std::string_view version = ") +string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" version "${version}") +set(port "${ROOT}/cmake/packaging/vcpkg/webfront") +file(READ "${port}/portfile.cmake" portfile) +file(READ "${port}/vcpkg.json" manifest) +file(READ "${ROOT}/cmake/packaging/conan/conanfile.py" recipe) +foreach(revision ${WEBFRONT_STDNET_REVISION} ${WEBFRONT_STDEXEC_REVISION}) + foreach(content portfile recipe) + string(FIND "${${content}}" "${revision}" position) + if(position EQUAL -1) + message(FATAL_ERROR "The ${content} does not pin ${revision} (cmake/WebFrontDependencies.cmake)") + endif() + endforeach() +endforeach() +string(JSON port_version GET "${manifest}" version) +if(NOT port_version STREQUAL version OR NOT recipe MATCHES "version = \"${version}\"") + message(FATAL_ERROR "The version of the packages (${port_version}) differs from WebFront ${version}") +endif() diff --git a/test/cmake/CheckSbom.cmake b/test/cmake/CheckSbom.cmake index 4095e3de..860742fc 100644 --- a/test/cmake/CheckSbom.cmake +++ b/test/cmake/CheckSbom.cmake @@ -36,7 +36,7 @@ file(READ "${ROOT}/js/developer/webfront-packages.lock.json" lock) string(JSON locked LENGTH "${lock}" packages) string(JSON listed LENGTH "${sbom}" packages) string(JSON related LENGTH "${sbom}" relationships) -math(EXPR expected "${locked} + 5") # the application, WebFront, stdnet, stdexec and WebView2 +math(EXPR expected "${locked} + 5") # the application, WebFront, stdnet, stdexec and WebView2 (no compiler in a script) if(NOT listed EQUAL expected OR NOT related EQUAL expected) message(FATAL_ERROR "Expected ${expected} packages and relationships, got ${listed} and ${related}") endif() @@ -76,3 +76,34 @@ string(JSON earlier_namespace GET "${earlier}" documentNamespace) if(later_namespace STREQUAL earlier_namespace OR later MATCHES "\"name\": \"stdexec\"") message(FATAL_ERROR "The namespace ignores the date, or an unused stdexec is listed") endif() + +# Licenses: declared by the sources, by the application, never concluded. Engines and system libraries are listed. +webfront_write_sbom(OUTPUT "${WORK}/full.json" NAME demo VERSION 1 LICENSE MIT + LOCK "${ROOT}/js/developer/webfront-packages.lock.json" + PACKAGE extra 2 https://example.org/extra + SYSTEM OpenSSL 3.5.0 + ENGINES WebView2 WKWebView + LICENSES extra BSD-3-Clause OpenSSL Apache-2.0 "WebView2 Runtime" "not an expression!") +file(READ "${WORK}/full.json" full) +string(JSON count LENGTH "${full}" packages) +math(EXPR last "${count} - 1") +foreach(index RANGE ${last}) + string(JSON name GET "${full}" packages ${index} name) + string(JSON license GET "${full}" packages ${index} licenseDeclared) + string(JSON concluded GET "${full}" packages ${index} licenseConcluded) + if(NOT concluded STREQUAL "NOASSERTION") + message(FATAL_ERROR "A license was concluded for ${name}") + endif() + string(MAKE_C_IDENTIFIER "${name}" key) + set(license_${key} "${license}") +endforeach() +foreach(expected "demo=MIT" "WebFront=Apache-2.0 OR CECILL-B" "stdnet=Apache-2.0 WITH LLVM-exception" "react=MIT" + "extra=BSD-3-Clause" "OpenSSL=Apache-2.0" "WebView2 Runtime=NOASSERTION" "WebKit.framework=NOASSERTION" + "Microsoft.Web.WebView2=NOASSERTION") + string(REGEX REPLACE "=.*" "" name "${expected}") + string(REGEX REPLACE "^[^=]*=" "" license "${expected}") + string(MAKE_C_IDENTIFIER "${name}" key) + if(NOT "${license_${key}}" STREQUAL license) + message(FATAL_ERROR "License of ${name}: '${license_${key}}', expected '${license}'") + endif() +endforeach() diff --git a/test/cmake/application-package/CMakeLists.txt b/test/cmake/application-package/CMakeLists.txt new file mode 100644 index 00000000..29ad0200 --- /dev/null +++ b/test/cmake/application-package/CMakeLists.txt @@ -0,0 +1,25 @@ +# An application packaged with webfront_package(), checked by CheckApplicationPackage.cmake. +cmake_minimum_required(VERSION 3.31) +project(ApplicationPackage LANGUAGES CXX VERSION 1.0.0) +set(CMAKE_CXX_SCAN_FOR_MODULES OFF) +if(CPM_MODULE) + file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/cmake") + get_filename_component(cpm_filename "${CPM_MODULE}" NAME) + file(COPY_FILE "${CPM_MODULE}" "${CMAKE_BINARY_DIR}/cmake/${cpm_filename}" ONLY_IF_DIFFERENT) +endif() +add_subdirectory("${WEBFRONT_SOURCE_DIR}" webfront EXCLUDE_FROM_ALL) +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp" "int main() {}\n") +add_executable(demo-app "${CMAKE_CURRENT_BINARY_DIR}/main.cpp") +if(OUTPUT_NAME_UNDER_TEST) + set_target_properties(demo-app PROPERTIES OUTPUT_NAME "${OUTPUT_NAME_UNDER_TEST}") +endif() +set(abi "") +if(APPARMOR) + set(abi APPARMOR_ABI 4.0) +endif() +webfront_package(demo-app NAME "Demo App" VERSION ${PACKAGE_VERSION_UNDER_TEST} ${abi} + SBOM SBOM_ARGUMENTS ENGINES NONE + SIGN_COMMAND "${CMAKE_COMMAND}" "-DRECORD=${CMAKE_BINARY_DIR}/signed.txt" -P "${CMAKE_CURRENT_SOURCE_DIR}/Sign.cmake") +if(PACKAGE_TWICE) + webfront_package(demo-app VERSION 1.0.0) +endif() diff --git a/test/cmake/application-package/Sign.cmake b/test/cmake/application-package/Sign.cmake new file mode 100644 index 00000000..878415ad --- /dev/null +++ b/test/cmake/application-package/Sign.cmake @@ -0,0 +1,7 @@ +# Stands for a signing tool: records the path it is given, and fails on request. +math(EXPR last "${CMAKE_ARGC} - 1") +set(path "${CMAKE_ARGV${last}}") +if(NOT EXISTS "${path}") + message(FATAL_ERROR "Nothing to sign at ${path}") +endif() +file(WRITE "${RECORD}" "${path}") diff --git a/test/cmake/package-consumer/CMakeLists.txt b/test/cmake/package-consumer/CMakeLists.txt new file mode 100644 index 00000000..34813b0f --- /dev/null +++ b/test/cmake/package-consumer/CMakeLists.txt @@ -0,0 +1,16 @@ +# A consuming project of the installed WebFront package (find_package), as installed by cmake --install, by the vcpkg overlay +# port or by the Conan recipe: it builds Hello World and uses the public helpers of the package (docs/DISTRIBUTION.md). +cmake_minimum_required(VERSION 3.31) +project(WebFrontPackageConsumer LANGUAGES CXX VERSION 1.0.0) + +set(HELLO_WORLD_SOURCE "" CACHE FILEPATH "examples/hello-world/HelloWorld.cpp of a WebFront checkout") +find_package(WebFront CONFIG REQUIRED) + +add_executable(HelloWorld "${HELLO_WORLD_SOURCE}") +target_link_libraries(HelloWorld PRIVATE WebFront::WebFront) +webfront_use_native_window(HelloWorld) + +# The helpers of the package work without a WebFront checkout. +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/interface/index.html" "x\n") +webfront_embed_directory(HelloWorld "${CMAKE_CURRENT_BINARY_DIR}/interface" CLASS ConsumerAssets NAMESPACE consumer) +webfront_write_sbom(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/consumer.spdx.json" NAME consumer VERSION 1.0.0) diff --git a/test/cmake/package-consumer/conanfile.txt b/test/cmake/package-consumer/conanfile.txt new file mode 100644 index 00000000..06887dca --- /dev/null +++ b/test/cmake/package-consumer/conanfile.txt @@ -0,0 +1,6 @@ +[requires] +webfront/1.3.0 + +[generators] +CMakeDeps +CMakeToolchain diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 6a7d80f7..30f726c9 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -162,6 +162,32 @@ endif() add_executable(forms_declaration FormsDeclaration.cpp) target_link_libraries(forms_declaration PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options WebFront) +# The optional verified updater (docs/DISTRIBUTION.md), in its own executable: it links the cryptography of the system, +# OpenSSL's libcrypto on Linux, which the other tests must not need. CI requires it so that it cannot be skipped there. +option(WEBFRONT_REQUIRE_UPDATER_TESTS "Fail the configuration when the updater tests cannot be built" OFF) +set(_updater_tests ON) +if(NOT WIN32 AND NOT APPLE) + find_package(OpenSSL 3.0 QUIET COMPONENTS Crypto) + if(NOT OPENSSL_FOUND) + set(_updater_tests OFF) + endif() +endif() +if(_updater_tests) + add_executable(updater_probe UpdaterProbe.cpp) + target_link_libraries(updater_probe PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options) + target_compile_features(updater_probe PRIVATE cxx_std_23) + add_executable(updater_tests Main.cpp UpdaterTests.cpp) + target_link_libraries(updater_tests PRIVATE WebFront::Bdd WebFront_test_hardening WebFront_warnings WebFront_options) + webfront_use_updater(updater_tests) + add_dependencies(updater_tests updater_probe) + target_compile_definitions(updater_tests PRIVATE UPDATER_PROBE="$") + webfront_bdd_discover_tests(updater_tests TEST_PREFIX "Updater." PROPERTIES TIMEOUT ${_unit_timeout} LABELS fast ${_unit_test_environment}) +elseif(WEBFRONT_REQUIRE_UPDATER_TESTS) + message(FATAL_ERROR "The updater tests need OpenSSL 3.0 or later (libssl-dev)") +else() + message(STATUS "Updater tests skipped: OpenSSL 3.0 or later was not found") +endif() + # The optional C++26 layer of the forms (ADR-018, #383): reflection needs GCC 16 with -std=c++26 -freflection. The library # stays C++23; only this test executable is compiled as C++26. CI requires it on Linux so that it cannot be skipped there. option(WEBFRONT_REQUIRE_REFLECTION_TESTS "Fail the configuration when the C++26 reflection tests cannot be compiled" OFF) @@ -428,6 +454,31 @@ add_test(NAME AddSubdirectoryConsumer -DENABLE_CACHE=OFF "-DCMAKE_CXX_COMPILER_LAUNCHER:STRING=$" -DCMAKE_BUILD_TYPE=$ -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}) set_tests_properties(AddSubdirectoryConsumer PROPERTIES TIMEOUT 600 LABELS portability) +# find_package(WebFront) from an installed copy of this build: a consumer builds Hello World with no network (#762). +add_test(NAME InstalledPackageConsumer + COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DBUILD=${CMAKE_BINARY_DIR} -DCONFIG=$ + -DWORK=${CMAKE_CURRENT_BINARY_DIR}/installed-package + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" "-DTEST_CXX_COMPILER=${CMAKE_CXX_COMPILER}" + -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckInstalledPackage.cmake) +set_tests_properties(InstalledPackageConsumer PROPERTIES TIMEOUT 900 LABELS portability) +# A non-default include directory, and a frontend requested by a second find_package. Configure and install only. +add_test(NAME InstalledPackageLayout + COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DWORK=${CMAKE_CURRENT_BINARY_DIR}/installed-layout + -DSTDNET_SOURCE=${stdnet_SOURCE_DIR} -DSTDEXEC_SOURCE=${stdexec_SOURCE_DIR} + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" "-DTEST_CXX_COMPILER=${CMAKE_CXX_COMPILER}" + -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckInstalledLayout.cmake) +set_tests_properties(InstalledPackageLayout PROPERTIES TIMEOUT 300 LABELS configuration) +# The vcpkg port and the Conan recipe pin the dependencies of the build. +add_test(NAME PackagePins + COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckPackagePins.cmake) +set_tests_properties(PackagePins PROPERTIES TIMEOUT 30 LABELS fast) +# webfront_package(): the installer's configuration of this platform, without building an application. +add_test(NAME ApplicationPackageConfiguration + COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DWORK=${CMAKE_CURRENT_BINARY_DIR}/application-package + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" "-DTEST_CXX_COMPILER=${CMAKE_CXX_COMPILER}" "-DDEPENDENCY_ARGS=${_consumer_dependency_args}" + -DCPM_MODULE=${CPM_DOWNLOAD_LOCATION} + -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckApplicationPackage.cmake) +set_tests_properties(ApplicationPackageConfiguration PROPERTIES TIMEOUT 300 LABELS configuration) # webfront_embed_directory() from a parent project (#675): the embedded directory is served like the disk, and the build # follows changed, added and removed files. add_test(NAME EmbedDirectoryConsumer diff --git a/test/unit/UpdaterProbe.cpp b/test/unit/UpdaterProbe.cpp new file mode 100644 index 00000000..2c04876f --- /dev/null +++ b/test/unit/UpdaterProbe.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/unit +// Role: A program the updater tests replace while it runs: it creates its first argument and waits for its second. +// Thread: worker-safe | Alloc: unrestricted +// LLM: test helper; ends by itself after a minute + +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) + return 2; + std::ofstream{argv[1]}.flush(); + for (int attempt = 0; attempt < 600 && !std::filesystem::exists(argv[2]); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + return 0; +} diff --git a/test/unit/UpdaterTests.cpp b/test/unit/UpdaterTests.cpp new file mode 100644 index 00000000..19fcfeae --- /dev/null +++ b/test/unit/UpdaterTests.cpp @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/unit +// Role: The verified updater: signatures, refused candidates, interrupted swaps and rollback. +// Thread: worker-safe | Alloc: heap-init +// LLM: the signatures were produced by `openssl dgst -sha256 -sign`; the private keys were discarded, so changing a signed content needs a new key + +#include "TemporaryDirectory.hpp" +#include +#include + +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront::update; + +namespace { + +constexpr std::string_view publicKey = R"(-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE3Q9+chWM/vkKQeQYy811WJMEENjv +U/zR6e3wCr0XVOT+J/DzddTDnrzNeP7eV/fDClc61258PfU0HZ11MtJBqA== +-----END PUBLIC KEY----- +)"; +constexpr std::string_view otherKey = R"(-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEs/3j32NC6Td9+Z9GdLMh9j4AwjCX +sDEp8LgSKg5v4a57yHSrfYlJG3fFuwhCRknlBiehrHGNXmbQRJpB7CrAZg== +-----END PUBLIC KEY----- +)"; +constexpr std::string_view rsaKey = R"(-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +-----END PUBLIC KEY----- +)"; +constexpr std::string_view oldContent = "old version 1\n"; +constexpr std::string_view newContent = "new version 2\n"; +constexpr std::array newSignature{0x30, 0x45, 0x02, 0x20, 0x63, 0x1d, 0xf3, 0xc8, 0xf0, 0x42, 0xc1, 0x7d, 0x37, 0x4e, 0x38, 0x84, 0xc0, 0xfb, + 0x19, 0x26, 0x87, 0x9a, 0xc3, 0xed, 0x35, 0x03, 0x9c, 0x9a, 0xd2, 0xc9, 0xc8, 0xf5, 0xab, 0xb4, 0x3b, 0xed, + 0x02, 0x21, 0x00, 0x96, 0x8e, 0x88, 0x4a, 0xad, 0xaf, 0xfe, 0xf8, 0x47, 0x0d, 0x1e, 0x88, 0x55, 0xd7, 0xbf, + 0xc5, 0xea, 0x87, 0x97, 0x9f, 0x6d, 0x6b, 0x07, 0xf5, 0x0d, 0x1d, 0xb9, 0x5e, 0x24, 0x0a, 0xdd, 0x38}; +constexpr std::array patternSignature{ + 0x30, 0x45, 0x02, 0x20, 0x72, 0xc9, 0x3c, 0x59, 0x85, 0x6d, 0xb1, 0x3d, 0x0e, 0x28, 0xb5, 0x3b, 0xe6, 0xfe, 0xce, 0x6e, 0xbf, 0x40, 0x39, 0xe2, + 0xf8, 0x89, 0x44, 0x26, 0x3a, 0x98, 0x47, 0x8d, 0xad, 0x27, 0xc2, 0x5a, 0x02, 0x21, 0x00, 0xf3, 0x9b, 0x2e, 0xb3, 0xa5, 0xd5, 0x17, 0x1f, 0xc1, + 0x26, 0x87, 0x67, 0xbd, 0x72, 0xbe, 0x66, 0x59, 0x9b, 0x70, 0x08, 0xda, 0x45, 0xed, 0xfe, 0xac, 0xba, 0x0b, 0x59, 0xb6, 0x9e, 0x2f, 0x17}; + +template +std::vector bytes(const std::array& values) { + std::vector result; + for (const auto value : values) + result.push_back(static_cast(value)); + return result; +} + +void write(const std::filesystem::path& file, std::string_view content) { + std::ofstream stream(file, std::ios::binary | std::ios::trunc); + stream << content; +} + +std::string read(const std::filesystem::path& file) { + std::ifstream stream(file, std::ios::binary); + return {std::istreambuf_iterator{stream}, std::istreambuf_iterator{}}; +} + +/// An installed "application" of version 1 and a downloaded candidate of version 2. +struct Installation { + webfront::test::TemporaryDirectory directory; + std::filesystem::path app{directory.path() / "app.exe"}; + std::filesystem::path download{directory.path() / "download.bin"}; + PublicKey key{PublicKey::fromPem(publicKey)}; + std::vector signature{bytes(newSignature)}; + Installation() { + write(app, oldContent); + write(download, newContent); + } + void apply(Updater::Checkpoint checkpoint = {}) { + Updater{app, std::move(checkpoint)}.apply(download, signature, key); + } + [[nodiscard]] std::size_t files() const { + return static_cast(std::distance(std::filesystem::directory_iterator{directory.path()}, std::filesystem::directory_iterator{})); + } +}; + +template +std::optional errorOf(F&& function) { + try { + function(); + } catch (const UpdateError& error) { + return error.code(); + } + return std::nullopt; +} + +struct PowerCut { }; + +const Scenario signatures{"The updater accepts only the signature of the file by the application's key", [] { + Installation installation; + given("a file signed with openssl", [&] { + require(verifySignature(installation.download, installation.signature, installation.key)); + }); + given("a signature of a file read in several blocks", [&] { + std::string pattern; + for (int i = 0; i < 1000; ++i) + for (int byte = 0; byte < 256; ++byte) + pattern.push_back(static_cast(byte)); + write(installation.download, pattern); + require(verifySignature(installation.download, bytes(patternSignature), installation.key)); + }); + given("another content, another key, a changed or truncated signature", [&] { + require(!verifySignature(installation.download, installation.signature, PublicKey::fromPem(otherKey))); + auto changed = installation.signature; + changed.back() ^= std::byte{1}; + require(!verifySignature(installation.download, changed, installation.key)); + changed = installation.signature; + changed.pop_back(); + require(!verifySignature(installation.download, changed, installation.key)); + changed = installation.signature; + changed.push_back(std::byte{0}); + require(!verifySignature(installation.download, changed, installation.key)); + require(!verifySignature(installation.download, {}, installation.key)); + write(installation.download, "new version 3\n"); + require(!verifySignature(installation.download, installation.signature, installation.key)); + }); + given("keys that are not ECDSA P-256 public keys", [&] { + require(errorOf([] { + (void)PublicKey::fromPem(rsaKey); + }) + == Errc::invalidKey); + require(errorOf([] { + (void)PublicKey::fromPem("not a key"); + }) + == Errc::invalidKey); + require(errorOf([] { + (void)PublicKey::fromPem("-----END PUBLIC KEY----- -----BEGIN PUBLIC KEY-----"); + }) + == Errc::invalidKey); + }); + }}; + +const Scenario refused{"A candidate with a wrong signature leaves the installation untouched", [] { + Installation installation; + write(installation.download, "tampered"); + require(errorOf([&] { + installation.apply(); + }) + == Errc::invalidSignature); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + require(!Updater{installation.app}.rollback()); + }}; + +const Scenario replaced{"An update keeps the former executable until it is confirmed", [] { + Installation installation; + installation.apply(); + Updater updater{installation.app}; + checkEqual(read(installation.app), std::string{newContent}); + checkEqual(read(updater.backupPath()), std::string{oldContent}); + require(errorOf([&] { + installation.apply(); + }) + == Errc::pending); + when("the new version confirms", [&] { + updater.confirm(); + require(!std::filesystem::exists(updater.backupPath())); + require(updater.recover() == Recovery::none); + checkEqual(read(installation.app), std::string{newContent}); + checkEqual(installation.files(), std::size_t{2}); + }); + }}; + +const Scenario rolledBack{"A rollback puts the former executable back", [] { + Installation installation; + installation.apply(); + Updater updater{installation.app}; + require(updater.rollback()); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + }}; + +const Scenario unconfirmed{"A new version that is never confirmed is rolled back after the allowed starts", [] { + Installation installation; + installation.apply(); + Updater updater{installation.app}; + require(updater.recover(2) == Recovery::pending); + require(updater.recover(2) == Recovery::pending); + checkEqual(read(installation.app), std::string{newContent}); + require(updater.recover(2) == Recovery::rolledBack); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + }}; + +const Scenario interrupted{"An update interrupted at any step is repaired by recover()", [] { + for (const auto step : {Step::staged, Step::verified, Step::prepared, Step::movedAside, Step::swapped}) { + Installation installation; + bool cut = false; + try { + installation.apply([&](Step reached) { + if (reached == step) + throw PowerCut{}; + }); + } catch (const PowerCut&) { + cut = true; + } +#if defined(_WIN32) + require(cut); +#else + if (step == Step::movedAside) continue; // the swap is a single rename + require(cut); +#endif + Updater updater{installation.app}; + const auto recovery = updater.recover(); + if (step == Step::swapped) { + require(recovery == Recovery::pending); + checkEqual(read(installation.app), std::string{newContent}); + require(updater.rollback()); + } else if (step == Step::movedAside) { + require(recovery == Recovery::restored); + } else if (step == Step::prepared) { + require(recovery == Recovery::abandoned); + } else { + require(recovery == Recovery::none); + } + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + // The installation updates normally afterwards. + installation.apply(); + checkEqual(read(installation.app), std::string{newContent}); + } + }}; + +const Scenario missing{"recover() restores an executable lost between two renames", [] { + Installation installation; + Updater updater{installation.app}; + std::filesystem::rename(installation.app, updater.backupPath()); + write(updater.stagedPath(), newContent); + write(updater.statePath(), "swapping"); + require(updater.recover() == Recovery::restored); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + }}; + +// The former executable is back (the rename of rollback() was done) but the state file survived the interruption. +const Scenario interruptedRollback{"recover() ends a rollback interrupted after the former executable is back", [] { + for (const std::string_view state : {"pending 0", "pending 3", "swapping"}) { + Installation installation; + installation.apply(); + Updater updater{installation.app}; + std::filesystem::rename(updater.backupPath(), installation.app); + write(updater.statePath(), state); + require(updater.recover() == Recovery::rolledBack); + require(updater.recover() == Recovery::none); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + installation.apply(); + checkEqual(read(installation.app), std::string{newContent}); + } + }}; + +#if !defined(_WIN32) +// A link to itself exists and cannot be opened, whatever the user's rights. +const Scenario unreadableState{"An unreadable state file keeps the former executable", [] { + Installation installation; + installation.apply(); + Updater updater{installation.app}; + std::filesystem::remove(updater.statePath()); + std::filesystem::create_symlink(updater.statePath().filename(), updater.statePath()); + require(errorOf([&] { + static_cast(updater.recover()); + }) + == Errc::io); + require(errorOf([&] { + installation.apply(); + }) + == Errc::io); + checkEqual(read(updater.backupPath()), std::string{oldContent}); + }}; +#endif + +const Scenario unwritable{"An update that cannot start reports an error and changes nothing", [] { + Installation installation; + require( + errorOf([&] { + Updater{installation.directory.path() / "absent"}.apply(installation.download, installation.signature, installation.key); + }) + == Errc::io); + require(errorOf([&] { + Updater{installation.app}.apply(installation.directory.path() / "absent", installation.signature, installation.key); + }) + == Errc::io); + checkEqual(read(installation.app), std::string{oldContent}); + checkEqual(installation.files(), std::size_t{2}); + }}; + +#if !defined(_WIN32) +const Scenario permissions{"The new executable keeps the permissions of the former one", [] { + Installation installation; + using enum std::filesystem::perms; + const auto mode = owner_all | group_read | group_exec; + std::filesystem::permissions(installation.app, mode); + installation.apply(); + require(std::filesystem::status(installation.app).permissions() == mode); + require(Updater{installation.app}.rollback()); + require(std::filesystem::status(installation.app).permissions() == mode); + }}; +#endif + +// The probe is a real program that runs until a file beside it appears: Windows forbids replacing a running image. +const Scenario running{"A running executable is replaced and rolled back", [] { + Installation installation; + const auto program = installation.directory.path() / std::filesystem::path{UPDATER_PROBE}.filename(); + std::filesystem::copy_file(UPDATER_PROBE, program); + const auto started = installation.directory.path() / "started"; + const auto stop = installation.directory.path() / "stop"; + std::jthread process{[&] { + auto command = "\"" + program.string() + "\" \"" + started.string() + "\" \"" + stop.string() + "\""; +#if defined(_WIN32) + command = "\"" + command + "\""; // cmd /c removes the outer pair +#endif + (void)std::system(command.c_str()); + }}; + struct Stop { + std::filesystem::path file; + ~Stop() { + write(file, ""); + } + } stopAtExit{stop}; + requireEventually( + [&] { + return std::filesystem::exists(started); + }, + std::chrono::seconds{30}); + + Updater updater{program}; + updater.apply(installation.download, installation.signature, installation.key); + checkEqual(read(program), std::string{newContent}); + require(updater.rollback()); + require(std::filesystem::file_size(program) == std::filesystem::file_size(UPDATER_PROBE)); + }}; + +} // namespace