From c8ea783cdaadd6fbe14ecd91fd11412b23982575 Mon Sep 17 00:00:00 2001 From: Dave Lane <42013603+ReenigneArcher@users.noreply.github.com> Date: Thu, 5 Nov 2026 08:31:49 -0500 Subject: [PATCH] fix(windows): open browser URLs through the Windows shell (#6047) --- src/platform/windows/misc.cpp | 22 +- src/platform/windows/misc.h | 9 + tests/tests_main.cpp | 65 +++++- .../platform/windows/test_url_launcher.cpp | 204 ++++++++++++++++++ 4 files changed, 294 insertions(+), 6 deletions(-) create mode 100644 tests/unit/platform/windows/test_url_launcher.cpp diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 955627582..c7e6ba129 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -1111,20 +1112,33 @@ namespace platf { return create_boost_child_from_results(ret, cmd, ec, process_info); } + std::wstring make_url_launch_command(const std::wstring &command_processor, const std::wstring &url) { + return std::format(LR"({} /d /v:off /c start "" {})", escape_argument(command_processor), escape_argument_for_cmd(escape_argument(url))); + } + /** - * @brief Open a url in the default web browser. - * @param url The url to open. + * @brief Open a URL through the Windows shell in the user's session. + * @details The command processor's start command preserves shell activation for packaged browsers. */ void open_url(const std::string &url) { + std::array system_directory; + const auto length = GetSystemDirectoryW(system_directory.data(), system_directory.size()); + if (!length || length >= system_directory.size()) { + BOOST_LOG(warning) << "Couldn't locate Windows command processor to open url ["sv << url << ']'; + return; + } + // Use the system command processor and disable AutoRun and delayed environment expansion. + // start performs shell activation in the user's process context, including MSIX activation. + const auto command = utf_utils::to_utf8(make_url_launch_command(std::wstring {system_directory.data(), length} + L"\\cmd.exe", utf_utils::from_utf8(url))); boost::process::v1::environment _env = boost::this_process::environment(); auto working_dir = boost::filesystem::path(); std::error_code ec; - auto child = run_command(false, false, url, working_dir, _env, nullptr, ec, nullptr); + auto child = run_command(false, false, command, working_dir, _env, nullptr, ec, nullptr); if (ec) { BOOST_LOG(warning) << "Couldn't open url ["sv << url << "]: System: "sv << ec.message(); } else { - BOOST_LOG(info) << "Opened url ["sv << url << "]"sv; + BOOST_LOG(info) << "Opening url ["sv << url << "]"sv; child.detach(); } } diff --git a/src/platform/windows/misc.h b/src/platform/windows/misc.h index ac866f281..30398d4e8 100644 --- a/src/platform/windows/misc.h +++ b/src/platform/windows/misc.h @@ -29,6 +29,15 @@ namespace platf { */ HDESK syncThreadDesktop(); + /** + * @brief Build a command that delegates URL activation to the Windows shell. + * + * @param command_processor Absolute path to the system command processor. + * @param url URL to pass unchanged to the shell's default protocol handler. + * @return Command line suitable for CreateProcessW(). + */ + std::wstring make_url_launch_command(const std::wstring &command_processor, const std::wstring &url); + /** * @brief Read the current Windows high-resolution performance counter. * diff --git a/tests/tests_main.cpp b/tests/tests_main.cpp index 1cf17c09e..df72f098f 100644 --- a/tests/tests_main.cpp +++ b/tests/tests_main.cpp @@ -8,9 +8,70 @@ #include "tests_environment.h" #include "tests_events.h" +// standard includes +#include + +#ifdef _WIN32 + // standard includes + #include + #include + #include + #include + + // platform includes + // Windows types must precede shellapi.h. + // clang-format off + #include + #include + // clang-format on + + // local includes + #include + #include + +/** + * @brief Record a URL delivered to a temporary test protocol handler without opening a browser. + * + * @return Recorder exit code, or no value for normal test invocations. + */ +std::optional record_test_url() { + int count = 0; + auto arguments = CommandLineToArgvW(GetCommandLineW(), &count); + if (!arguments) { + return ERROR_NOT_ENOUGH_MEMORY; + } + auto free_arguments = util::fail_guard([arguments]() { + LocalFree(arguments); + }); + if (count < 2 || std::wcscmp(arguments[1], L"--record-url") != 0) { + return std::nullopt; + } + if (count != 4) { + return ERROR_INVALID_PARAMETER; + } + std::ofstream output(std::filesystem::path {arguments[2]}, std::ios::binary); + output << utf_utils::to_utf8(arguments[3]); + return output.good() ? ERROR_SUCCESS : ERROR_WRITE_FAULT; +} +#endif + +/** + * @brief Run Sunshine tests, or record a URL delivered to a test protocol handler. + * + * @param argc Number of process arguments. + * @param argv Process arguments forwarded to GoogleTest. + * @return Test result or URL recorder exit code. + */ int main(int argc, char **argv) { +#ifdef _WIN32 + if (auto result = record_test_url(); result.has_value()) { + return *result; + } +#endif + testing::InitGoogleTest(&argc, argv); - testing::AddGlobalTestEnvironment(new SunshineEnvironment); - testing::UnitTest::GetInstance()->listeners().Append(new SunshineEventListener); + // GoogleTest takes ownership of the environment and listener after registration. + testing::AddGlobalTestEnvironment(std::make_unique().release()); + testing::UnitTest::GetInstance()->listeners().Append(std::make_unique().release()); return RUN_ALL_TESTS(); } diff --git a/tests/unit/platform/windows/test_url_launcher.cpp b/tests/unit/platform/windows/test_url_launcher.cpp new file mode 100644 index 000000000..19006b1db --- /dev/null +++ b/tests/unit/platform/windows/test_url_launcher.cpp @@ -0,0 +1,204 @@ +/** + * @file tests/unit/platform/windows/test_url_launcher.cpp + * @brief Exercise Windows URL opening through a temporary per-user protocol handler. + */ + +// test includes +#include "../../../tests_common.h" +#include "../../../tests_log_checker.h" + +#ifdef _WIN32 + // standard includes + #include + #include + #include + #include + #include + #include + #include + #include + #include + + // platform includes + #include + + // local includes + #include + #include + #include + +/** + * @brief Register an isolated URL handler that records requests instead of opening the user's browser. + */ +class WindowsOpenUrlTest: public BaseTest { +protected: + /** + * @brief Mark tests that temporarily register a per-user protocol. + * + * @return True because these tests briefly create an isolated registry entry. + */ + bool isSystemTest() const override { + return true; + } + + /** + * @brief Register a unique protocol whose handler is the test executable's URL recorder. + */ + void SetUp() override { + BaseTest::SetUp(); + if (IsSkipped()) { + return; + } + scheme = std::format(L"sunshine-url-test-{}-{}", GetCurrentProcessId(), sequence++); + registry_path = std::format(LR"(Software\Classes\{})", scheme); + output_path = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / (scheme + L".txt"); + + HKEY protocol; + DWORD disposition; + ASSERT_EQ(RegCreateKeyExW(HKEY_CURRENT_USER, registry_path.c_str(), 0, nullptr, 0, KEY_WRITE, nullptr, &protocol, &disposition), ERROR_SUCCESS); + auto close_protocol = util::fail_guard([protocol]() { + RegCloseKey(protocol); + }); + if (disposition != REG_CREATED_NEW_KEY) { + GTEST_SKIP() << "Test protocol already exists"; + } + owns_protocol = true; + ASSERT_EQ(RegSetValueExW(protocol, L"URL Protocol", 0, REG_SZ, reinterpret_cast(L""), sizeof(wchar_t)), ERROR_SUCCESS); + + std::array executable; + const auto length = GetModuleFileNameW(nullptr, executable.data(), executable.size()); + ASSERT_GT(length, 0U); + ASSERT_LT(length, executable.size()); + const auto command = std::format(LR"("{}" --record-url "{}" "%1")", std::wstring {executable.data(), length}, output_path.wstring()); + HKEY command_key; + ASSERT_EQ(RegCreateKeyExW(protocol, LR"(shell\open\command)", 0, nullptr, 0, KEY_WRITE, nullptr, &command_key, nullptr), ERROR_SUCCESS); + auto close_command = util::fail_guard([command_key]() { + RegCloseKey(command_key); + }); + ASSERT_EQ(RegSetValueExW(command_key, nullptr, 0, REG_SZ, reinterpret_cast(command.c_str()), static_cast((command.size() + 1) * sizeof(wchar_t))), ERROR_SUCCESS); + } + + /** + * @brief Remove only this fixture's temporary protocol and recorded URL. + */ + void TearDown() override { + if (owns_protocol) { + EXPECT_EQ(RegDeleteTreeW(HKEY_CURRENT_USER, registry_path.c_str()), ERROR_SUCCESS); + std::error_code remove_error; + std::filesystem::remove(output_path, remove_error); + EXPECT_FALSE(remove_error); + } + BaseTest::TearDown(); + } + + /** + * @brief Wait for asynchronous shell dispatch and verify the recorder receives the exact URL. + * + * @param suffix URL text following the temporary protocol name. + */ + void expect_url_delivered(const std::wstring &suffix) { + const auto url = utf_utils::to_utf8(scheme + suffix); + std::array system_directory; + const auto length = GetSystemDirectoryW(system_directory.data(), system_directory.size()); + ASSERT_GT(length, 0U); + ASSERT_LT(length, system_directory.size()); + const auto command_processor = std::filesystem::path {system_directory.data()} / L"cmd.exe"; + auto command = platf::make_url_launch_command(command_processor.wstring(), utf_utils::from_utf8(url)); + + // CI runners prohibit the breakaway flag used by run_command(). Exercise the production URL + // command inside the runner's job instead of changing Sunshine's process-lifetime behavior. + STARTUPINFOW startup_info {}; + startup_info.cb = sizeof(startup_info); + PROCESS_INFORMATION process_info {}; + ASSERT_TRUE(CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &startup_info, &process_info)) << GetLastError(); + auto close_process = util::fail_guard([&process_info]() { + CloseHandle(process_info.hThread); + CloseHandle(process_info.hProcess); + }); + ASSERT_EQ(WaitForSingleObject(process_info.hProcess, 10000), WAIT_OBJECT_0); + DWORD exit_code; + ASSERT_TRUE(GetExitCodeProcess(process_info.hProcess, &exit_code)); + ASSERT_EQ(exit_code, 0U); + + expect_url_recorded(url); + } + + /** + * @brief Wait until the registered handler records the exact URL delivered by the shell. + * + * @param url Expected UTF-8 URL. + */ + void expect_url_recorded(const std::string &url) { + std::string received; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds {10}; + do { + std::ifstream input(output_path, std::ios::binary); + received.assign(std::istreambuf_iterator {input}, std::istreambuf_iterator {}); + if (received == url) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds {20}); + } while (std::chrono::steady_clock::now() < deadline); + EXPECT_EQ(received, url); + } + + /** + * @brief Exercise the public launcher and distinguish accepted requests from runner access denial. + */ + void expect_launch_request_reported() { + const auto url = utf_utils::to_utf8(scheme + L"://localhost/launch-request"); + platf::open_url(url); + const auto accepted = log_checker::line_contains("test_sunshine.log", std::format("Opening url [{}]", url)); + const auto failed = log_checker::line_contains("test_sunshine.log", std::format("Couldn't open url [{}]", url)); + ASSERT_NE(accepted, failed); + if (accepted) { + expect_url_recorded(url); + } else { + // The runner can reject CREATE_BREAKAWAY_FROM_JOB with ERROR_ACCESS_DENIED. + EXPECT_TRUE(log_checker::line_contains("test_sunshine.log", "Failed to launch process: 5")); + } + } + +private: + inline static std::atomic_uint64_t sequence = 0; ///< Distinguishes protocols created by this test process. + std::wstring scheme; ///< Unique URL scheme owned by the fixture. + std::wstring registry_path; ///< Per-user protocol registration to remove during cleanup. + std::filesystem::path output_path; ///< UTF-8 URL written by the native protocol handler. + bool owns_protocol = false; ///< Whether setup created the protocol rather than finding an existing key. +}; + +/** + * @brief Preserve Unicode URLs, query separators, percent escapes, and pairing fragments. + */ +TEST_F(WindowsOpenUrlTest, PreservesUnicodeQueriesAndFragments) { + expect_url_delivered(L"://localhost/pin?name=\u{65e5}\u{672c}\u{8a9e}&text=hello%20world&value=100%25#pair"); +} + +/** + * @brief Preserve spaces and shell metacharacters through the command processor's start command. + */ +TEST_F(WindowsOpenUrlTest, PreservesSpacesAndShellMetacharacters) { + expect_url_delivered(L"://localhost/path with spaces?value=(one)^|&literal=!text!#fragment"); +} + +/** + * @brief Keep environment-like URL text from expanding in the command processor. + */ +TEST_F(WindowsOpenUrlTest, PreservesPercentAndExclamationDelimitedText) { + const auto name = std::format(L"SUNSHINE_URL_TEST_{}", GetCurrentProcessId()); + ASSERT_EQ(GetEnvironmentVariableW(name.c_str(), nullptr, 0), 0U); + ASSERT_EQ(GetLastError(), ERROR_ENVVAR_NOT_FOUND); + ASSERT_TRUE(SetEnvironmentVariableW(name.c_str(), L"unexpected-expansion")); + auto clear_environment = util::fail_guard([&name]() { + SetEnvironmentVariableW(name.c_str(), nullptr); + }); + expect_url_delivered(std::format(L"://localhost/?percent=%{}%&exclamation=!{}!", name, name)); +} + +/** + * @brief Verify that the public launcher reports accepted requests or runner access denial accurately. + */ +TEST_F(WindowsOpenUrlTest, ReportsTheActualLaunchRequestOutcome) { + expect_launch_request_reported(); +} +#endif