From 150996039d76ad83f0481ae4c714b4dbdd189271 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:12:56 +0100 Subject: [PATCH 1/3] Harden download installation and destinations after review (#451) - Install a new WKWebView destination by hard link, then by an exclusive copy on filesystems without links; report a failed installation on stderr. - Never download into the home folder itself on WebKitGTK, and strip leading dots from suggested names. - Open the WKWebView file chooser only for the application's own origin. - Remove staging directories left by a crash after a week. - Release the copied handler and panel when a sheet fails to start. - Reserve the exact target chosen in a save panel against concurrent downloads. - Treat an unreadable path as unavailable when choosing a download name. --- docs/FRONTENDS.md | 4 +- include/webfront/ContentPolicy.hpp | 6 ++ include/webfront/frontend/Downloads.hpp | 59 +++++++++++-- include/webfront/frontend/WKWebView.hpp | 110 +++++++++++++++--------- include/webfront/frontend/WebKitGTK.hpp | 12 +-- 5 files changed, 138 insertions(+), 53 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index ab8a0859..07494e06 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -53,7 +53,7 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | Frontend | Chooser | Download | Test injection | | --- | --- | --- | --- | -| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder, the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder (`~/Downloads` when none is configured, never the home folder itself; leading dots are removed from names), the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | | CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | | WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | | WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | @@ -75,7 +75,7 @@ WebKit reduces a suggested name such as `../x.txt` to `_x.txt` before the fronte If all 10,000 candidate names are occupied, automatic destination selection fails and cancels the download. WKWebView writes each download in a private staging directory beside the destination. On success it installs the file; if a destination that was free appears during the download, it preserves that file and discards the download. Failed and -cancelled downloads remove their staging directory. Installing a new destination requires hard-link support on its filesystem. +cancelled downloads remove their staging directory. A new destination is installed with a hard link, or by a copy that still refuses an existing file on filesystems without links (exFAT, network shares); a failed installation is reported on `stderr`. Staging directories left by a crash are removed after a week. Two downloads cannot target the same chosen file at once. The file chooser opens only for the application's own origin. ### Tests diff --git a/include/webfront/ContentPolicy.hpp b/include/webfront/ContentPolicy.hpp index edf263c2..2ad1aecd 100644 --- a/include/webfront/ContentPolicy.hpp +++ b/include/webfront/ContentPolicy.hpp @@ -169,6 +169,12 @@ class BoundContentPolicy { return origin && (policy.allowAnyNavigation || *origin == applicationOrigin || contains(policy.navigationAllowedOrigins, *origin)); } + /// Whether `url` belongs to the application's own origin, whatever the navigation allow-list admits. + bool isApplicationOrigin(std::string_view url) const { + const auto origin = contentOrigin(url); + return origin && *origin == applicationOrigin; + } + // Popups always leave the embedded session. Only HTTP(S) is forwarded, never shell/file schemes. template void handlePopup(const std::string& url, bool userInitiated, Launcher&& launch) const { diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 5686f236..91696f12 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -1,7 +1,8 @@ #pragma once -#include #include +#include +#include #include #include #include @@ -22,6 +23,7 @@ namespace webfront::frontend::detail { class DownloadStaging { public: explicit DownloadStaging(const std::filesystem::path& parent) { + sweepStale(parent); #ifdef __APPLE__ auto pattern = (parent / ".webfront-download-XXXXXX").string(); std::vector buffer(pattern.begin(), pattern.end()); @@ -56,14 +58,50 @@ class DownloadStaging { std::filesystem::remove_all(directory, ignored); } [[nodiscard]] std::filesystem::path path() const { return directory / "download"; } + /** + * @brief Installs the staged file. A new target never replaces a file that appeared meanwhile. + * + * A hard link installs atomically; on a filesystem without links (exFAT, FAT, some network shares) the file is copied, + * which still refuses an existing target. A copy that failed midway is removed. + */ bool finish(const std::filesystem::path& target, bool replace) const { std::error_code error; - if (replace) + if (replace) { std::filesystem::rename(path(), target, error); - else - std::filesystem::create_hard_link(path(), target, error); + return !error; + } + std::filesystem::create_hard_link(path(), target, error); + if (!error) + return true; + error.clear(); + std::filesystem::copy_file(path(), target, std::filesystem::copy_options::none, error); + if (error && error != std::errc::file_exists) { + std::error_code ignored; + std::filesystem::remove(target, ignored); + } return !error; } + + /// Removes the staging directories that a crash left in `parent` more than a week ago. + static void sweepStale(const std::filesystem::path& parent) noexcept { + try { + constexpr std::string_view prefix = ".webfront-download-"; + const auto limit = std::filesystem::file_time_type::clock::now() - std::chrono::hours(24 * 7); + std::error_code error; + for (std::filesystem::directory_iterator it(parent, error), end; !error && it != end; it.increment(error)) { + const auto name = it->path().filename().string(); + if (!name.starts_with(prefix) || !it->is_directory(error)) + continue; + if (const auto written = std::filesystem::last_write_time(it->path(), error); !error && written < limit) { + std::error_code ignored; + std::filesystem::remove_all(it->path(), ignored); + } + error.clear(); + } + } catch (...) { + } + } + private: std::filesystem::path directory; }; @@ -79,12 +117,17 @@ class DownloadStaging { inline std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, std::string_view suggested, const std::function& taken = {}) { auto name = std::filesystem::path(std::string(suggested)).filename(); + // Leading dots would let a page create hidden files (".bash_login") when the folder is the home folder. + if (const auto text = name.string(); text.starts_with('.')) + name = text.substr(text.find_first_not_of('.') == std::string::npos ? text.size() : text.find_first_not_of('.')); if (name.empty() || name == "." || name == "..") name = "download"; auto result = folder / name; std::error_code error; const auto unavailable = [&](const std::filesystem::path& path) { - return std::filesystem::exists(path, error) || (taken && taken(path)); + error.clear(); + const bool exists = std::filesystem::exists(path, error); + return exists || error || (taken && taken(path)); // An unreadable path is not known to be free. }; for (int index = 1; unavailable(result); ++index) { if (index == 10'000) @@ -112,6 +155,12 @@ class DownloadReservations { return result; } + /// Reserves exactly `path` (a destination the user chose); false if another running download already holds it. + [[nodiscard]] bool reserveExact(const std::filesystem::path& path) { + std::scoped_lock lock{mutex}; + return reserved.insert(path).second; + } + void release(const std::filesystem::path& path) { std::scoped_lock lock{mutex}; reserved.erase(path); diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index ada3d979..39cbeaf9 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -573,8 +574,8 @@ struct Session { id result = nullptr; // NSArray*; nil cancels. bool deferred = false; guard([&] { - // Only the frames the policy admits may open a chooser. - if (!contentPolicy.allowsNavigation(effectiveFrameUrl(frame))) + // Only the application's own origin may open a chooser, not every origin that navigation admits. + if (!contentPolicy.isApplicationOrigin(effectiveFrameUrl(frame))) return; if (options.chooseFiles) { const auto files = options.chooseFiles(); @@ -594,15 +595,24 @@ struct Session { const auto directories = send(parameters, "allowsDirectories"); send(panel, "setCanChooseDirectories:", directories); send(panel, "setCanChooseFiles:", static_cast(!directories)); - auto handler = Block_copy(completion); - send(panel, "retain"); - void (^finished)(long) = ^(long response) { - handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK - send(panel, "release"); - Block_release(handler); - }; + auto handler = Block_copy(completion); + bool retained = false; + try { + send(panel, "retain"); + retained = true; + void (^finished)(long) = ^(long response) { + handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK + send(panel, "release"); + Block_release(handler); + }; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + } catch (...) { + if (retained) + send(panel, "release"); + Block_release(handler); // The panel never took the handler: `completion` answers below. + throw; + } deferred = true; - send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); }); if (!deferred) completion(result); @@ -637,36 +647,54 @@ struct Session { const auto panel = send(type("NSSavePanel"), "savePanel"); Object name(text(std::filesystem::path(suggested).filename().string())); send(panel, "setNameFieldStringValue:", name.get()); - auto handler = Block_copy(completion); - auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. - const id key = download; // By value: the panel answers after this lambda and its references are gone. - send(panel, "retain"); - void (^finished)(long) = ^(long response) { - id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK - if (chosen && !*token) - chosen = nullptr; // The session is gone: nobody could move the file afterwards. - try { - if (chosen) { - const std::filesystem::path target = utf8(send(chosen, "path")); - std::error_code code; - const bool replace = std::filesystem::exists(target, code); - if (code) - throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); - auto staging = std::make_unique(target.parent_path()); - const auto temporary = staging->path(); - Object path(text(temporary.string())); - chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); - (*token)->downloadDestinations[key] = {std::move(staging), target, false, replace}; + auto handler = Block_copy(completion); + bool retained = false; + auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. + const id key = download; // By value: the panel answers after this lambda and its references are gone. + try { + send(panel, "retain"); + retained = true; + void (^finished)(long) = ^(long response) { + id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK + if (chosen && !*token) + chosen = nullptr; // The session is gone: nobody could move the file afterwards. + try { + if (chosen) { + const std::filesystem::path target = utf8(send(chosen, "path")); + std::error_code code; + const bool replace = std::filesystem::exists(target, code); + if (code) + throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); + auto& reservations = (*token)->reservations; + if (!reservations.reserveExact(target)) + throw std::filesystem::filesystem_error("Another download is writing this target", target, + std::make_error_code(std::errc::file_exists)); + try { + auto staging = std::make_unique(target.parent_path()); + const auto temporary = staging->path(); + Object path(text(temporary.string())); + chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); + (*token)->downloadDestinations[key] = {std::move(staging), target, true, replace}; + } catch (...) { + reservations.release(target); + throw; + } + } + } catch (const std::filesystem::filesystem_error&) { + chosen = nullptr; // No staging, or the target is taken: answer WebKit once, without crossing the AppKit block. } - } catch (const std::filesystem::filesystem_error&) { - chosen = nullptr; // No temporary name is free: answer WebKit once, without crossing the AppKit block. - } - handler(chosen); - send(panel, "release"); - Block_release(handler); - }; + handler(chosen); + send(panel, "release"); + Block_release(handler); + }; + send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); + } catch (...) { + if (retained) + send(panel, "release"); + Block_release(handler); // The panel never took the handler: `completion` answers below. + throw; + } deferred = true; - send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); }); if (!deferred) completion(result); @@ -678,8 +706,10 @@ struct Session { return; const auto pending = std::move(found->second); downloadDestinations.erase(found); - if (completed) - completed = pending.staging->finish(pending.target, pending.replace); + if (completed && !pending.staging->finish(pending.target, pending.replace)) { + completed = false; + std::fprintf(stderr, "WebFront: the download could not be installed at %s\n", pending.target.string().c_str()); + } if (pending.reserved) reservations.release(pending.target); if (completed && options.downloadFinished) diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index bf0c80e4..bb3d50c0 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -425,15 +425,15 @@ struct Session : FailureState { std::filesystem::path destinationFolder() const { if (!downloadDirectory.empty()) return downloadDirectory; - if (const auto* folder = a.userDirectory(2); folder && *folder) - return folder; - if (const auto* home = std::getenv("HOME"); home && *home) { + const auto* home = std::getenv("HOME"); + if (const auto* folder = a.userDirectory(2); folder && *folder) { std::error_code error; - const auto folder = std::filesystem::path(home) / "Downloads"; - if (std::filesystem::is_directory(folder, error)) + // GLib reports the home folder itself when no download folder is configured: never write there. + if (!(home && *home && std::filesystem::equivalent(folder, home, error))) return folder; - return home; } + if (home && *home) + return std::filesystem::path(home) / "Downloads"; // Created on demand. return std::filesystem::temp_directory_path(); } std::filesystem::path reserveDestination(std::string_view suggested) { From 01244e8b3d5f254507c9a5be83bc1934575ba27b Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:27:59 +0100 Subject: [PATCH 2/3] Avoid shadowing the session's reservations in the save panel handler (#451) --- include/webfront/frontend/WKWebView.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 39cbeaf9..c3dba55b 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -665,8 +665,8 @@ struct Session { const bool replace = std::filesystem::exists(target, code); if (code) throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); - auto& reservations = (*token)->reservations; - if (!reservations.reserveExact(target)) + auto& sessionReservations = (*token)->reservations; + if (!sessionReservations.reserveExact(target)) throw std::filesystem::filesystem_error("Another download is writing this target", target, std::make_error_code(std::errc::file_exists)); try { @@ -676,7 +676,7 @@ struct Session { chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); (*token)->downloadDestinations[key] = {std::move(staging), target, true, replace}; } catch (...) { - reservations.release(target); + sessionReservations.release(target); throw; } } From 741ea83be527a2dfee21e8d887dfe3e606682cca Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:49:56 +0100 Subject: [PATCH 3/3] Keep sweeping after an unreadable staging entry, resolve the home folder without HOME, align the chooser table (#451) --- docs/FRONTENDS.md | 2 +- include/webfront/frontend/Downloads.hpp | 7 ++++++- include/webfront/frontend/WebKitGTK.hpp | 3 +++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 07494e06..393195a1 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -55,7 +55,7 @@ admitted origin passes the navigation policy (`webfront::detail::blobOriginUrl`) | --- | --- | --- | --- | | WebKitGTK | default `run-file-chooser` dialog (portal under Flatpak) | `download-started` / `decide-destination`: the user's XDG download folder (`~/Downloads` when none is configured, never the home folder itself; leading dots are removed from names), the page's name reduced to its last component, never overwriting (`name (1).ext`), also between downloads that run at the same time (`DownloadReservations`) | `Session::chooseFiles`, `downloadDirectory`, `downloadFinished` | | CEF (Chrome runtime) | the runtime's dialog | the runtime's download handling | `SimpleCEFClient::chooseFiles` (`CefDialogHandler::OnFileDialog`), `downloadDirectory`, `downloadFinished`. The runtime itself turns a suggested name `../x` into `_x` | -| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames admitted by the policy | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | +| WKWebView | `runOpenPanelWithParameters` shows an `NSOpenPanel` sheet of the window; only frames of the application's own origin | `WKDownload` (macOS 11.3+): a save panel proposes the name | `WKWebViewOptions::chooseFiles`, `downloadDirectory`, `downloadFinished` | | WebView2 | the engine's native chooser | the engine's native download UI | DevTools intercepts the chooser in tests; `DownloadStarting` redirects the download to a private path | The engines require a user gesture to open a chooser, so the native scenarios click with a real pointer event (XTest under diff --git a/include/webfront/frontend/Downloads.hpp b/include/webfront/frontend/Downloads.hpp index 91696f12..ca306d5d 100644 --- a/include/webfront/frontend/Downloads.hpp +++ b/include/webfront/frontend/Downloads.hpp @@ -90,8 +90,13 @@ class DownloadStaging { std::error_code error; for (std::filesystem::directory_iterator it(parent, error), end; !error && it != end; it.increment(error)) { const auto name = it->path().filename().string(); - if (!name.starts_with(prefix) || !it->is_directory(error)) + if (!name.starts_with(prefix)) continue; + const bool directory = it->is_directory(error); + if (error || !directory) { + error.clear(); // An unreadable entry must not stop the sweep of the next ones. + continue; + } if (const auto written = std::filesystem::last_write_time(it->path(), error); !error && written < limit) { std::error_code ignored; std::filesystem::remove_all(it->path(), ignored); diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index bb3d50c0..92a867c0 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -116,6 +116,7 @@ class Api { void (*bytesUnref)(Object) = symbol("g_bytes_unref"); void (*errorFree)(Error*) = symbol("g_error_free"); // GLib resolves the folder from user-dirs.dirs (a user may have moved it), not only from the environment. + const char* (*homeDirectory)() = symbol("g_get_home_dir"); const char* (*userDirectory)(int) = symbol("g_get_user_special_dir"); // G_USER_DIRECTORY_DOWNLOAD = 2 void (*downloadDestination)(Object, const char*) = symbol("webkit_download_set_destination"); void (*downloadCancel)(Object) = symbol("webkit_download_cancel"); @@ -426,6 +427,8 @@ struct Session : FailureState { if (!downloadDirectory.empty()) return downloadDirectory; const auto* home = std::getenv("HOME"); + if (!home || !*home) + home = a.homeDirectory(); // GLib reads the passwd database when HOME is unset. if (const auto* folder = a.userDirectory(2); folder && *folder) { std::error_code error; // GLib reports the home folder itself when no download folder is configured: never write there.