diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c5d055aa1..3c3d604ff 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -194,8 +194,8 @@ open **Troubleshooting**, and select **Reset XDG Portal Capture**. Sunshine dele Approve the Remote Desktop prompt again and select the display to capture when it appears. > [!TIP] -> If Sunshine uses a custom configuration directory, you may need to delete the `portal_token` file from the custom -> directory and restart Sunshine manually in lieu of the Web UI. +> If Sunshine uses a custom configuration directory, you may need to delete the `portal_token` file (which may +> include a suffix such as .kde or .gnome) from the custom directory and restart Sunshine manually in lieu of the Web UI. Users of the KDE Plasma desktop can bypass manual permission setup either by switching to `kwin` capture or setting the following configuration to enable permanent capture authorization for Sunshine via Portal capture: diff --git a/src/confighttp.cpp b/src/confighttp.cpp index 4e6ba138e..1e2403ae5 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -126,11 +126,11 @@ namespace confighttp { auto &portal_token_path_provider() { #ifdef SUNSHINE_TESTS static portal_token_path_provider_t path_provider = []() { - return platf::appdata() / "portal_token"; + return platf::get_xdg_restore_token_path(); }; #else static const portal_token_path_provider_t path_provider = []() { - return platf::appdata() / "portal_token"; + return platf::get_xdg_restore_token_path(); }; #endif return path_provider; @@ -189,7 +189,7 @@ namespace confighttp { void reset_portal_token_path_provider_for_testing() { portal_token_path_provider() = []() { - return platf::appdata() / "portal_token"; + return platf::get_xdg_restore_token_path(); }; } diff --git a/src/platform/common.h b/src/platform/common.h index 365f9a6fa..52925cba8 100644 --- a/src/platform/common.h +++ b/src/platform/common.h @@ -884,6 +884,8 @@ namespace platf { std::filesystem::path appdata(); + std::filesystem::path get_xdg_restore_token_path(); ///< XDG restore token path. + /** * @brief Return the hardware MAC address associated with a network address. * diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 1c2eb4b0e..4d2430da4 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -369,6 +369,19 @@ namespace platf { return config_path; } + /** + * @brief Get path of the XDG Portal restore token. + * + * @return Path of token that may include the session desktop as a suffix (e.g. .gnome, .kde). + */ + std::filesystem::path get_xdg_restore_token_path() { +#ifdef SUNSHINE_BUILD_PORTAL + return portal::get_saved_token_path(); +#else + return appdata() / "portal_token"; +#endif + } + /** * @brief Convert a socket address to a printable IP address. */ diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index 25e575c56..5d88fbb04 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -64,6 +64,24 @@ namespace portal { */ void clear_saved_token(); + /** + * @brief Get path of the XDG Portal restore token. + * + * @return Path of token that may include the session desktop as a suffix (e.g. .gnome, .kde). + */ + std::filesystem::path get_saved_token_path(); + + #ifdef SUNSHINE_TESTS + /** + * @brief Resolve and migrate a saved token using isolated test inputs. + * + * @param directory Directory containing test tokens. + * @param desktop Session desktop used to select the token suffix. + * @return Path of the selected test token. + */ + std::filesystem::path get_saved_token_path_for_testing(const std::filesystem::path &directory, const std::string &desktop); + #endif + /** * @brief Check if the Portal service responds to a DBus Ping within 2 seconds. * diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index 773ff5454..b530ae6d4 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -2,6 +2,14 @@ * @file src/platform/linux/portalgrab.cpp * @brief Definitions for XDG portal grab. */ +// standard includes +#include +#include +#include + +// lib includes +#include + // local includes #include "pipewire.cpp" #include "src/globals.h" @@ -116,12 +124,57 @@ namespace portal { } } + /** + * @brief Get file path of the XDG Portal restore token. + * + * The token filename is suffixed with the XDG session desktop when set in the environment. + * + * @param directory Directory containing saved tokens; defaults to the application data directory. + * @param desktop Session desktop; defaults to the XDG_SESSION_DESKTOP environment variable. + * @return File path. + */ + static std::filesystem::path get_file_path( + const std::filesystem::path &directory = platf::appdata(), + const std::string &desktop = lizardbyte::common::get_env("XDG_SESSION_DESKTOP") + ) { + const std::filesystem::path legacy_path = directory / "portal_token"; + + std::string suffix(desktop); + boost::algorithm::to_lower(suffix); + + // Restrict the suffix to prevent path traversal and other invalid filename characters. + if (const bool is_safe = !suffix.empty() && std::all_of(suffix.begin(), suffix.end(), [](unsigned char c) { + return std::isalnum(c) || c == '_' || c == '-'; + }); + !is_safe) { + BOOST_LOG(warning) << "[portalgrab] XDG session desktop type cannot be determined. Using .unknown suffix for Portal restore token."sv; + suffix = "unknown"; + } + + const std::filesystem::path suffixed_path = directory / ("portal_token." + suffix); + + // One-time migration of legacy portal_token. + std::error_code ec; + if (!std::filesystem::exists(suffixed_path, ec) && !ec) { + const bool legacy_exists = std::filesystem::exists(legacy_path, ec); + + if (!ec && legacy_exists) { + // Attempt one-time adoption of a pre-upgrade token. Best-effort guess that it belongs + // to this session type; if wrong, we're no worse off than not migrating. + std::filesystem::rename(legacy_path, suffixed_path, ec); + if (ec) { + BOOST_LOG(error) << "[portalgrab] Portal restore token migration failed: "sv << ec.message(); + } else { + BOOST_LOG(info) << "[portalgrab] Portal restore token migrated to portal_token."sv << suffix; + } + } + } + + return suffixed_path; + } + private: static inline const std::unique_ptr token_ = std::make_unique(); - - static std::string get_file_path() { - return platf::appdata().string() + "/portal_token"; - } }; /** @@ -191,6 +244,21 @@ namespace portal { GDBusConnection *conn; ///< Borrowed — owned by the calling dbus_t/portal_t. }; + /** + * @brief Get path of the XDG Portal restore token. + * + * @return Path of token that may include the session desktop as a suffix (e.g. .gnome, .kde). + */ + std::filesystem::path get_saved_token_path() { + return restore_token_t::get_file_path(); + } + +#ifdef SUNSHINE_TESTS + std::filesystem::path get_saved_token_path_for_testing(const std::filesystem::path &directory, const std::string &desktop) { + return restore_token_t::get_file_path(directory, desktop); + } +#endif + /** * @brief PipeWire stream node and negotiated capture size. */ diff --git a/src/platform/macos/misc.mm b/src/platform/macos/misc.mm index 3d9d8e5a0..703ace5e2 100644 --- a/src/platform/macos/misc.mm +++ b/src/platform/macos/misc.mm @@ -355,6 +355,15 @@ namespace platf { return fs::path {homedir} / ".config/sunshine"sv; } + /** + * @brief XDG Portal token path (unused on MacOS). + * + * @return Path of portal_token in appdata path. + */ + std::filesystem::path get_xdg_restore_token_path() { + return appdata() / "portal_token"; + } + using ifaddr_t = util::safe_ptr; ifaddr_t get_ifaddrs() { diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index cbd6f3c0a..1d34174e8 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -165,6 +165,15 @@ namespace platf { return std::filesystem::path {sunshine_path}.remove_filename() / L"config"sv; } + /** + * @brief XDG Portal token path (unused on Windows). + * + * @return Path of portal_token in appdata path. + */ + std::filesystem::path get_xdg_restore_token_path() { + return appdata() / "portal_token"; + } + std::string from_sockaddr(const sockaddr *const socket_address) { char data[INET6_ADDRSTRLEN] = {}; diff --git a/tests/unit/platform/test_portal_token.cpp b/tests/unit/platform/test_portal_token.cpp new file mode 100644 index 000000000..36a06f856 --- /dev/null +++ b/tests/unit/platform/test_portal_token.cpp @@ -0,0 +1,192 @@ +/** + * @file tests/unit/platform/test_portal_token.cpp + * @brief Tests for session-specific XDG Portal token paths and legacy migration. + */ + +// test includes +#include "../../tests_common.h" + +#ifndef SUNSHINE_BUILD_PORTAL +TEST_F(BaseTest, XdgRestoreTokenPathUsesLegacyFilenameWithoutPortal) { + EXPECT_EQ(platf::get_xdg_restore_token_path(), platf::appdata() / "portal_token"); +} +#else + // standard includes + #include + #include + #include + #include + + // local includes + #include "src/platform/linux/misc.h" + +/** + * @brief Desktop input and expected normalized token suffix. + */ +struct portal_desktop_suffix_t { + const char *desktop; ///< Desktop identifier supplied to the resolver. + const char *suffix; ///< Expected safe filename suffix. +}; + +namespace { + /** + * @brief Provide a private token directory without changing process environment variables. + */ + class PortalTokenTest: public BaseTest { + protected: + /** + * @brief Create a unique writable directory for test tokens. + */ + void SetUp() override { + BaseTest::SetUp(); + if (HasFatalFailure() || IsSkipped()) { + return; + } + auto directory_template = (std::filesystem::temp_directory_path() / "sunshine-portal-token-XXXXXX").string(); // NOSONAR(cpp:S5443): mkdtemp creates a private unique directory. + const auto *directory = mkdtemp(directory_template.data()); + ASSERT_NE(directory, nullptr); + token_directory_ = directory; + } + + /** + * @brief Remove only the private directory created by this fixture. + */ + void TearDown() override { + if (!token_directory_.empty()) { + std::error_code ec; + std::filesystem::remove_all(token_directory_, ec); + EXPECT_FALSE(ec) << ec.message(); + } + BaseTest::TearDown(); + } + + /** + * @brief Resolve a token path through the production resolver. + * @param desktop Desktop identifier to normalize and validate. + * @return Selected path in the private token directory. + */ + std::filesystem::path resolve(const std::string &desktop = "KDE") const { + return portal::get_saved_token_path_for_testing(token_directory_, desktop); + } + + /** + * @brief Write a token in the private directory. + * @param name Token filename. + * @param value Token contents. + */ + void write_token(const std::string &name, const std::string &value) const { + std::ofstream file(token_directory_ / name); + ASSERT_TRUE(file.is_open()); + file << value; + ASSERT_TRUE(file.good()); + } + + /** + * @brief Read a token without changing its contents. + * @param name Token filename. + * @return First line of the saved token. + */ + std::string read_token(const std::string &name) const { + std::ifstream file(token_directory_ / name); + std::string value; + std::getline(file, value); + return value; + } + + /** + * @brief Get the private directory used by token assertions. + * + * @return Read-only path to this fixture's token directory. + */ + const std::filesystem::path &token_directory() const { + return token_directory_; + } + + private: + std::filesystem::path token_directory_; ///< Private directory owned by this fixture. + }; + + /** + * @brief Parameterized suffix normalization and validation tests. + */ + class PortalTokenSuffixTest: public PortalTokenTest, public testing::WithParamInterface {}; +} // namespace + +TEST_P(PortalTokenSuffixTest, SelectsSafeSessionFilename) { + const auto &value = GetParam(); + EXPECT_EQ(resolve(value.desktop), token_directory() / (std::string("portal_token.") + value.suffix)); +} + +INSTANTIATE_TEST_SUITE_P( + DesktopNames, + PortalTokenSuffixTest, + testing::Values( + portal_desktop_suffix_t {"KDE", "kde"}, + portal_desktop_suffix_t {"GNOME", "gnome"}, + portal_desktop_suffix_t {"Hyprland", "hyprland"}, + portal_desktop_suffix_t {"Desktop_1-test", "desktop_1-test"}, + portal_desktop_suffix_t {"", "unknown"}, + portal_desktop_suffix_t {"../kde", "unknown"}, + portal_desktop_suffix_t {"kde/gnome", "unknown"}, + portal_desktop_suffix_t {"kde\\gnome", "unknown"}, + portal_desktop_suffix_t {"kde:gnome", "unknown"}, + portal_desktop_suffix_t {"kde.name", "unknown"} + ) +); + +TEST_F(PortalTokenTest, MigratesLegacyTokenAndPreservesContents) { + ASSERT_NO_FATAL_FAILURE(write_token("portal_token", "legacy-token")); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_FALSE(std::filesystem::exists(token_directory() / "portal_token")); + EXPECT_EQ(read_token("portal_token.kde"), "legacy-token"); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_EQ(read_token("portal_token.kde"), "legacy-token"); +} + +TEST_F(PortalTokenTest, MigratesLegacyTokenToUnknownWhenDesktopIsEmpty) { + ASSERT_NO_FATAL_FAILURE(write_token("portal_token", "legacy-token")); + EXPECT_EQ(resolve(""), token_directory() / "portal_token.unknown"); + EXPECT_FALSE(std::filesystem::exists(token_directory() / "portal_token")); + EXPECT_EQ(read_token("portal_token.unknown"), "legacy-token"); +} + +TEST_F(PortalTokenTest, ExistingSessionTokenPreventsLegacyMigration) { + ASSERT_NO_FATAL_FAILURE(write_token("portal_token", "legacy-token")); + ASSERT_NO_FATAL_FAILURE(write_token("portal_token.kde", "current-token")); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_EQ(read_token("portal_token"), "legacy-token"); + EXPECT_EQ(read_token("portal_token.kde"), "current-token"); +} + +TEST_F(PortalTokenTest, MigrationPreservesOtherDesktopToken) { + ASSERT_NO_FATAL_FAILURE(write_token("portal_token", "legacy-token")); + ASSERT_NO_FATAL_FAILURE(write_token("portal_token.gnome", "gnome-token")); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_EQ(read_token("portal_token.kde"), "legacy-token"); + EXPECT_EQ(read_token("portal_token.gnome"), "gnome-token"); +} + +TEST_F(PortalTokenTest, SessionPathLookupErrorLeavesLegacyTokenUntouched) { + ASSERT_NO_FATAL_FAILURE(write_token("portal_token", "legacy-token")); + std::filesystem::create_symlink("portal_token.kde", token_directory() / "portal_token.kde"); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_TRUE(std::filesystem::is_symlink(token_directory() / "portal_token.kde")); + EXPECT_EQ(read_token("portal_token"), "legacy-token"); +} + +TEST_F(PortalTokenTest, LegacyPathLookupErrorDoesNotCreateSessionToken) { + std::filesystem::create_symlink("portal_token", token_directory() / "portal_token"); + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_TRUE(std::filesystem::is_symlink(token_directory() / "portal_token")); + EXPECT_FALSE(std::filesystem::exists(token_directory() / "portal_token.kde")); +} + +TEST_F(PortalTokenTest, FailedRenamePreservesLegacyEntryAndSessionPath) { + ASSERT_TRUE(std::filesystem::create_directory(token_directory() / "portal_token")); + std::filesystem::create_symlink("missing-token", token_directory() / "portal_token.kde"); + // POSIX cannot rename a directory over a symlink, even when its target is missing. + EXPECT_EQ(resolve(), token_directory() / "portal_token.kde"); + EXPECT_TRUE(std::filesystem::is_directory(token_directory() / "portal_token")); + EXPECT_TRUE(std::filesystem::is_symlink(token_directory() / "portal_token.kde")); +} +#endif diff --git a/tests/unit/test_confighttp.cpp b/tests/unit/test_confighttp.cpp index 944c2e004..3d6688184 100644 --- a/tests/unit/test_confighttp.cpp +++ b/tests/unit/test_confighttp.cpp @@ -34,6 +34,10 @@ #include #include +#ifdef SUNSHINE_BUILD_PORTAL + #include +#endif + using namespace std::literals; namespace { @@ -739,6 +743,53 @@ TEST_F(ConfigHttpTest, PortalTokenResetReportsDeletionFailure) { EXPECT_TRUE(std::filesystem::exists(token_path)); } +#ifdef SUNSHINE_BUILD_PORTAL +TEST_F(ConfigHttpTest, PortalTokenResetUsesSessionResolverAndPreservesOtherDesktops) { + const auto active_token = test_web_dir / "portal_token.kde"; + const auto other_token = test_web_dir / "portal_token.gnome"; + std::ofstream(active_token) << "kde-token"; + std::ofstream(other_token) << "gnome-token"; + confighttp::set_portal_token_path_provider_for_testing([this]() { + return portal::get_saved_token_path_for_testing(test_web_dir, "KDE"); + }); + + SimpleWeb::CaseInsensitiveMultimap headers; + headers.emplace("Authorization", create_auth_header("testuser", "testpass")); + headers.emplace("Origin", std::format("https://localhost:{}", port)); + const auto response = client->request("POST", "/portal-token-reset-test", "", headers); + + ASSERT_EQ(response->status_code, "200 OK"); + EXPECT_TRUE(nlohmann::json::parse(response->content.string()).at("status").get()); + EXPECT_FALSE(std::filesystem::exists(active_token)); + ASSERT_TRUE(std::filesystem::exists(other_token)); + std::ifstream remaining_token(other_token); + std::string value; + std::getline(remaining_token, value); + EXPECT_EQ(value, "gnome-token"); +} + +TEST_F(ConfigHttpTest, PortalTokenResetRemovesMigratedLegacyToken) { + const auto legacy_token = test_web_dir / "portal_token"; + const auto active_token = test_web_dir / "portal_token.kde"; + std::ofstream(legacy_token) << "legacy-token"; + confighttp::set_portal_token_path_provider_for_testing([this]() { + return portal::get_saved_token_path_for_testing(test_web_dir, "KDE"); + }); + + SimpleWeb::CaseInsensitiveMultimap headers; + headers.emplace("Authorization", create_auth_header("testuser", "testpass")); + headers.emplace("Origin", std::format("https://localhost:{}", port)); + const auto response = client->request("POST", "/portal-token-reset-test", "", headers); + + ASSERT_EQ(response->status_code, "200 OK"); + EXPECT_TRUE(nlohmann::json::parse(response->content.string()).at("status").get()); + EXPECT_FALSE(std::filesystem::exists(legacy_token)); + EXPECT_FALSE(std::filesystem::exists(active_token)); + EXPECT_EQ(portal::get_saved_token_path_for_testing(test_web_dir, "KDE"), active_token); + EXPECT_FALSE(std::filesystem::exists(active_token)); +} +#endif + // Test: confighttp::authenticate() rejects requests without auth header TEST_F(ConfigHttpTest, AuthenticateRejectsNoAuth) { const auto response = client->request("GET", "/auth-test");