diff --git a/doc/about/update_notifications/index.md b/doc/about/update_notifications/index.md index ecce3e2c..27afabc1 100644 --- a/doc/about/update_notifications/index.md +++ b/doc/about/update_notifications/index.md @@ -38,6 +38,15 @@ automatically determined). We inform the developer about new Sharg versions, if the app is running in debug mode. Additionally, we recommend registering your app with us (support@seqan.de). +## Where the files are stored + +The timestamp, the user's choice, and the server's response are stored in `~/.config/seqan`, i.e., in the directory +given by the environment variable `HOME` (`UserProfile` on Windows). +If this environment variable is not set or empty, `.config/seqan` is created in the current working directory instead. +If `.config/seqan` cannot be created, the temporary directory (e.g., `TMPDIR`) is used. +If the chosen directory is not writable, no version check is performed. If the terminal is interactive, a message +informs about this. + ## Privacy Implications **No data is transmitted unless the user _explicitly_ allows it.** diff --git a/include/sharg/detail/version_check.hpp b/include/sharg/detail/version_check.hpp index c2c1a509..86495329 100644 --- a/include/sharg/detail/version_check.hpp +++ b/include/sharg/detail/version_check.hpp @@ -11,6 +11,8 @@ #include #include +#include +#include #include #include #include @@ -18,7 +20,6 @@ #include #include -#include #include namespace sharg::detail @@ -44,6 +45,43 @@ inline void call_server(std::string const & command, std::promise prom) prom.set_value(true); } +// ------------------------------------------------------------------------------------------------------------------ +// function quote_argument() +// ------------------------------------------------------------------------------------------------------------------ + +/*!\brief Quotes a string such that the shell executing the server call treats it as a single, literal argument. + * \ingroup parser + * \param[in] argument The string to quote. + * \returns The single-quoted string. + * + * Within single quotes, only the single quote itself needs to be escaped. + */ +inline std::string quote_argument(std::string const & argument) +{ +#if defined(_WIN32) + // The argument is part of a PowerShell command, which escapes a single quote by doubling it. + // Windows is not supported. If it ever is, this needs to be adapted: PowerShell also treats the typographic quotes + // U+2018 to U+201B as single quotes, and cmd.exe, which runs the command, expands %VARIABLE% even within quotes. + constexpr std::string_view escaped_quote{"''"}; +#else + // A POSIX shell cannot escape a single quote within single quotes: close the quotes, add an escaped quote, reopen. + constexpr std::string_view escaped_quote{"'\\''"}; +#endif + + std::string result{'\''}; + + for (char const c : argument) + { + if (c == '\'') + result.append(escaped_quote); + else + result.push_back(c); + } + + result.push_back('\''); + return result; +} + // ------------------------------------------------------------------------------------------------------------------ // version_checker // ------------------------------------------------------------------------------------------------------------------ @@ -182,12 +220,12 @@ class version_checker return; } - // 'cookie_path' is no user input and `name` is escaped on construction of the parser. + // 'cookie_path' is derived from environment variables and may contain any character, e.g. spaces. std::filesystem::path out_file = cookie_path / (name + ".version"); // build up command for server call std::string command = program + // no user defined input - " " + out_file.string() + " " + " " + quote_argument(out_file.string()) + " " + std::string{"https://seqan-update.cs.uni-tuebingen.de/check/SeqAn-Sharg_"} + #ifdef __linux "Linux" + @@ -219,7 +257,12 @@ class version_checker std::thread(call_server, command, std::move(prom)).detach(); } - //!\brief Returns a writable path to store timestamp and version files or an empty path if none exists. + /*!\brief Returns a writable path to store timestamp and version files or an empty path if none exists. + * \details + * The path is `.config/seqan` in the home directory given by the environment variable `HOME` (`UserProfile` on + * Windows). If this variable is not set or empty, `.config/seqan` is relative to the current working directory. + * If `.config/seqan` cannot be created, the temporary directory is used, see std::filesystem::temp_directory_path. + */ static std::filesystem::path get_path() { using namespace std::filesystem; @@ -243,17 +286,30 @@ class version_checker // .config/seqan cannot be created, try tmp directory. if (err) - tmp_path = temp_directory_path(); // choose temp dir instead + { + tmp_path = temp_directory_path(err); // choose temp dir instead + + if (err) // e.g., TMPDIR is not a directory + { + tmp_path.clear(); // empty path signals no available directory to write to + return tmp_path; + } + } - // check if files can be written inside dir - path dummy = tmp_path / "dummy.txt"; - std::ofstream file{dummy}; - sharg::detail::safe_filesystem_entry file_guard{dummy}; + // Check if files can be written inside dir. An existing file, e.g., in the temporary directory, might belong to + // someone else and must not be opened. Hence, the probe file gets a unique name and std::ios::noreplace fails + // instead of opening an existing file. In the unlikely case of a name clash, the directory is not used. + path const dummy = + tmp_path + / ("dummy_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".txt"); + std::ofstream file{dummy, std::ios::out | std::ios::noreplace}; bool is_open = file.is_open(); bool is_good = file.good(); file.close(); - file_guard.remove_no_throw(); + + if (is_open) // only remove the file if it was created here + remove(dummy, err); if (!is_good || !is_open) // no write permissions { @@ -263,6 +319,21 @@ class version_checker return tmp_path; } + /*!\brief Whether the developer, the environment variable SHARG_NO_VERSION_CHECK or the user disabled the check. + * \param[in] developer_approval Whether the developer approved (update_notifications::on) or not + * (update_notifications::off). + * \param[in] user_approval Whether the user approved (true) or not (false) or did not decide (unset optional). + * + * In contrast to decide_if_check_is_performed(), this does not need the directory for the timestamp and version + * files. Hence, the parser can call it before constructing the version_checker, which determines and creates this + * directory. + */ + static bool is_disabled(update_notifications developer_approval, std::optional user_approval) + { + return developer_approval == update_notifications::off || std::getenv("SHARG_NO_VERSION_CHECK") != nullptr + || user_approval == false; + } + /*!\brief The central decision whether to perform the version check or not. * \param[in] developer_approval Whether the developer approved (update_notifications::on) or not * (update_notifications::off). @@ -277,7 +348,9 @@ class version_checker * No cookie is written. * * If the user explicitly uses the --version-check option (user_approval is set) it rules out all following - * decisions. No cookie is written. + * decisions. No cookie is written. However, if there is no writable directory (see get_path()), no version check + * is done even if the user specified --version-check true. If the terminal is interactive, + * message_no_writable_directory is printed instead. * * If none of the above apply, version check was not explicitly handled so cookie content is checked: * * NEVER: Do not perform the version check and do not change the cookie. @@ -290,14 +363,20 @@ class version_checker */ bool decide_if_check_is_performed(update_notifications developer_approval, std::optional user_approval) { - if (developer_approval == update_notifications::off) + if (is_disabled(developer_approval, user_approval)) return false; - if (std::getenv("SHARG_NO_VERSION_CHECK") != nullptr) // environment variable was set + if (cookie_path.empty()) // no directory to write the timestamp and version files to + { + // Like the question whether to perform the version check, the message is only shown interactively. + if (detail::stdin_is_terminal() && detail::stderr_is_terminal()) // LCOV_EXCL_START + std::cerr << message_no_writable_directory << std::flush; + // LCOV_EXCL_STOP return false; + } - if (user_approval.has_value()) - return user_approval.value(); + if (user_approval.has_value()) // the user explicitly enabled the version check + return true; // version check was not explicitly handled so let's check the cookie if (std::filesystem::exists(cookie_path)) @@ -408,6 +487,12 @@ class version_checker "[APP VERSION INFO] :: We noticed the app version you use is newer than the one registered with us.\n" "[APP VERSION INFO] :: Please send us an email with the new version so we can correct it " "(support@seqan.de)\n\n"; + //!\brief The message if the version check is skipped because there is no writable directory for its files. + static constexpr std::string_view message_no_writable_directory = + "[SHARG VERSION INFO] :: The version check was skipped because there is no writable directory for its files.\n" + "[SHARG VERSION INFO] :: For details, see " + "https://docs.seqan.de/sharg/main_user/about_update_notifications.html\n" + "[SHARG VERSION INFO] :: If you don't wish to receive further notifications, set --version-check false.\n\n"; //!\brief The message directed to the user of the app if a new app version is available. std::string message_app_update = "[APP VERSION INFO] :: A new version of this application is now available.\n" diff --git a/include/sharg/parser.hpp b/include/sharg/parser.hpp index 84ea157f..ee697651 100644 --- a/include/sharg/parser.hpp +++ b/include/sharg/parser.hpp @@ -1120,6 +1120,10 @@ class parser */ inline void run_version_check() { + // Constructing the version_checker determines and creates the directory for its files. + if (detail::version_checker::is_disabled(version_check_dev_decision, version_check_user_decision)) + return; + detail::version_checker app_version{info.app_name, info.version, info.url}; if (app_version.decide_if_check_is_performed(version_check_dev_decision, version_check_user_decision)) diff --git a/test/unit/detail/version_check_test.hpp b/test/unit/detail/version_check_test.hpp index 72c4ce9d..1b6ab27d 100644 --- a/test/unit/detail/version_check_test.hpp +++ b/test/unit/detail/version_check_test.hpp @@ -52,12 +52,31 @@ class version_check_test : public sharg::test::test_fixture return false; } + // Some tests change TMPDIR or the current working directory, which are restored after each test case. + std::optional cached_tmpdir{}; + std::filesystem::path const cached_working_directory{std::filesystem::current_path()}; + void SetUp() override { + if (char const * tmpdir = std::getenv("TMPDIR")) + cached_tmpdir = tmpdir; + // set HOME environment to a random home folder before starting each test case randomise_home_folder(); } + void TearDown() override + { + if (cached_tmpdir.has_value()) + setenv("TMPDIR", cached_tmpdir->c_str(), 1); + else + unsetenv("TMPDIR"); + + std::error_code error{}; + std::filesystem::current_path(cached_working_directory, error); + EXPECT_FALSE(error) << error.message(); + } + static std::filesystem::path app_tmp_path() { return sharg::detail::version_checker::get_path(); @@ -538,3 +557,180 @@ TEST_F(version_check_test, wrong_version_string) EXPECT_TRUE(remove_files_from_path()); // clear files again } + +//------------------------------------------------------------------------------ +// directory for the timestamp and version files +//------------------------------------------------------------------------------ + +// Checking whether the directory is writable must not modify existing files, which might belong to someone else. +TEST_F(version_check_test, existing_dummy_file) +{ + std::filesystem::path const directory = app_tmp_path(); + std::filesystem::path const dummy_file = directory / "dummy.txt"; + ASSERT_TRUE(create_file(dummy_file, "existing content")); + + EXPECT_EQ(app_tmp_path(), directory); + EXPECT_EQ(read_first_line(dummy_file), "existing content"); + + // A file that is not writable does not affect whether the directory is writable. + std::filesystem::permissions(dummy_file, + std::filesystem::perms::owner_write | std::filesystem::perms::group_write + | std::filesystem::perms::others_write, + std::filesystem::perm_options::remove); + + EXPECT_EQ(app_tmp_path(), directory); + EXPECT_EQ(read_first_line(dummy_file), "existing content"); + + // The probe files are removed again. + EXPECT_EQ(std::ranges::distance(std::filesystem::directory_iterator{directory}), 1); +} + +// Without a home directory, the files are stored in .config/seqan relative to the current working directory. +TEST_F(version_check_test, home_not_set_or_empty) +{ + std::filesystem::path const working_directory = tmp_file.get_path().parent_path() / "working_directory"; + std::filesystem::create_directory(working_directory); + ASSERT_EQ(unsetenv(sharg::detail::version_checker::home_env_name), 0); + std::filesystem::current_path(working_directory); // Restored in TearDown. + + EXPECT_EQ(app_tmp_path(), std::filesystem::path{".config"} / "seqan"); + EXPECT_TRUE(std::filesystem::is_directory(working_directory / ".config" / "seqan")); + + // The version check writes its timestamp file there. + auto [out, err, app_call_succeeded] = simulate_parser("-f"); + EXPECT_FALSE(app_call_succeeded); + EXPECT_TRUE(app_timestamp_filename().is_relative()) << app_timestamp_filename(); + EXPECT_TRUE(std::filesystem::exists(working_directory / app_timestamp_filename())) << app_timestamp_filename(); + + // An empty home directory behaves the same. + ASSERT_EQ(setenv(sharg::detail::version_checker::home_env_name, "", 1), 0); + EXPECT_EQ(app_tmp_path(), std::filesystem::path{".config"} / "seqan"); +} + +TEST_F(version_check_test, no_writable_directory) +{ + // HOME/.config cannot be created and the fallback TMPDIR is not a directory. + std::filesystem::path const missing = tmp_file.get_path().parent_path() / "missing"; + ASSERT_EQ(setenv(sharg::detail::version_checker::home_env_name, missing.c_str(), 1), 0); + ASSERT_EQ(setenv("TMPDIR", missing.c_str(), 1), 0); + ASSERT_TRUE(app_tmp_path().empty()); + + // version_checker::message_no_writable_directory is only printed if the terminal is interactive. The tests are + // not interactive because stderr is captured. + { + auto [out, err, app_call_succeeded] = simulate_parser("-f"); + + EXPECT_EQ(out, ""); + EXPECT_EQ(err, ""); + EXPECT_FALSE(app_call_succeeded); + // Without a directory, the timestamp file would be written to the current working directory. + EXPECT_FALSE(std::filesystem::exists(app_timestamp_filename())) << app_timestamp_filename(); + } + + { + auto [out, err, app_call_succeeded] = simulate_parser(OPTION_VERSION_CHECK, OPTION_ON, "-f"); + + EXPECT_EQ(out, ""); + EXPECT_EQ(err, ""); + EXPECT_FALSE(app_call_succeeded); + // Without a directory, the version file would be downloaded to the current working directory. + EXPECT_FALSE(std::filesystem::exists(app_version_filename())) << app_version_filename(); + } +} + +TEST_F(version_check_test, tmp_directory_fallback) +{ + // HOME/.config cannot be created, hence the temporary directory is used. + std::filesystem::path const missing = tmp_file.get_path().parent_path() / "missing"; + std::filesystem::path const tmp_directory = tmp_file.get_path().parent_path() / "tmp"; + std::filesystem::create_directory(tmp_directory); + ASSERT_EQ(setenv(sharg::detail::version_checker::home_env_name, missing.c_str(), 1), 0); + ASSERT_EQ(setenv("TMPDIR", tmp_directory.c_str(), 1), 0); + + EXPECT_EQ(app_tmp_path(), tmp_directory); + + auto [out, err, app_call_succeeded] = simulate_parser("-f"); + + EXPECT_EQ(out, ""); + EXPECT_EQ(err, ""); + EXPECT_FALSE(app_call_succeeded); + EXPECT_TRUE(std::filesystem::exists(tmp_directory / app_timestamp_filename().filename())); +} + +TEST_F(version_check_test, option_off_no_directory_created) +{ + std::filesystem::path const home = tmp_file.get_path().parent_path() / "home"; + std::filesystem::create_directory(home); + ASSERT_EQ(setenv(sharg::detail::version_checker::home_env_name, home.c_str(), 1), 0); + + auto [out, err, app_call_succeeded] = simulate_parser(OPTION_VERSION_CHECK, OPTION_OFF, "-f"); + + EXPECT_EQ(out, ""); + EXPECT_EQ(err, ""); + EXPECT_FALSE(app_call_succeeded); + // The directory for the timestamp and version files is only determined (and created) if needed. + EXPECT_FALSE(std::filesystem::exists(home / ".config")); +} + +//------------------------------------------------------------------------------ +// shell quoting +//------------------------------------------------------------------------------ + +#if !defined(_WIN32) +TEST_F(version_check_test, quote_argument) +{ + std::filesystem::path const tmp_directory = tmp_file.get_path().parent_path(); + std::filesystem::path const out_file = tmp_directory / "quoted.out"; + std::string const marker = (tmp_directory / "injected").string(); + + for (std::string const & argument : {std::string{"with space"}, + std::string{"it's"}, + std::string{"''"}, + "a;touch " + marker + ";b", + "$(touch " + marker + ")", + "`touch " + marker + "`", + std::string{"\"double\" \\back\\slash $HOME *"}, + std::string{"line\nbreak"}}) + { + std::string const command = "printf '%s' " + sharg::detail::quote_argument(argument) + " > " + + sharg::detail::quote_argument(out_file.string()); + ASSERT_EQ(std::system(command.c_str()), 0) << command; + + std::ifstream file{out_file}; + EXPECT_EQ((std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}), argument); + } + + EXPECT_FALSE(std::filesystem::exists(marker)); +} +#endif // !defined(_WIN32) + +// The path of the version file is derived from the home directory and passed to the shell. +TEST_F(version_check_test, home_with_shell_metacharacters) +{ + // Without wget or curl, no command is executed and the test would pass regardless of the quoting. + if (std::system("/usr/bin/env -i wget --version > /dev/null 2>&1") + && std::system("/usr/bin/env -i curl --version > /dev/null 2>&1")) + GTEST_SKIP() << "Neither wget nor curl is available."; + + std::filesystem::path const tmp_directory = tmp_file.get_path().parent_path(); + std::filesystem::path const marker = tmp_directory / "injected"; + std::filesystem::path const home = tmp_directory / ("home;touch " + marker.string() + ";x"); + + // The home directory must exist, otherwise the tmp directory is used. + std::filesystem::create_directories(home); + ASSERT_EQ(setenv(sharg::detail::version_checker::home_env_name, home.c_str(), 1), 0); + ASSERT_TRUE(app_tmp_path().string().starts_with(home.string())) << app_tmp_path(); + + auto [out, err, app_call_succeeded] = simulate_parser(OPTION_VERSION_CHECK, OPTION_ON, "-f"); + + EXPECT_EQ(out, ""); + EXPECT_EQ(err, ""); + EXPECT_FALSE(std::filesystem::exists(marker)); + + if (app_call_succeeded) + { + EXPECT_TRUE(std::filesystem::exists(app_version_filename())); + } + + EXPECT_TRUE(remove_files_from_path()); // clear files again +}