From 86e8dd97ab4c09d9c94d5626f24eceb214237866 Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Tue, 10 Nov 2026 13:35:48 +0200 Subject: [PATCH 1/7] fix(uninstall): refuse system folders and homes, require ROCm CLI's marker elsewhere `rocm uninstall` had no protected-location check: ROCM_CLI_DATA_DIR=/ or an SDK installed with `--prefix ~` could make it remove `/` or the home folder, and so could a home folder spelled as `.` or reached through a symlinked parent. Each config, data and cache root is now judged both as written and by where it really is. The filesystem root, system folders, folders other programs share, the home folder, anything containing it and other users' homes are refused; anything inside the user's own home is allowed; any other folder is removed only if it carries `.rocm-cli-root`, which ROCm CLI writes only into folders it creates itself (its setup, the first log line, the first config save, the download-metadata and vLLM cache writes, and an SDK `--prefix`). A refusal stops the whole command before the prompt, names the folder, the reason and the setting it came from (a cache folder that follows the data folder names the data folder's setting), and says what clears it. A refused dry run says so and exits non-zero. Every entry is re-checked just before removal, an entry already removed with an earlier one is still reported, and a shared cache inside a folder being removed is listed as WILL BE DELETED before confirmation. Confirmation goes through rocm-core's shared yes/terminal guard. The dashboard's /uninstall now passes --keep-* and --force-dev-binaries through, the assistant's preview honours them, and `rocm` children run for the dashboard and assistant receive ROCM_CLI_APP_PATH_SOURCES so their refusals name the setting the user actually made. The assistant refuses an SDK --prefix by the runtime-folder rule and says why, and the runtime and prune refusals now name the reason. Signed-off-by: Roman Inflianskas --- README.md | 52 +- apps/rocm/src/chat.rs | 5 + apps/rocm/src/chat/mcp_bridge.rs | 18 +- apps/rocm/src/cli.rs | 11 +- apps/rocm/src/deletion_properties.rs | 171 +- apps/rocm/src/engine_ipc.rs | 11 + apps/rocm/src/engine_runtime_select.rs | 24 +- apps/rocm/src/logging.rs | 32 + apps/rocm/src/runtime_uninstall.rs | 48 +- apps/rocm/src/storage.rs | 59 +- apps/rocm/src/therock.rs | 6 +- apps/rocm/src/therock/fetch.rs | 2 + apps/rocm/src/therock/python.rs | 84 + apps/rocm/src/tool_policy.rs | 30 +- apps/rocm/src/uninstall.rs | 343 +++- apps/rocm/src/uninstall_plan.rs | 1805 ++++++++++++++++- crates/rocm-core/src/config.rs | 32 + crates/rocm-core/src/confirm.rs | 10 +- crates/rocm-core/src/lib.rs | 39 +- crates/rocm-core/src/paths.rs | 236 ++- crates/rocm-core/src/runtime.rs | 936 ++++++++- crates/rocm-dash-tui/src/app/slash.rs | 91 +- docs/architecture.md | 6 +- docs/manual-testing.md | 96 + docs/testing.md | 33 +- engines/vllm/src/install.rs | 3 +- tests/e2e-cucumber/features/uninstall.feature | 74 +- .../e2e-cucumber/tests/e2e/lifecycle_steps.rs | 11 +- tests/e2e-cucumber/tests/e2e/runtime_steps.rs | 8 +- .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 734 +++++-- 30 files changed, 4560 insertions(+), 450 deletions(-) diff --git a/README.md b/README.md index a46d140315..5ae906b83f 100644 --- a/README.md +++ b/README.md @@ -1780,10 +1780,54 @@ Before removing anything, `uninstall` prints warnings about two situations: Otherwise the model keeps running on the remote machine with its endpoint published, and the record that tracked it is gone. -It also lists the shared caches it leaves in place, when they live outside the -ROCm CLI directories: a `uv` package cache that `UV_CACHE_DIR` or the default -`~/.cache/uv` points to, and the Hugging Face model cache. Delete them yourself -if you no longer need them. +It also names the shared caches: a `uv` package cache that `UV_CACHE_DIR` or +the default `~/.cache/uv` points to, and the Hugging Face model cache. One that +lives outside the folders being removed is left in place; delete it yourself if +you no longer need it. If one sits inside a folder being removed (for example +`ROCM_CLI_CACHE_DIR=~/.cache`), the review says it WILL BE DELETED before you +confirm, and which `--keep-` flag keeps it. + +`rocm uninstall` removes a config, data, or cache folder inside your home +folder as usual. It never removes: + +- `/`, your home folder, or a folder that contains it; +- `/usr`, `/etc`, `/boot`, `/bin`, `/sbin`, `/lib`, `/lib32`, `/lib64`, `/libx32`, `/sys`, `/proc`, `/dev`, + `/run`, `/media`, `/snap`, or anything inside them — on Windows, `Windows`, + `Program Files`, `Program Files (x86)` and `ProgramData` on the system drive, + and the same folders on a drive WSL mounts at `/mnt/`; +- a folder other programs share: anything directly under `/` (`/opt`, `/srv`, + `/tmp`, ...), `/var/lib`, `/var/cache`, `/var/log`, `/var/tmp`, or a mounted + drive itself (`/mnt/c`); +- another user's home folder (anything under `/home`, `/Users`, `C:\Users` + or a WSL drive's `Users`, or beside your own home, that is not inside yours). + +Anywhere else outside your home folder — `/opt/rocm-cli`, `/srv/rocm`, +`/mnt/d/rocm`, another disk — it removes a folder only if it carries a +`.rocm-cli-root` file. ROCm CLI writes that file only into a folder it creates +itself: the config, data and cache folders when its setup, its first log line +or its first config save creates them, the cache folder its download metadata +or a vLLM install first writes to, and an SDK `--prefix` it creates. A folder +that already existed, one made by hand, one made by a release before this one, +or one some other command happened to create first is not marked, and is +refused rather than removed until you create the file or keep the folder. The check looks at where a folder really is as well as how it is +written, so `ROCM_CLI_DATA_DIR=.` run from your home folder, a home reached +through a linked parent folder, or a system folder reached through a link is +caught too. + +If a folder is refused (for example `ROCM_CLI_DATA_DIR=/`, or an SDK installed +with `--prefix ~`), the review lists it under "Refused" with why and the +setting it came from, the command exits with an error, and nothing is removed. +The message says what clears it: re-run with the `--keep-config`, +`--keep-data`, or `--keep-cache` flag to leave that folder in place; point the +`ROCM_CLI_*_DIR` variable it came from elsewhere; or, for an unmarked folder +that is ROCm CLI's, create the `.rocm-cli-root` file it names. For a folder +set by `setup.therock_venv`, use `--keep-data`: moving that setting would leave +the SDK installed there behind. The same flags work in the dashboard's +`/uninstall` and in the assistant's preview, and their refusals name the same +setting. Between the review and the removal, each folder is resolved again; +if it now points somewhere else, the uninstall stops instead. +`rocm runtimes uninstall` and `rocm storage remove-old-installs` keep their own +rule for runtime folders. ### Shell completions diff --git a/apps/rocm/src/chat.rs b/apps/rocm/src/chat.rs index e817f0ab97..d54d6e5fc9 100644 --- a/apps/rocm/src/chat.rs +++ b/apps/rocm/src/chat.rs @@ -34,6 +34,11 @@ pub(crate) use self::summaries::deterministic_comfyui_tool_summary; // `run_internal_mcp_call` lives in `mcp_bridge.rs` and stays reachable here as // `chat::run_internal_mcp_call` for `main.rs` and `dash_seam.rs`. pub(crate) use self::mcp_bridge::run_internal_mcp_call; +// `run_rocm_read_only_in_process` lives in `mcp_bridge.rs` and stays +// reachable here for `uninstall_plan.rs`'s tests, which prove the assistant's +// in-process uninstall preview honours the `--keep-*` flags a refusal advises. +#[cfg(test)] +pub(crate) use self::mcp_bridge::run_rocm_read_only_in_process; // `rocm_chat_tool_system_prompt_for_host` lives in `turn.rs` and stays // reachable here as `chat::rocm_chat_tool_system_prompt_for_host` for `dash.rs`. use self::turn::render_chat_prompt_result_with_progress; diff --git a/apps/rocm/src/chat/mcp_bridge.rs b/apps/rocm/src/chat/mcp_bridge.rs index a4a7238f94..4e719c1c96 100644 --- a/apps/rocm/src/chat/mcp_bridge.rs +++ b/apps/rocm/src/chat/mcp_bridge.rs @@ -22,6 +22,7 @@ use super::summaries::managed_service_running_state; use crate::automations::{render_automations_text, render_daemon_text}; +use crate::engine_runtime_select::rocm_child_app_path_env; use crate::freeform_planner::{format_structured_tool_call, plan_freeform_request_with_context}; use crate::managed_service_status::{load_managed_services, managed_service_is_live}; use crate::rocm_argv::{chat_cli_arg_value, chat_cli_has_flag}; @@ -31,7 +32,7 @@ use crate::services_text::{ render_services_text, }; use crate::tool_policy::{ - ChatRocmCommandAction, chat_install_prefix_is_system, chat_rocm_command_action, + ChatRocmCommandAction, chat_install_prefix_protection, chat_rocm_command_action, chat_tool_call_is_read_only, json_string, rocm_chat_tool_requested_args, validate_chat_tool_call, }; @@ -457,7 +458,12 @@ fn run_rocm_capture_for_paths( args: &[&str], timeout: Duration, ) -> Result { - rocm_core::run_rocm_capture_with_env(args, &paths.env_vars(), timeout) + let vars = rocm_child_app_path_env(paths); + let env = vars + .iter() + .map(|(key, value)| (*key, Path::new(value))) + .collect::>(); + rocm_core::run_rocm_capture_with_env(args, &env, timeout) } fn run_rocm_command_for_paths( @@ -483,7 +489,7 @@ fn run_rocm_command_for_paths( } } -fn run_rocm_read_only_in_process(paths: &AppPaths, args: &[String]) -> Result { +pub(crate) fn run_rocm_read_only_in_process(paths: &AppPaths, args: &[String]) -> Result { let config = RocmCliConfig::load(paths).unwrap_or_default(); match args { [] => bail!("rocm command requires at least one argument"), @@ -599,7 +605,7 @@ fn run_rocm_read_only_in_process(paths: &AppPaths, args: &[String]) -> Result { - render_uninstall_dry_run(paths) + render_uninstall_dry_run(paths, rest) } [command] if command.eq_ignore_ascii_case("setup") => { render_setup_status_text(paths, &config) @@ -682,9 +688,9 @@ fn internal_mcp_install_sdk_args( ]; if let Some(prefix) = json_string(arguments, "prefix") { let prefix_path = Path::new(&prefix); - if chat_install_prefix_is_system(prefix_path) { + if let Some(why) = chat_install_prefix_protection(prefix_path) { bail!( - "install_sdk prefix `{}` is a system folder; choose a user folder instead", + "install_sdk prefix `{}` is {why}; choose a user folder instead", prefix_path.display() ); } diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 310474b111..2702c12586 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -697,10 +697,17 @@ rocm logs --search error timeout")] /// warning). It also undoes the PATH change the installer made (its marked /// shell-profile block, or the user PATH entry it recorded adding on /// Windows), unless other programs share the install folder. - #[command(after_help = "EXAMPLES:\n \ + #[command( + after_help = "Never removes /, your home folder or one containing it, another user's home, a \ +system location (/usr, /etc, /lib, /run, ...; Windows, Program Files, ProgramData), or a shared \ +folder (anything directly under /, /var/lib, /mnt/, ...). Outside your home folder it \ +removes only a folder holding the .rocm-cli-root file ROCm CLI writes into folders it creates. A \ +refusal stops the whole uninstall and says what clears it. See the README for the full rules.\n\n\ +EXAMPLES:\n \ rocm uninstall --dry-run\n \ rocm uninstall\n \ -rocm uninstall --keep-data --yes")] +rocm uninstall --keep-data --yes" + )] Uninstall { /// Do not ask for interactive confirmation. Without it, the command /// asks `[y/N]` (default: no) in an interactive terminal; outside one, diff --git a/apps/rocm/src/deletion_properties.rs b/apps/rocm/src/deletion_properties.rs index a664dbef0b..4f772a0725 100644 --- a/apps/rocm/src/deletion_properties.rs +++ b/apps/rocm/src/deletion_properties.rs @@ -24,7 +24,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use proptest::prelude::*; use proptest::test_runner::{Config, TestCaseError, TestRunner}; -use rocm_core::AppPaths; +use rocm_core::{AppPathSources, AppPaths}; use crate::uninstall_plan::{UninstallOptions, build_uninstall_plan, remove_path}; @@ -516,6 +516,14 @@ enum Target { RegularFile, /// A symlink planted in home whose target does not exist. DanglingLink, + /// `$HOME` spelled relative to the process's working directory — what + /// `ROCM_CLI_DATA_DIR=.` run from home amounts to. + RelativeHome, + /// `/Documents/..` spelled relative to the working directory — `..` + /// run from a project folder in home. + RelativeHomeViaChild, + /// `$HOME` reached through a symlink to its parent (`/home -> var/home`). + HomeViaLinkedParent, } #[derive(Debug, Clone, Copy)] @@ -538,6 +546,9 @@ fn target() -> impl Strategy { 1 => Just(Target::LinkToHome), 1 => Just(Target::RegularFile), 1 => Just(Target::DanglingLink), + 1 => Just(Target::RelativeHome), + 1 => Just(Target::RelativeHomeViaChild), + 1 => Just(Target::HomeViaLinkedParent), ] } @@ -592,13 +603,42 @@ fn resolve_target(home: &Path, name: &str, target: Target, spelling: Spelling) - let _ = symlink(home.join("does-not-exist"), &link); link } + Target::RelativeHome => relative_from_cwd(home), + Target::RelativeHomeViaChild => relative_from_cwd(&home.join("Documents")).join(".."), + Target::HomeViaLinkedParent => { + let sandbox = home.parent().expect("home has a parent"); + let link = sandbox.join(format!("linked-parent-{name}")); + let _ = symlink(sandbox, &link); + link.join(home.file_name().expect("home has a name")) + } }; respell(&raw, spelling) } /// Is `target` one that plainly names somewhere ROCm CLI did not create? const fn names_foreign_dir(target: Target) -> bool { - matches!(target, Target::Home | Target::LinkToHome) + matches!( + target, + Target::Home + | Target::LinkToHome + | Target::RelativeHome + | Target::RelativeHomeViaChild + | Target::HomeViaLinkedParent + ) +} + +/// `target` spelled relative to this process's working directory with `..` +/// segments, so a case can use a relative root without changing the +/// (process-global) working directory. +fn relative_from_cwd(target: &Path) -> PathBuf { + let cwd = std::env::current_dir() + .and_then(|cwd| cwd.canonicalize()) + .expect("working directory"); + let mut relative = PathBuf::new(); + for _ in cwd.components().skip(1) { + relative.push(".."); + } + relative.join(target.strip_prefix("/").expect("absolute target")) } fn uninstall_case( @@ -645,6 +685,9 @@ fn uninstall_case( Target::LinkToHome => "target: symlink -> $HOME", Target::RegularFile => "target: regular file", Target::DanglingLink => "target: dangling symlink", + Target::RelativeHome => "target: $HOME, relative to cwd", + Target::RelativeHomeViaChild => "target: $HOME/Documents/.., relative", + Target::HomeViaLinkedParent => "target: $HOME via a symlinked parent", }); reach.hit(match s { Spelling::Plain => "spelling: plain", @@ -660,13 +703,41 @@ fn uninstall_case( } } + // Shared caches the review must talk about truthfully: one inside the + // own cache dir, one inside the own data dir, one outside everything. + let shared_caches = [ + rocm.join("cache").join("uv-shared"), + rocm.join("data").join("hf-hub"), + home.join(".cache").join("uv"), + ]; + for cache in &shared_caches { + std::fs::create_dir_all(cache).expect("shared cache"); + std::fs::write(cache.join("blob"), b"cached").expect("shared cache blob"); + } + let candidates: Vec = shared_caches + .iter() + .map(|path| crate::uninstall_plan::SharedCache { + path: path.clone(), + kept: "a shared cache is", + name: "a shared cache", + loss: "It is shared.", + pronoun: "it", + }) + .collect(); + let options = UninstallOptions { yes: true, keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options) - .map_err(|error| TestCaseError::fail(format!("plan failed: {error:#}")))?; + let plan = crate::uninstall_plan::build_uninstall_plan_for_home( + &paths, + &AppPathSources::default(), + &options, + Some(&home), + ) + .map_err(|error| TestCaseError::fail(format!("plan failed: {error:#}")))?; + let notes = crate::uninstall_plan::shared_cache_notes_for(&plan.actions, &candidates); let rendered = crate::uninstall_plan::render_uninstall_plan( &plan, &UninstallOptions { @@ -677,23 +748,39 @@ fn uninstall_case( ); let planned: BTreeSet = plan.actions.iter().map(|e| e.path.clone()).collect(); prop_assert_eq!(&listed_in_render(&rendered), &planned, "{}", rendered); + let refused = !plan.refused.is_empty(); + if refused { + reach.lock().expect("reach lock").hit("plan: refused"); + // The review names every refused root and the flag that clears it. + for root in &plan.refused { + prop_assert!( + rendered.contains(&root.path.display().to_string()) + && rendered.contains(&format!("--keep-{}", root.kind)), + "refused {} root not named with its remedy:\n{}", + root.kind, + rendered + ); + } + } let before = snapshot(&sandbox); let mut expected_gone = BTreeSet::new(); - for path in &planned { - assert_inside_sandbox(&sandbox, path); - if let Some(id) = identity_of(path) { - expected_gone.extend(subtree_ids(&before, id)); + if !refused { + for path in &planned { + assert_inside_sandbox(&sandbox, path); + if let Some(id) = identity_of(path) { + expected_gone.extend(subtree_ids(&before, id)); + } } } - for entry in &plan.actions { - remove_path(&entry.path).map_err(|error| { - TestCaseError::fail(format!( - "remove_path({}) failed: {error:#}", - entry.path.display() - )) - })?; - } + // The real removal step, which refuses on its own when the plan does. + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + prop_assert_eq!( + outcome.is_err(), + refused, + "apply_uninstall_plan result {:?} disagrees with the plan's refusal", + outcome + ); let after = snapshot(&sandbox); let actually_gone: BTreeSet<(u64, u64)> = before .keys() @@ -763,6 +850,31 @@ fn uninstall_case( describe(&missed) ); + // Every shared cache is mentioned exactly once, and the review warns + // that it will be deleted exactly when the removal deleted it. + for cache in &shared_caches { + let text = cache.display().to_string(); + let mentions: Vec<&String> = notes.iter().filter(|n| n.contains(&text)).collect(); + prop_assert_eq!(mentions.len(), 1, "{} mentioned {:?}", text, mentions); + let warned = mentions[0].contains("WILL BE DELETED"); + if !refused { + let deleted = !cache.join("blob").exists(); + prop_assert_eq!( + warned, + deleted, + "{} deleted={} but the review said: {}", + text, + deleted, + mentions[0] + ); + reach.lock().expect("reach lock").hit(if deleted { + "shared cache: deleted and warned" + } else { + "shared cache: kept and noted" + }); + } + } + if require_safety { for sentinel in [ home.join("Documents/thesis.txt"), @@ -820,12 +932,10 @@ fn uninstall_removes_exactly_what_the_review_lists() { } /// Safety: `rocm uninstall` must never delete a folder ROCm CLI did not create. -/// It applies no guard at all to the three AppPaths roots, so a data/cache/ -/// config dir that names `$HOME` itself is deleted wholesale (a link to it, -/// however spelled, is only unlinked). Shrinks to one root naming `$HOME`. -/// Tracked in #531; un-ignore this when that guard lands. +/// A data/cache/config dir that names `$HOME` (directly, or through a link, +/// however spelled) must be refused or unlinked, never emptied — the shape +/// this used to shrink to was `cache_dir = $HOME`. #[test] -#[ignore = "known gap: rocm uninstall applies no guard to config/data/cache roots (#531)"] fn uninstall_never_deletes_a_folder_rocm_cli_did_not_create() { if let Err(error) = run_uninstall_property(case_count(), true) { panic!("{error}"); @@ -853,7 +963,15 @@ fn uninstall_removes_a_link_whose_target_an_earlier_step_removed() { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options).expect("plan"); + // Judged against the sandbox home, so the data folder inside it is removed + // first and the link really dangles by its turn. + let plan = crate::uninstall_plan::build_uninstall_plan_for_home( + &paths, + &AppPathSources::default(), + &options, + Some(&home), + ) + .expect("plan"); let listed = plan.actions.iter().any(|entry| entry.path == link); for entry in &plan.actions { remove_path(&entry.path).expect("remove"); @@ -888,7 +1006,7 @@ fn uninstall_lists_and_removes_a_dangling_link_root() { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options).expect("plan"); + let plan = build_uninstall_plan(&paths, &AppPathSources::default(), &options).expect("plan"); let listed = plan.actions.iter().any(|entry| entry.path == link); for entry in &plan.actions { remove_path(&entry.path).expect("remove"); @@ -919,7 +1037,7 @@ fn uninstall_plan_fails_when_a_root_cannot_be_checked() { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options); + let plan = build_uninstall_plan(&paths, &AppPathSources::default(), &options); cleanup(&sandbox); let error = plan.expect_err("a root that cannot be checked must fail the plan"); let message = format!("{error:#}"); @@ -948,7 +1066,7 @@ fn a_root_below_a_regular_file_is_not_present() { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options); + let plan = build_uninstall_plan(&paths, &AppPathSources::default(), &options); let removal = remove_path(&cache); let file_kept = file.is_file(); cleanup(&sandbox); @@ -1046,7 +1164,8 @@ fn a_regular_file_spelled_as_a_directory_is_not_removed() { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options).expect("plan"); + let plan = + build_uninstall_plan(&paths, &AppPathSources::default(), &options).expect("plan"); cleanup(&sandbox); assert!( diff --git a/apps/rocm/src/engine_ipc.rs b/apps/rocm/src/engine_ipc.rs index d36318c7ae..1a7e181f91 100644 --- a/apps/rocm/src/engine_ipc.rs +++ b/apps/rocm/src/engine_ipc.rs @@ -211,6 +211,17 @@ impl Drop for ScopedEnvVar { } } +/// Hold the lock `with_scoped_builtin_engine_env` takes while it rewrites the +/// `ROCM_CLI_*` variables, for a test that reads them and must not see a +/// built-in engine call's values in the middle of a parallel test. +#[cfg(test)] +pub(crate) fn builtin_engine_env_test_lock() -> std::sync::MutexGuard<'static, ()> { + BUILTIN_ENGINE_ENV_LOCK + .get_or_init(|| Mutex::new(())) + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + fn with_scoped_builtin_engine_env( paths: Option<&AppPaths>, env_root: Option<&Path>, diff --git a/apps/rocm/src/engine_runtime_select.rs b/apps/rocm/src/engine_runtime_select.rs index aa65af269d..fd6a945c6d 100644 --- a/apps/rocm/src/engine_runtime_select.rs +++ b/apps/rocm/src/engine_runtime_select.rs @@ -12,7 +12,8 @@ //! `daemon_run_argv`, `managed_service_launcher_path`), the `ROCM_CLI_*` //! environment variables every managed child inherits //! (`app_path_env_var_values`/`app_path_env_var_refs`, over -//! [`AppPaths::env_vars`]; a command gets them from `AppPaths::apply_env`), and polling a freshly launched service until it can +//! [`AppPaths::env_vars`]; a command gets them from `AppPaths::apply_env`, and a `rocm` +//! child also gets the folders' sources from `rocm_child_app_path_env`), and polling a freshly launched service until it can //! actually answer inference requests (`wait_for_service_http_ready`, //! `wait_for_service_http_ready_with_progress`, //! `service_http_readiness_paths`, `http_get_local_service`, @@ -64,6 +65,7 @@ //! `engine_recipe_json_arg` is `pub(crate)`, read from `engine_ipc.rs`'s //! `engine_request`; `parse_engine_recipe_json_arg` is `pub(crate)`, read //! from `main.rs`'s `dispatch()` and `service_control.rs`'s `restart_child_argv`. +//! `rocm_child_app_path_env` is `pub(crate)`, read from `chat/mcp_bridge.rs`; //! `app_path_env_var_values`/ //! `app_path_env_var_refs` are `pub(crate)`, read from `service_launch.rs` //! and `service_control.rs`'s `restart_internal_managed_service_with`. @@ -304,6 +306,26 @@ pub(crate) fn managed_service_launcher_path() -> Result { Ok(current_exe) } +/// [`AppPaths::env_vars`] for a `rocm` child run on the user's behalf (the +/// dashboard's and assistant's approved commands). The variables pin the +/// child's folders, which would make it report every one as "set by +/// ROCM_CLI_*_DIR"; this also tells it where each pinned folder really came +/// from, so a refusal names a setting the user can change. Not used for an +/// interactive shell or an engine, which have no use for it. +pub(crate) fn rocm_child_app_path_env(paths: &AppPaths) -> Vec<(&'static str, OsString)> { + let mut vars = paths + .env_vars() + .into_iter() + .map(|(key, value)| (key, value.as_os_str().to_owned())) + .collect::>(); + if let Ok(sources) = + serde_json::to_string(&rocm_core::ForwardedAppPathSources::for_paths(paths)) + { + vars.push((rocm_core::APP_PATH_SOURCES_ENV, OsString::from(sources))); + } + vars +} + pub(crate) fn wait_for_service_http_ready( engine: &str, host: &str, diff --git a/apps/rocm/src/logging.rs b/apps/rocm/src/logging.rs index b6174f5af1..73d4e387e1 100644 --- a/apps/rocm/src/logging.rs +++ b/apps/rocm/src/logging.rs @@ -99,6 +99,10 @@ pub fn init(paths: &AppPaths) -> Option { fn validated_log_dir(paths: &AppPaths) -> Option { let root = paths.data_dir.as_path(); let log_dir = paths.client_log_dir(); + // Logging is usually what first brings the data folder into being, so it + // is created here as ROCm CLI's own (marked), and only if this call is + // what creates it. + rocm_core::create_marked_root(root).ok()?; std::fs::create_dir_all(&log_dir).ok()?; let canonical_root = std::fs::canonicalize(root).ok()?; @@ -198,6 +202,34 @@ mod tests { assert!(is_enabled_for(&args(&["uninstall-all"]))); } + /// Logging usually creates the data folder first; when it does, the + /// folder is marked as ROCm CLI's own. A data folder that was already + /// there is not marked. + #[test] + fn the_data_folder_logging_creates_is_marked_and_an_existing_one_is_not() { + let (root, fresh) = temp_paths("marks-data-root"); + validated_log_dir(&fresh).expect("log dir"); + let fresh_marked = fresh + .data_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .is_file(); + + let (other_root, existing) = temp_paths("keeps-existing-data-root"); + std::fs::create_dir_all(&existing.data_dir).unwrap(); + validated_log_dir(&existing).expect("log dir"); + let existing_marked = existing + .data_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .exists(); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(&other_root); + assert!( + fresh_marked, + "the data folder logging created is not marked" + ); + assert!(!existing_marked, "an existing data folder was marked"); + } + #[test] fn temp_paths_gives_each_call_its_own_root_even_for_one_label() { crate::test_support::assert_each_call_gets_its_own_root(|| temp_paths("same-label").0); diff --git a/apps/rocm/src/runtime_uninstall.rs b/apps/rocm/src/runtime_uninstall.rs index e140cf1550..3498ff6357 100644 --- a/apps/rocm/src/runtime_uninstall.rs +++ b/apps/rocm/src/runtime_uninstall.rs @@ -23,7 +23,7 @@ use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; -use rocm_core::{AppPaths, RocmCliConfig, runtime_install_root_is_protected}; +use rocm_core::{AppPaths, RocmCliConfig}; use rocm_engine_lemonade::RecordCleanup; use crate::cli_report; @@ -418,6 +418,17 @@ fn local_runtime_manifest_matches(manifest: &therock::InstalledRuntimeManifest) } fn ensure_runtime_install_root_is_safe_to_remove(path: &Path) -> Result<()> { + ensure_runtime_install_root_is_safe_to_remove_for_home( + path, + rocm_core::runtime_home_dir().as_deref(), + ) +} + +/// [`ensure_runtime_install_root_is_safe_to_remove`] judged against `home`. +fn ensure_runtime_install_root_is_safe_to_remove_for_home( + path: &Path, + home: Option<&Path>, +) -> Result<()> { if path.as_os_str().is_empty() || path.parent().is_none() || path.file_name().is_none() { bail!( "refusing to remove unsafe runtime folder {}", @@ -429,12 +440,13 @@ fn ensure_runtime_install_root_is_safe_to_remove(path: &Path) -> Result<()> { // matching in-tree `.rocm-cli-runtime.json`, slipping past // `local_runtime_manifest_matches`. `prune` already refuses these before // ever calling this function (see storage.rs); check it here too so the - // single source of truth for "may ROCm CLI delete this folder?" refuses + // runtime-folder rule (`rocm uninstall`'s own roots have their own) refuses // it for every caller, including a direct `runtimes uninstall `. - if runtime_install_root_is_protected(path) { + if let Some(why) = rocm_core::runtime_protected_location_for_home(path, home) { bail!( - "refusing to remove runtime folder {} in a protected system location", - path.display() + "refusing to remove runtime folder {} because it is {}", + path.display(), + why.describe() ); } Ok(()) @@ -728,7 +740,7 @@ mod tests { // registry entry could point a direct `runtimes uninstall ` // manifest's `install_root` at the same kind of path while still // carrying a matching in-tree `.rocm-cli-runtime.json`, slipping past - // `local_runtime_manifest_matches`. The single source of truth for + // `local_runtime_manifest_matches`. The runtime-folder rule for // "may ROCm CLI delete this folder?" must refuse it too, regardless // of caller. let protected = if cfg!(windows) { @@ -742,6 +754,30 @@ mod tests { assert!(err.to_string().contains("protected system location")); } + /// `rocm runtimes uninstall` and `rocm storage remove-old-installs` share + /// the protected-location predicate with `rocm uninstall`, so a runtime + /// whose `install_root` is the home folder itself (`--prefix ~`) is refused + /// too — and the refusal says it is the home folder, not a system location. + #[test] + fn ensure_runtime_install_root_refuses_the_home_folder_by_name() { + // A fixed home, so the check cannot fall back to some other refusal + // on a host whose home is `/`. + let home = Path::new("/home/alice"); + let err = ensure_runtime_install_root_is_safe_to_remove_for_home(home, Some(home)) + .expect_err("the home folder must be refused"); + assert_eq!( + err.to_string(), + "refusing to remove runtime folder /home/alice because it is your home folder" + ); + // The real gate consults the real home. + let real_home = rocm_core::runtime_home_dir().expect("a home directory"); + if real_home.parent().is_some() { + let err = ensure_runtime_install_root_is_safe_to_remove(&real_home) + .expect_err("the real home folder must be refused"); + assert!(err.to_string().ends_with("is your home folder"), "{err}"); + } + } + /// The gate above is the last thing between a registry entry and /// `fs::remove_dir_all`, and the path it is handed is text somebody else /// wrote. One folder has many spellings, so the refusal has to survive all diff --git a/apps/rocm/src/storage.rs b/apps/rocm/src/storage.rs index d1c08eaca6..f810a2bc44 100644 --- a/apps/rocm/src/storage.rs +++ b/apps/rocm/src/storage.rs @@ -23,9 +23,7 @@ use std::fmt::Write as _; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; -use rocm_core::{ - AppPaths, RocmCliConfig, require_yes_or_interactive, runtime_install_root_is_protected, -}; +use rocm_core::{AppPaths, RocmCliConfig, require_yes_or_interactive}; use serde::Serialize; use crate::cli_report::{JsonOrText, print_json_or_text}; @@ -895,15 +893,16 @@ pub(crate) fn build_prune_plan( // Belt and braces on top of `should_remove_runtime_install_root`: prune // acts on a set the user never typed out, so a runtime whose folder sits // in a protected system location is refused outright. - if runtime_install_root_is_protected(&manifest.install_root) { + if let Some(why) = rocm_core::runtime_protected_location(&manifest.install_root) { plan.skipped.push(format!( - "{runtime_key}: folder {} is in a protected system location", - manifest.install_root.display() + "{runtime_key}: folder {} is {}, so it is left in place", + manifest.install_root.display(), + why.describe() )); continue; } - // The single source of truth for "may ROCm CLI delete this folder?". + // The runtime-folder rule for "may ROCm CLI delete this folder?". // It refuses read-only and imported records and requires a matching // in-tree manifest, and it runs `ensure_runtime_install_root_is_safe_to_remove`. match should_remove_runtime_install_root(manifest) { @@ -1046,7 +1045,11 @@ pub(crate) fn build_downloads_plan(paths: &AppPaths) -> UninstallPlan { stack.push(path); } else { found = true; - plan.actions.push(UninstallPlanEntry { kind, path }); + plan.actions.push(UninstallPlanEntry { + kind, + path, + planned: crate::uninstall_plan::PlannedAs::Unchecked, + }); } } } @@ -1626,6 +1629,46 @@ mod tests { ); } + /// A registry entry whose folder sits in a protected location is left in + /// place by prune, and the line says which folder and why. + #[test] + fn prune_plan_leaves_a_protected_install_folder_and_says_why() -> Result<()> { + let (root, paths) = test_paths("prune-protected"); + let mut old = install_fixture(&paths, manifest("old", "gfx110X-all", "7.10.0", 10), 64)?; + install_fixture(&paths, manifest("newer", "gfx110X-all", "7.11.0", 20), 64)?; + // In the host's own spelling: the registry entry is read back + // normalized, and the line prints it that way. + let protected = if cfg!(windows) { + PathBuf::from(r"C:\Windows\rocm-cli-prune-test") + } else { + PathBuf::from("/etc/rocm-cli-prune-test") + }; + old.install_root = protected.clone(); + std::fs::write( + paths + .data_dir + .join("runtimes") + .join("registry") + .join("old.json"), + serde_json::to_vec_pretty(&old)?, + )?; + + let plan = build_prune_plan(&paths, &RocmCliConfig::default(), 1)?; + let _ = std::fs::remove_dir_all(root); + + assert!(plan.remove.is_empty(), "{:?}", plan.remove); + let expected = format!( + "old: folder {} is a protected system location, so it is left in place", + protected.display() + ); + assert!( + plan.skipped.contains(&expected), + "expected `{expected}` in {:?}", + plan.skipped + ); + Ok(()) + } + #[test] fn prune_plan_skips_installs_without_a_matching_in_tree_manifest() -> Result<()> { let (root, paths) = test_paths("prune-plan"); diff --git a/apps/rocm/src/therock.rs b/apps/rocm/src/therock.rs index 38434f6dc1..b072555e66 100644 --- a/apps/rocm/src/therock.rs +++ b/apps/rocm/src/therock.rs @@ -42,7 +42,7 @@ pub(crate) use self::probe::{ use self::process::{extract_tarball_and_discard_archive, progress_line, run_uv_progress_command}; pub(crate) use self::python::NEXT_MANAGED_PYTHON_VERSION; use self::python::{ - ensure_uv_venv, managed_python_version, python_for_install, python_requirement, + ensure_marked_uv_venv, managed_python_version, python_for_install, python_requirement, python_requirement_for_version, }; use self::resolve::{ @@ -624,7 +624,7 @@ fn install_wheel_runtime( "Creating Python environment at {}.", install_root.display() )); - ensure_uv_venv(paths, &uv, &python_launcher.executable, &install_root)?; + ensure_marked_uv_venv(paths, &uv, &python_launcher.executable, &install_root)?; let env_python = venv_python_path(&install_root); progress_line(format!( @@ -922,7 +922,7 @@ fn install_tarball_runtime( } fs::create_dir_all(paths.cache_dir.join("therock"))?; - fs::create_dir_all(&install_root)?; + rocm_core::create_marked_root(&install_root)?; ensure_tarball_install_target_is_clean(&install_root)?; if let Some(warning) = preflight_tarball_space(&artifact.url, &cache_path, &install_root)? { diff --git a/apps/rocm/src/therock/fetch.rs b/apps/rocm/src/therock/fetch.rs index 6829709e25..018555d63b 100644 --- a/apps/rocm/src/therock/fetch.rs +++ b/apps/rocm/src/therock/fetch.rs @@ -416,6 +416,8 @@ pub(super) fn download_text_cached( let cache_dir = body_path .parent() .context("metadata cache path has no parent directory")?; + // The cache folder itself is ROCm CLI's own when this is what creates it. + rocm_core::create_marked_root(&paths.cache_dir)?; fs::create_dir_all(cache_dir)?; let tmp_public_key = body_path.with_extension("public-key.pem"); diff --git a/apps/rocm/src/therock/python.rs b/apps/rocm/src/therock/python.rs index 46f34c8067..4ccb2418a3 100644 --- a/apps/rocm/src/therock/python.rs +++ b/apps/rocm/src/therock/python.rs @@ -115,6 +115,28 @@ fn current_platform_wheel_tags() -> Result> { Ok(vec![platform_tag.to_owned(), "any".to_owned()]) } +/// [`ensure_uv_venv`], marking `install_root` as ROCm CLI's own when this +/// call is what created it. `uv venv` creates the folder, and an SDK +/// `--prefix` becomes the data folder `rocm uninstall` later judges; a folder +/// that already existed is not marked, since ROCm CLI did not make it. +pub(super) fn ensure_marked_uv_venv( + paths: &AppPaths, + uv: &Path, + python_launcher: &Path, + install_root: &Path, +) -> Result<()> { + // Both decided BEFORE `ensure_uv_venv`, which may remove and recreate the + // folder (an incompatible venv is rebuilt) and so lose the marker: a + // folder ROCm CLI created, or one it had already marked, is marked again. + let created = !install_root.exists(); + let was_marked = install_root.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file(); + ensure_uv_venv(paths, uv, python_launcher, install_root)?; + if (created || was_marked) && !install_root.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file() { + rocm_core::mark_root(install_root); + } + Ok(()) +} + pub(super) fn ensure_uv_venv( paths: &AppPaths, uv: &Path, @@ -2910,4 +2932,66 @@ exit 1 } Ok(()) } + + /// The SDK folder `uv venv` creates for an install is marked as ROCm CLI's + /// own; a folder that was already there (here, a stale venv being rebuilt) + /// is not. + #[test] + #[cfg(unix)] + fn a_created_install_root_is_marked_and_an_existing_one_is_not() { + let root = std::env::temp_dir().join(format!( + "rocm-cli-marked-venv-{}-{}", + std::process::id(), + unix_time_millis() + )); + fs::create_dir_all(root.join("data")).unwrap(); + fs::create_dir_all(root.join("cache")).unwrap(); + let root = root.canonicalize().unwrap(); + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: root.join("data"), + cache_dir: root.join("cache"), + }; + let python_launcher = + write_fake_python_reporting(&root, "python3.14", "cp314", "Python 3.14.5").unwrap(); + let uv = write_fake_uv_creating_venv(&root, "uv", "cp314", "Python 3.14.5").unwrap(); + + let fresh = root.join("prefix"); + ensure_marked_uv_venv(&paths, &uv, &python_launcher, &fresh).unwrap(); + let existing = root.join("existing"); + fs::create_dir_all(existing.join("bin")).unwrap(); + write_fake_python_reporting(&existing.join("bin"), "python", "cp312", "Python 3.12.10") + .unwrap(); + ensure_marked_uv_venv(&paths, &uv, &python_launcher, &existing).unwrap(); + + // A stale venv ROCm CLI had already marked is rebuilt (removed and + // recreated) and must keep its marker. + let rebuilt = root.join("rebuilt"); + fs::create_dir_all(rebuilt.join("bin")).unwrap(); + write_fake_python_reporting(&rebuilt.join("bin"), "python", "cp312", "Python 3.12.10") + .unwrap(); + fs::write(rebuilt.join(rocm_core::ROCM_CLI_ROOT_MARKER), b"").unwrap(); + ensure_marked_uv_venv(&paths, &uv, &python_launcher, &rebuilt).unwrap(); + let rebuilt_python = wheel_compatibility_for_python(&venv_python_path(&rebuilt)) + .map(|compat| compat.python_tag); + + let fresh_marked = fresh.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file(); + let existing_marked = existing.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file(); + let rebuilt_marked = rebuilt.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file(); + fs::remove_dir_all(root).ok(); + assert!( + fresh_marked, + "the install folder this install created is not marked" + ); + assert!(!existing_marked, "a folder that already existed was marked"); + assert_eq!( + rebuilt_python.ok().as_deref(), + Some("cp314"), + "the stale venv was not rebuilt, so this case proves nothing" + ); + assert!( + rebuilt_marked, + "rebuilding a marked venv dropped its marker" + ); + } } diff --git a/apps/rocm/src/tool_policy.rs b/apps/rocm/src/tool_policy.rs index 9634985e45..c3fafc9467 100644 --- a/apps/rocm/src/tool_policy.rs +++ b/apps/rocm/src/tool_policy.rs @@ -8,7 +8,7 @@ //! //! `validate_chat_tool_call` and the `validate_chat_*_tool_call` family //! reject malformed or unsafe requests (a CPU or public-bind `serve`, a -//! system install folder, a service id or watcher mode that does not parse); +//! protected install folder, a service id or watcher mode that does not parse); //! `chat_rocm_command_action` and `chat_rocm_command_action_from_args` sort a //! `rocm` argv into a read-only command or one that needs approval //! (`ChatRocmCommandAction`); `chat_tool_approval_request` builds the approval @@ -32,7 +32,7 @@ use crate::services_text::validate_service_id; use crate::shell_quote::has_terminal_control_character; use crate::{providers, therock}; use anyhow::{Context, Result, bail}; -use rocm_core::{DEFAULT_LOCAL_HOST, builtin_watcher, runtime_install_root_is_protected}; +use rocm_core::{DEFAULT_LOCAL_HOST, builtin_watcher}; use std::path::Path; #[derive(Debug, Clone, Eq, PartialEq)] @@ -354,9 +354,9 @@ fn validate_chat_install_sdk_tool_call(call: &providers::ChatToolCall) -> Result ); }; let prefix_path = Path::new(&prefix); - if chat_install_prefix_is_system(prefix_path) { + if let Some(why) = chat_install_prefix_protection(prefix_path) { bail!( - "local assistant cannot request system install folder `{}`", + "local assistant cannot request install folder `{}`: it is {why}", prefix_path.display() ); } @@ -945,9 +945,9 @@ pub(crate) fn validate_chat_rocm_command_safety(args: &[String]) -> Result<()> { ); }; let prefix_path = Path::new(prefix); - if chat_install_prefix_is_system(prefix_path) { + if let Some(why) = chat_install_prefix_protection(prefix_path) { bail!( - "local assistant cannot request system install folder `{}`", + "local assistant cannot request install folder `{}`: it is {why}", prefix_path.display() ); } @@ -955,8 +955,20 @@ pub(crate) fn validate_chat_rocm_command_safety(args: &[String]) -> Result<()> { Ok(()) } -pub(crate) fn chat_install_prefix_is_system(prefix: &Path) -> bool { - prefix.as_os_str().is_empty() || runtime_install_root_is_protected(prefix) +// Only the unix-only respelling test calls this. +#[cfg(all(test, unix))] +fn chat_install_prefix_is_system(prefix: &Path) -> bool { + chat_install_prefix_protection(prefix).is_some() +} + +/// Why the local assistant may not install into `prefix`, if it may not: the +/// same protected-location rule every recursive delete uses, since an install +/// folder is one a later uninstall or a broken-venv rebuild may remove. +pub(crate) fn chat_install_prefix_protection(prefix: &Path) -> Option<&'static str> { + if prefix.as_os_str().is_empty() { + return Some("an empty path"); + } + rocm_core::runtime_protected_location(prefix).map(rocm_core::ProtectedLocation::describe) } pub(crate) fn chat_tool_call_is_read_only(call: &providers::ChatToolCall) -> bool { @@ -2525,7 +2537,7 @@ mod tests { serde_json::json!({ "prefix": if cfg!(windows) { "C:\\Windows\\rocm" } else { "/opt/rocm" } }), - "system install folder", + "cannot request install folder", ), ( serde_json::json!({ diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index 28007a0c46..8f3f713a0f 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -12,6 +12,9 @@ //! - removing the fish completion script the Linux installer recorded writing, //! when it is still the installer's own file; //! - deleting the running `rocm.exe` on Windows, which cannot unlink itself. +//! +//! [`apply_uninstall_plan`] lives here too: it is the one step that deletes, +//! and it refuses a plan with a protected root on its own. use std::ffi::OsString; use std::fmt::Write as _; @@ -20,11 +23,12 @@ use std::io::Write as _; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; -use rocm_core::{AppPaths, interactive_terminal, require_yes_or_interactive}; +use rocm_core::{AppPaths, interactive_terminal}; use crate::uninstall_plan::{ - PlanAudience, UninstallOptions, UninstallPlan, UninstallPlanEntry, build_uninstall_plan, - confirm_uninstall, is_rocm_install_entry_name, remove_path, render_uninstall_plan, + PlanAudience, PlannedAs, UninstallOptions, UninstallPlan, UninstallPlanEntry, + build_uninstall_plan, confirm_uninstall, entry_path, is_rocm_install_entry_name, remove_path, + render_uninstall_plan, }; /// The file, next to the installed binaries, in which `install.sh` and @@ -81,8 +85,8 @@ pub(crate) fn reject_force(force: bool) -> Result<()> { } pub(crate) fn uninstall(options: UninstallOptions) -> Result<()> { - let paths = AppPaths::discover()?; - let plan = build_uninstall_plan(&paths, &options)?; + let (paths, sources) = AppPaths::discover_with_sources()?; + let plan = build_uninstall_plan(&paths, &sources, &options)?; print!( "{}", render_uninstall_plan( @@ -91,26 +95,61 @@ pub(crate) fn uninstall(options: UninstallOptions) -> Result<()> { PlanAudience::for_command(interactive_terminal()) ) ); + run_uninstall_plan(&plan, &options, interactive_terminal, confirm_uninstall) +} + +/// Everything after the review is printed: refuse, preview, confirm, remove. +/// +/// How to tell whether the terminal is interactive and how to ask are passed +/// in, so tests can prove the refusal comes before the prompt rather than only +/// before the first removal. +pub(crate) fn run_uninstall_plan( + plan: &UninstallPlan, + options: &UninstallOptions, + interactive: impl FnOnce() -> bool, + confirm: impl FnOnce() -> Result, +) -> Result<()> { + // A refused root stops the whole command, before the prompt and before the + // first removal: removing the rest and then failing would leave a partial + // uninstall behind a folder that was never going to be removed. A dry run + // fails too, so `rocm uninstall --dry-run && rocm uninstall --yes` cannot + // read a refusal as a go-ahead; its review above already carries the advice. + if let Some(error) = plan.refusal_error() { + if options.dry_run { + bail!("uninstall would be refused; see the review above"); + } + bail!(error); + } - if plan_is_empty(&plan) || options.dry_run { + if plan_is_empty(plan) || options.dry_run { return Ok(()); } - let already_approved = require_yes_or_interactive(options.yes, "uninstall")?; - if !already_approved && !confirm_uninstall()? { + let already_approved = + rocm_core::require_yes_or_interactive_with(options.yes, "uninstall", interactive)?; + if !already_approved && !confirm()? { println!("uninstall cancelled"); return Ok(()); } - execute_plan(&plan, &mut |line| println!("{line}"))?; + apply_uninstall_plan(plan)?; println!("uninstall complete"); Ok(()) } +/// Remove everything `plan` lists, reporting each step as it happens. +/// +/// Refuses again on its own, so no caller can reach a removal with a protected +/// root in the plan, whatever it checked first. +pub(crate) fn apply_uninstall_plan(plan: &UninstallPlan) -> Result<()> { + execute_plan(plan, &mut |line| println!("{line}")) +} + /// Carry out `plan`, handing `report` a line for each step as soon as it is /// done, so a failure partway still leaves the user told what already changed. /// -/// The PATH changes are undone first, so a change that cannot be undone stops +/// A plan with a refused root is refused here before anything changes. The +/// PATH changes are undone first, so a change that cannot be undone stops /// the uninstall before anything is removed: `rocm`, the user's settings, and /// the record of the change are all still there to retry with. Then the /// config, data, and cache go, while `rocm` is still there to retry a failure @@ -118,6 +157,15 @@ pub(crate) fn uninstall(options: UninstallOptions) -> Result<()> { /// A fish completion script that cannot be removed is reported as a warning /// and the rest goes on. fn execute_plan(plan: &UninstallPlan, report: &mut dyn FnMut(String)) -> Result<()> { + if let Some(error) = plan.refusal_error() { + bail!(error); + } + // Every entry is checked once before anything changes, so one that moved + // since the review stops the uninstall with the PATH change still in place, + // and again right before its own removal below. + for entry in &plan.actions { + recheck(entry)?; + } for edit in &plan.path_edits { match apply_path_edit(edit) { Ok(line) => report(line), @@ -133,33 +181,43 @@ fn execute_plan(plan: &UninstallPlan, report: &mut dyn FnMut(String)) -> Result< let non_binaries = plan.actions.iter().filter(|entry| !is_binary(entry.kind)); let binaries = plan.actions.iter().filter(|entry| is_binary(entry.kind)); for entry in non_binaries.chain(binaries) { - // The review may have sat at a prompt, so a completion script is - // looked at again: only the regular file that was planned is removed. - if entry.kind == SHELL_COMPLETIONS_KIND && is_not_a_regular_file(&entry.path) { - report(format!( - "warning: left {} {} in place: it is no longer the regular file that was \ - reviewed", - entry.kind, - entry.path.display() - )); - continue; - } - match remove_path(&entry.path) { - Ok(()) => report(format!("removed {} {}", entry.kind, entry.path.display())), - // Completions are best effort when installed, so a script that - // cannot be removed does not stop the uninstall either. - Err(error) if entry.kind == SHELL_COMPLETIONS_KIND => report(format!( - "warning: could not remove {} {}: {error:#}\n \ - The uninstall went on without it; delete that file yourself so fish \ - stops completing rocm.", - entry.kind, - entry.path.display() - )), - Err(error) => { - return Err(error) - .with_context(|| format!("failed to remove {}", entry.path.display())); + // A fish completion script keeps its own, softer check: the review may + // have sat at a prompt, so it is looked at again, only the regular file + // that was planned is removed, and a failure is a warning, not a stop. + if entry.kind == SHELL_COMPLETIONS_KIND { + if is_not_a_regular_file(&entry.path) { + report(format!( + "warning: left {} {} in place: it is no longer the regular file that was \ + reviewed", + entry.kind, + entry.path.display() + )); + continue; + } + match remove_path(&entry.path) { + Ok(()) => report(format!("removed {} {}", entry.kind, entry.path.display())), + // Completions are best effort when installed, so a script that + // cannot be removed does not stop the uninstall either. + Err(error) => report(format!( + "warning: could not remove {} {}: {error:#}\n \ + The uninstall went on without it; delete that file yourself so fish \ + stops completing rocm.", + entry.kind, + entry.path.display() + )), } + continue; } + let Some(target) = recheck(entry)? else { + // Already gone, as for a cache folder inside a data folder removed + // just before it: the review listed it and it is gone, so it is + // reported like every other entry rather than left unaccounted for. + report(format!("removed {} {}", entry.kind, entry.path.display())); + continue; + }; + remove_path(&target) + .with_context(|| format!("failed to remove {}", entry.path.display()))?; + report(format!("removed {} {}", entry.kind, entry.path.display())); } if let Some(record) = &plan.path_record { remove_path(record).with_context(|| format!("failed to remove {}", record.display()))?; @@ -172,6 +230,95 @@ fn execute_plan(plan: &UninstallPlan, report: &mut dyn FnMut(String)) -> Result< Ok(()) } +/// Check `entry` again against what the review saw, and return what to +/// remove: `None` when it is already gone (for example inside a folder removed +/// earlier in the plan). +/// +/// Check, then act on what was checked. The review judged where a real +/// directory resolved to when it was made; a parent swapped for a +/// symlink while the prompt was open would point the same spelling at +/// a different folder. Resolve again, refuse if it moved, and remove +/// the resolved location rather than re-walking the spelling. +fn recheck(entry: &UninstallPlanEntry) -> Result> { + let target = match &entry.planned { + PlannedAs::Unchecked => entry.path.clone(), + PlannedAs::Dir(planned) => match rocm_core::canonicalize_for_compare(&entry.path) { + Ok(now) if &now == planned => now, + Ok(now) => bail!( + "stopped before removing the {} folder {}: it now resolves to {}, not {} as \ + the review showed. Anything reported as removed above is gone; nothing \ + after it was touched. Check the folder and run the uninstall again.", + entry.kind, + entry.path.display(), + now.display(), + planned.display() + ), + // Already gone, e.g. inside a folder removed earlier in the plan. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(error).with_context(|| { + format!( + "failed to resolve {} before removing it", + entry.path.display() + ) + }); + } + }, + // A link or file is unlinked, never walked — unless it has turned + // into something else since the review: a link replaced by a real + // folder would otherwise be removed recursively, unreviewed. + PlannedAs::Link { parent } | PlannedAs::File { parent } => { + let was_link = matches!(entry.planned, PlannedAs::Link { .. }); + let spelled = entry_path(&entry.path); + let now = match std::fs::symlink_metadata(&spelled) { + Ok(now) => now, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(error).with_context(|| { + format!("failed to check {} before removing it", spelled.display()) + }); + } + }; + let unchanged = if was_link { + now.file_type().is_symlink() + } else { + now.is_file() + }; + if !unchanged { + bail!( + "stopped before removing the {} {}: it was a {} when reviewed and is \ + not one now. Anything reported as removed above is gone; nothing after \ + it was touched. Check it and run the uninstall again.", + entry.kind, + entry.path.display(), + if was_link { "symbolic link" } else { "file" } + ); + } + let parent_now = spelled + .parent() + .map(|p| { + if p.as_os_str().is_empty() { + std::path::Path::new(".") + } else { + p + } + }) + .and_then(|p| rocm_core::canonicalize_for_compare(p).ok()); + if parent.is_some() && &parent_now != parent { + bail!( + "stopped before removing the {} {}: the folder holding it now resolves \ + somewhere else than the review showed. Anything reported as removed \ + above is gone; nothing after it was touched.", + entry.kind, + entry.path.display() + ); + } + spelled + } + }; + Ok(Some(target)) +} + pub(crate) const fn plan_is_empty(plan: &UninstallPlan) -> bool { plan.actions.is_empty() && plan.path_edits.is_empty() @@ -454,6 +601,8 @@ fn plan_completion_removals_with( plan.actions.push(UninstallPlanEntry { kind: SHELL_COMPLETIONS_KIND, path, + // Re-checked by its own rule in `execute_plan`. + planned: PlannedAs::Unchecked, }); } Ok(Some(owner)) => plan.skipped.push(format!( @@ -1130,6 +1279,7 @@ mod tests { .map(|path| crate::uninstall_plan::UninstallPlanEntry { kind: "binary", path: path.clone(), + planned: crate::uninstall_plan::PlannedAs::Unchecked, }) .collect(); plan @@ -1149,11 +1299,131 @@ mod tests { crate::uninstall_plan::UninstallPlanEntry { kind: "config", path: config.clone(), + planned: crate::uninstall_plan::PlannedAs::Unchecked, }, ); Ok((plan, config)) } + /// A planned folder that an earlier step already removed — the cache + /// folder inside the data folder, when only the data folder is set — + /// is reported as removed like the rest, so the report accounts for + /// every entry the review listed. + #[test] + fn an_entry_removed_with_an_earlier_one_is_still_reported() -> Result<()> { + let layout = layout()?; + let data = layout.home.join(".rocm").join("data"); + let cache = data.join("cache"); + fs::create_dir_all(&cache)?; + let dir = |kind, path: &Path| -> Result { + Ok(crate::uninstall_plan::UninstallPlanEntry { + kind, + path: path.to_path_buf(), + planned: PlannedAs::Dir(rocm_core::canonicalize_for_compare(path)?), + }) + }; + let plan = UninstallPlan { + actions: vec![dir("data", &data)?, dir("cache", &cache)?], + ..UninstallPlan::default() + }; + + let (lines, result) = run(&plan); + result?; + assert_eq!( + lines, + vec![ + format!("removed data {}", data.display()), + format!("removed cache {}", cache.display()), + ] + ); + assert!(!data.exists()); + Ok(()) + } + + /// A refused root stops the uninstall before the installer's PATH + /// change is undone, not only before the first removal: "nothing was + /// removed" covers the shell profile too. + #[test] + fn a_refused_plan_leaves_the_path_change_in_place() -> Result<()> { + let layout = layout()?; + let profile = layout.home.join(".bashrc"); + let contents = format!("export A=1\n{POSIX_BLOCK}"); + fs::write(&profile, &contents)?; + let record = record(&layout, &format!("profile {}\n", profile.display()))?; + let mut plan = with_binaries(&layout, plan_for(&layout)); + assert!(!plan.path_edits.is_empty(), "{plan:?}"); + // A fish completion script the installer wrote, planned for + // removal: the refusal keeps it too, despite its softer rule. + let fish = layout.home.join("completions").join("rocm.fish"); + fs::create_dir_all(fish.parent().expect("parent"))?; + fs::write(&fish, "# rocm-cli fish completions for x\n")?; + plan.actions.insert( + 0, + crate::uninstall_plan::UninstallPlanEntry { + kind: SHELL_COMPLETIONS_KIND, + path: fish.clone(), + planned: PlannedAs::Unchecked, + }, + ); + plan.refused.push(crate::uninstall_plan::RefusedRoot { + kind: "data", + path: layout.home.clone(), + resolved: None, + real: None, + why: rocm_core::ProtectedLocation::Home, + source: rocm_core::AppPathSource::Default, + }); + + let (lines, result) = run(&plan); + let error = format!("{:#}", result.expect_err("a refused plan must fail")); + assert!(error.contains("nothing was removed"), "{error}"); + assert!(lines.is_empty(), "nothing may be reported: {lines:?}"); + assert_eq!(fs::read_to_string(&profile)?, contents); + assert!(record.exists() && layout.removed.iter().all(|path| path.exists())); + assert!( + fish.is_file(), + "a refused plan removed the fish completions" + ); + Ok(()) + } + + /// A binary that is no longer what the review saw stops the uninstall + /// before anything changes, PATH change included: the entries are all + /// checked once before the first step, with the resolver the plan was + /// built with. + #[test] + fn a_binary_that_became_a_folder_stops_before_the_path_change() -> Result<()> { + let layout = layout()?; + let profile = layout.home.join(".bashrc"); + let contents = format!("export A=1\n{POSIX_BLOCK}"); + fs::write(&profile, &contents)?; + record(&layout, &format!("profile {}\n", profile.display()))?; + let mut plan = UninstallPlan::default(); + crate::uninstall_plan::plan_installed_binaries( + &mut plan, + &UninstallOptions::default(), + || Ok(layout.removed[0].clone()), + Some(&layout.home), + &rocm_core::canonicalize_for_compare, + )?; + assert!(!plan.path_edits.is_empty(), "{plan:?}"); + let swapped = &layout.removed[1]; + fs::remove_file(swapped)?; + fs::create_dir(swapped)?; + fs::write(swapped.join("keep.txt"), "user data")?; + + let (lines, result) = run(&plan); + let error = format!("{:#}", result.expect_err("a changed binary must stop")); + assert!( + error.contains("stopped before removing the binary"), + "{error}" + ); + assert!(lines.is_empty(), "nothing may be reported: {lines:?}"); + assert_eq!(fs::read_to_string(&profile)?, contents); + assert!(swapped.join("keep.txt").is_file() && layout.removed[0].is_file()); + Ok(()) + } + #[test] fn a_recorded_profile_block_is_undone_and_the_record_goes_last() -> Result<()> { let layout = layout()?; @@ -1228,6 +1498,7 @@ mod tests { .push(crate::uninstall_plan::UninstallPlanEntry { kind: "binary", path: layout.bin.join("x".repeat(300)), + planned: crate::uninstall_plan::PlannedAs::Unchecked, }); let (lines, result) = run(&plan); @@ -1484,6 +1755,7 @@ mod tests { &options, || Ok(layout.removed[0].clone()), Some(&layout.home), + &rocm_core::canonicalize_for_compare, )?; Ok(plan) }; @@ -1969,6 +2241,7 @@ mod tests { crate::uninstall_plan::UninstallPlanEntry { kind: SHELL_COMPLETIONS_KIND, path: stuck.clone(), + planned: PlannedAs::Unchecked, }, ); diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index c350ae86e9..c319c9bcb0 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -5,8 +5,9 @@ //! The uninstall plan: what would be removed, how that plan is rendered for //! review, and the filesystem-removal primitive used to carry it out. //! -//! Mechanically relocated from `main.rs` with no behavior change — Phase 6f -//! (ROCMAI-212) of the `main.rs` modularization (see `docs/architecture.md`). +//! First relocated mechanically from `main.rs` — Phase 6f (ROCMAI-212) of +//! the `main.rs` modularization (see `docs/architecture.md`); the +//! protected-root judgment described at the end was added here afterwards. //! `dispatch()`'s call sites are unaffected: none of this module's functions //! are called directly from `dispatch()`. //! @@ -21,18 +22,19 @@ //! describe the `uninstall` command's own, exclusive logic. //! //! This module owns: the plan types (`UninstallOptions`, `UninstallPlan`, -//! `UninstallPlanEntry`), the `PlanAudience` a rendered plan is written for -//! (a person at a terminal, a captured caller, or the assistant's preview), -//! which decides what the dry-run footer says comes next, building the plan (`build_uninstall_plan`, +//! `UninstallPlanEntry`, `PlannedAs`, `RefusedRoot`), the `PlanAudience` a +//! rendered plan is written for (a person at a terminal, a captured caller, or +//! the assistant's preview), which decides what the dry-run footer says comes +//! next, building the plan (`build_uninstall_plan`, `build_uninstall_plan_for_home`, //! `plan_installed_binaries`, and the installed-binary/shared-cache //! discovery helpers behind them), rendering it (`render_uninstall_dry_run`, //! `render_uninstall_plan`), the `[y/N]` confirmation prompt //! (`confirm_uninstall`), and the filesystem removal primitive both //! `uninstall.rs` and `storage.rs` call to carry a plan out (`remove_path`, //! and the entry-resolution helpers behind it). `uninstall.rs` calls into it -//! for `PlanAudience`/`UninstallOptions`/`UninstallPlan`/`build_uninstall_plan`/ -//! `confirm_uninstall`/`is_rocm_install_entry_name`/`remove_path`/ -//! `render_uninstall_plan`; `storage.rs` calls into it for +//! for `PlanAudience`/`UninstallOptions`/`UninstallPlan`/`UninstallPlanEntry`/ +//! `PlannedAs`/`build_uninstall_plan`/`confirm_uninstall`/`entry_path`/ +//! `is_rocm_install_entry_name`/`remove_path`/`render_uninstall_plan`; `storage.rs` calls into it for //! `UninstallPlan`/`UninstallPlanEntry`/`confirm_uninstall`; `runtimes_cmd.rs` //! calls into it for `confirm_uninstall` (the same `[y/N]` prompt, reused for //! `rocm runtimes uninstall`); `chat/mcp_bridge.rs` calls into it for @@ -40,8 +42,15 @@ //! result, which renders for `PlanAudience::Assistant` itself and so does not //! import the type); `deletion_properties.rs`'s recursive-deletion property //! tests call into it for `PlanAudience` (the `uninstall_case` property renders -//! as `Captured`)/`UninstallOptions`/`build_uninstall_plan`/`remove_path`/ -//! `render_uninstall_plan`. +//! as `Captured`)/`UninstallOptions`/`build_uninstall_plan`/ +//! `build_uninstall_plan_for_home`/`SharedCache`/`shared_cache_notes_for`/ +//! `remove_path`/`render_uninstall_plan`. +//! +//! Building the plan also judges each config, data and cache root against the +//! protected locations (`judge_uninstall_root`), so a refused root lands in +//! `UninstallPlan::refused` with the advice that clears it, and records what +//! each planned entry was (`PlannedAs`) so `uninstall.rs` can check it again +//! right before removing it (with `entry_path`). use std::fmt::Write as _; use std::fs; @@ -69,11 +78,141 @@ pub(crate) struct UninstallOptions { pub(crate) struct UninstallPlanEntry { pub(crate) kind: &'static str, pub(crate) path: PathBuf, + /// What the entry was when the review was made, checked again right + /// before it is removed. + pub(crate) planned: PlannedAs, +} + +/// What a planned entry was at review time. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum PlannedAs { + /// A real directory, and where it really was. + Dir(PathBuf), + /// A symbolic link, and where the folder holding it really was. + Link { parent: Option }, + /// A file, and where the folder holding it really was. + File { parent: Option }, + /// Not re-checked (`rocm storage remove-downloads` entries, which have + /// their own removal loop). + Unchecked, +} + +impl PlannedAs { + /// A non-directory entry as it is now, with its folder resolved. + pub(crate) fn non_dir( + path: &Path, + metadata: &fs::Metadata, + canonicalize: Canonicalize<'_>, + ) -> Self { + let parent = path + .parent() + .map(|parent| { + if parent.as_os_str().is_empty() { + Path::new(".") + } else { + parent + } + }) + .and_then(|parent| canonicalize(parent).ok()); + if metadata.file_type().is_symlink() { + Self::Link { parent } + } else { + Self::File { parent } + } + } +} + +/// A config/data/cache root `rocm uninstall` will not remove, and why. +#[derive(Debug, Clone)] +pub(crate) struct RefusedRoot { + pub(crate) kind: &'static str, + pub(crate) path: PathBuf, + /// Where `path` really is, when only that (not its spelling) is protected: + /// `.` run from home, or home reached through a symlinked parent. + pub(crate) resolved: Option, + /// The resolved location whether or not it differs from `path`; where the + /// marker would go for [`rocm_core::ProtectedLocation::NotMarked`]. + pub(crate) real: Option, + pub(crate) why: rocm_core::ProtectedLocation, + pub(crate) source: rocm_core::AppPathSource, +} + +impl RefusedRoot { + /// What would clear this refusal, as one sentence. Every way named here is + /// one the tests follow: `--keep-` leaves the root out of the plan; + /// pointing the environment variable elsewhere moves it; creating the + /// marker in a folder that is ROCm CLI's makes it removable. For a root + /// that came from `setup.therock_venv` the flag comes first and moving the + /// setting is advised against: the ROCm SDK is installed in that folder, + /// and repointing the setting would leave it there, unknown to ROCm CLI. + pub(crate) fn advice(&self) -> String { + let keep = format!("re-run with --keep-{} to leave it in place", self.kind); + let mut ways = Vec::new(); + if let rocm_core::AppPathSource::Env(var) = &self.source { + ways.push(format!("point {var} at a folder of ROCm CLI's own")); + } + if self.why == rocm_core::ProtectedLocation::NotMarked { + let real = self.real.as_deref().unwrap_or(&self.path); + ways.push(format!( + "if this folder belongs to ROCm CLI, create {}", + real.join(rocm_core::ROCM_CLI_ROOT_MARKER).display() + )); + } + let therock = matches!(self.source, rocm_core::AppPathSource::TheRockVenv(_)); + if therock { + ways.insert(0, keep); + } else { + ways.push(keep); + } + let mut sentence = ways.join(", or "); + if let Some(first) = sentence.get(..1) { + sentence.replace_range(..1, &first.to_uppercase()); + } + sentence.push('.'); + if therock { + sentence.push_str( + " Moving setup.therock_venv instead would orphan the ROCm SDK installed there.", + ); + } + match self.why { + rocm_core::ProtectedLocation::NotMarked => sentence.push_str( + " Folders created by ROCm CLI releases before this one carry no marker; a \ + config.json or runtime registry inside it is not taken as proof that it is \ + ROCm CLI's.", + ), + rocm_core::ProtectedLocation::SharedTopLevel + | rocm_core::ProtectedLocation::OtherUsersHome + | rocm_core::ProtectedLocation::System => sentence.push_str( + " ROCm CLI never removes this folder itself; if you are sure what in it is \ + ROCm CLI's, remove those files by hand.", + ), + _ => {} + } + sentence + } + + /// ` is ([; resolves to ])`. + pub(crate) fn describe(&self) -> String { + let resolved = self + .resolved + .as_ref() + .map(|resolved| format!("; resolves to {}", resolved.display())) + .unwrap_or_default(); + format!( + "{} is {} ({}{resolved})", + self.path.display(), + self.why.describe(), + self.source.describe() + ) + } } #[derive(Debug, Clone, Default)] pub(crate) struct UninstallPlan { pub(crate) actions: Vec, + /// Roots the plan would otherwise remove but that sit in a protected + /// location. Any entry here refuses the whole uninstall. + pub(crate) refused: Vec, pub(crate) skipped: Vec, pub(crate) warnings: Vec, /// Installer PATH changes `rocm uninstall` undoes. @@ -85,9 +224,194 @@ pub(crate) struct UninstallPlan { pub(crate) self_delete: Option, } +impl UninstallPlan { + /// How to get past a refusal, derived from the refused roots themselves: + /// the setting each one came from, which moves it, and its `--keep-` + /// flag, which is exactly what leaves it out of the plan — so the advice + /// cannot name a flag that does not clear it. + pub(crate) fn refusal_advice(&self) -> Option { + if self.refused.is_empty() { + return None; + } + let per_root = self + .refused + .iter() + .map(|root| { + if self.refused.len() == 1 { + root.advice() + } else { + format!("For the {} folder: {}", root.kind, root.advice()) + } + }) + .collect::>(); + Some(per_root.join(" ")) + } + + /// The error a real (non-dry-run) uninstall stops with when anything was + /// refused. It is raised before the confirmation prompt and before the + /// first removal, which is what makes "nothing was removed" true. + pub(crate) fn refusal_error(&self) -> Option { + let advice = self.refusal_advice()?; + let reasons = self + .refused + .iter() + .map(|root| format!("the {} folder {}", root.kind, root.describe())) + .collect::>() + .join("; "); + Some(format!( + "uninstall refused, nothing was removed: {reasons}, and ROCm CLI never removes \ + such a folder. {advice}" + )) + } +} + +/// How a planned root resolves: where it really is, for display and for the +/// check made again right before removal. +pub(crate) type Canonicalize<'a> = &'a dyn Fn(&Path) -> io::Result; + +/// What `rocm uninstall` does with one config, data or cache root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum RootJudgment { + /// Remove it; `planned` is what it is now, to check again before removal. + Remove { planned: PlannedAs }, + /// Refuse the whole uninstall. `shown` is the resolved location when it + /// differs from the spelling; `real` is the resolved location regardless. + Refuse { + why: rocm_core::ProtectedLocation, + shown: Option, + real: Option, + }, +} + +/// Judge the root `path` by [`rocm_core::uninstall_root_verdict`]: on its +/// spelling first, then — for a real directory, the only kind removed +/// recursively — on where it really is against where home and the system +/// locations really are. `.` run from home, `..` run from `~/proj`, home +/// reached through a symlinked parent (`/home -> var/home`), or `/usr/lib` +/// where `/lib -> usr/lib`, name a protected place without spelling it. +/// A real directory outside the home folder must also carry the marker. +pub(crate) fn judge_uninstall_root( + path: &Path, + metadata: &fs::Metadata, + home: Option<&Path>, + canonicalize: Canonicalize<'_>, +) -> RootJudgment { + use rocm_core::{ProtectedLocation, UninstallRootVerdict}; + if let UninstallRootVerdict::Refused(why) = rocm_core::uninstall_root_verdict(path, home, &[]) + && !(why == ProtectedLocation::OtherUsersHome + && metadata.is_dir() + && resolves_inside_own_home(path, home, canonicalize)) + { + return RootJudgment::Refuse { + why, + shown: None, + real: None, + }; + } + // `symlink_metadata`: a symlinked root is unlinked, never walked, and a + // file is just a file. + if !metadata.is_dir() { + return RootJudgment::Remove { + planned: PlannedAs::non_dir(path, metadata, canonicalize), + }; + } + // A directory that cannot be resolved cannot be judged by where it is, and + // is about to be walked recursively: refuse rather than guess. + let Ok(resolved) = canonicalize(path) else { + return RootJudgment::Refuse { + why: ProtectedLocation::Unresolvable, + shown: None, + real: None, + }; + }; + let resolved_home = home.map(|home| { + canonicalize(home).unwrap_or_else(|_| rocm_core::resolve_path_through_symlinks(home)) + }); + let resolved_system_roots = rocm_core::uninstall_system_roots() + .iter() + .filter_map(|root| canonicalize(root).ok()) + .collect::>(); + let shown = (resolved != path).then(|| resolved.clone()); + let refuse = |why| RootJudgment::Refuse { + why, + shown: shown.clone(), + real: Some(resolved.clone()), + }; + match rocm_core::uninstall_root_verdict( + &resolved, + resolved_home.as_deref(), + &resolved_system_roots, + ) { + UninstallRootVerdict::Refused(why) => refuse(why), + UninstallRootVerdict::NeedsMarker + if !resolved.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file() => + { + refuse(ProtectedLocation::NotMarked) + } + UninstallRootVerdict::Allowed | UninstallRootVerdict::NeedsMarker => RootJudgment::Remove { + planned: PlannedAs::Dir(resolved), + }, + } +} + +/// Whether the real directory `path` really sits inside the user's home, +/// though spelled outside it — on Windows the temp folder is often spelled +/// with the home folder's short 8.3 name (`C:\Users\RUNNER~1\...`), which by +/// spelling alone is someone else's folder under `C:\Users`. Such a root is +/// judged by where it really is instead. +fn resolves_inside_own_home( + path: &Path, + home: Option<&Path>, + canonicalize: Canonicalize<'_>, +) -> bool { + let (Some(home), Ok(resolved)) = (home, canonicalize(path)) else { + return false; + }; + let Ok(resolved_home) = canonicalize(home) else { + return false; + }; + rocm_core::runtime_path_is_same_or_inside(&resolved, &resolved_home) + && !rocm_core::runtime_paths_equivalent(&resolved, &resolved_home) +} + pub(crate) fn build_uninstall_plan( paths: &AppPaths, + sources: &rocm_core::AppPathSources, + options: &UninstallOptions, +) -> Result { + build_uninstall_plan_for_home( + paths, + sources, + options, + rocm_core::runtime_home_dir().as_deref(), + ) +} + +/// [`build_uninstall_plan`] judged against `home` rather than the process's +/// own, so the protected-root check can be tested in a sandbox. +pub(crate) fn build_uninstall_plan_for_home( + paths: &AppPaths, + sources: &rocm_core::AppPathSources, + options: &UninstallOptions, + home: Option<&Path>, +) -> Result { + build_uninstall_plan_with( + paths, + sources, + options, + home, + &rocm_core::canonicalize_for_compare, + ) +} + +/// [`build_uninstall_plan_for_home`] with the resolver passed in, so a test +/// can make a root unresolvable. +pub(crate) fn build_uninstall_plan_with( + paths: &AppPaths, + sources: &rocm_core::AppPathSources, options: &UninstallOptions, + home: Option<&Path>, + canonicalize: Canonicalize<'_>, ) -> Result { let mut plan = UninstallPlan::default(); @@ -95,13 +419,29 @@ pub(crate) fn build_uninstall_plan( &mut plan, options, || daemon_binary_path().context("failed to discover current rocm executable"), - rocm_core::runtime_home_dir().as_deref(), + home, + canonicalize, )?; - for (keep, kind, path) in [ - (options.keep_config, "config", paths.config_dir.clone()), - (options.keep_data, "data", paths.data_dir.clone()), - (options.keep_cache, "cache", paths.cache_dir.clone()), + for (keep, kind, path, source) in [ + ( + options.keep_config, + "config", + paths.config_dir.clone(), + &sources.config, + ), + ( + options.keep_data, + "data", + paths.data_dir.clone(), + &sources.data, + ), + ( + options.keep_cache, + "cache", + paths.cache_dir.clone(), + &sources.cache, + ), ] { if keep { plan.skipped @@ -115,19 +455,33 @@ pub(crate) fn build_uninstall_plan( // A failed check is not an absence either: it fails the plan, so the // uninstall stops before removing anything instead of leaving a folder // that may still be on disk out of the review. - match existing_entry(&path) + let Some((path, metadata)) = existing_entry(&path) .with_context(|| format!("failed to check the {kind} folder {}", path.display()))? - { - Some((entry, _)) => plan.actions.push(UninstallPlanEntry { kind, path: entry }), - None => plan - .skipped - .push(format!("{kind} path not present: {}", path.display())), + else { + plan.skipped + .push(format!("{kind} path not present: {}", path.display())); + continue; + }; + // These roots come from environment variables or `setup.therock_venv`, + // so `/` or the home folder is one typo away. + match judge_uninstall_root(&path, &metadata, home, canonicalize) { + RootJudgment::Refuse { why, shown, real } => plan.refused.push(RefusedRoot { + kind, + path, + resolved: shown, + real, + why, + source: source.clone(), + }), + RootJudgment::Remove { planned } => plan.actions.push(UninstallPlanEntry { + kind, + path, + planned, + }), } } - for note in shared_cache_notes(paths) { - plan.warnings.push(note); - } + plan.warnings.extend(shared_cache_notes(&plan.actions)); let managed_services = load_managed_services(paths).unwrap_or_default(); if !managed_services.is_empty() { @@ -205,6 +559,7 @@ pub(crate) fn plan_installed_binaries( options: &UninstallOptions, current_exe: impl FnOnce() -> Result, home: Option<&Path>, + canonicalize: Canonicalize<'_>, ) -> Result<()> { if options.keep_binaries { // The PATH change and the completions only serve the binaries, so @@ -237,9 +592,13 @@ pub(crate) fn plan_installed_binaries( if path.file_name().and_then(|name| name.to_str()) == Some(uninstall::PATH_EDIT_RECORD) { continue; } + let planned = fs::symlink_metadata(path).map_or(PlannedAs::Unchecked, |meta| { + PlannedAs::non_dir(path, &meta, canonicalize) + }); plan.actions.push(UninstallPlanEntry { kind: "binary", path: path.clone(), + planned, }); } if let Some(bin_dir) = current_exe.parent() { @@ -268,12 +627,43 @@ fn is_running_executable(path: &Path, current_exe: &Path, windows: bool) -> bool })) } -pub(crate) fn render_uninstall_dry_run(paths: &AppPaths) -> Result { +/// The in-process `uninstall --dry-run` the assistant and dashboard run. +/// +/// Honours the same `--keep-*` and `--force-dev-binaries` flags as the real +/// command: a refusal's advice is to re-run with `--keep-`, and a preview +/// that ignored the flag would keep repeating that advice after it was taken. +/// +/// Where each folder came from is derived from `paths` itself +/// ([`rocm_core::AppPathSources::for_paths`]): the source of a folder +/// discovery would pick is discovery's, and a folder it would not pick is +/// reported as pinned — so the source shown can never belong to a different +/// folder than the one judged. +pub(crate) fn render_uninstall_dry_run(paths: &AppPaths, args: &[String]) -> Result { + let sources = rocm_core::AppPathSources::for_paths(paths); + render_uninstall_dry_run_with( + paths, + &sources, + args, + rocm_core::runtime_home_dir().as_deref(), + ) +} + +pub(crate) fn render_uninstall_dry_run_with( + paths: &AppPaths, + sources: &rocm_core::AppPathSources, + args: &[String], + home: Option<&Path>, +) -> Result { let options = UninstallOptions { dry_run: true, + keep_binaries: crate::rocm_argv::chat_cli_has_flag(args, "--keep-binaries"), + keep_config: crate::rocm_argv::chat_cli_has_flag(args, "--keep-config"), + keep_data: crate::rocm_argv::chat_cli_has_flag(args, "--keep-data"), + keep_cache: crate::rocm_argv::chat_cli_has_flag(args, "--keep-cache"), + force_dev_binaries: crate::rocm_argv::chat_cli_has_flag(args, "--force-dev-binaries"), ..UninstallOptions::default() }; - let plan = build_uninstall_plan(paths, &options)?; + let plan = build_uninstall_plan_for_home(paths, sources, &options, home)?; Ok(render_uninstall_plan( &plan, &options, @@ -292,8 +682,9 @@ pub(crate) enum PlanAudience { /// tool). Whatever drives that caller has its own way to proceed, so there /// is no next step to name; "run it again" would address the wrong reader. Captured, - /// The assistant's read-only preview tool: it has no flag to offer, and the - /// removal itself goes through an approval step. + /// The assistant's read-only preview tool: it offers no command to run next, + /// since the removal itself goes through an approval step. (A refused + /// preview still names the `--keep-` flag that clears the refusal.) Assistant, } @@ -342,6 +733,13 @@ pub(crate) fn render_uninstall_plan( } } uninstall::render_extra_plan(&mut output, plan); + if !plan.refused.is_empty() { + let _ = writeln!(output); + let _ = writeln!(output, "Refused (ROCm CLI never removes these folders):"); + } + for root in &plan.refused { + let _ = writeln!(output, " - {}: {}", root.kind, root.describe()); + } if !plan.warnings.is_empty() { let _ = writeln!(output); let _ = writeln!(output, "Please review:"); @@ -356,50 +754,103 @@ pub(crate) fn render_uninstall_plan( for skipped in &plan.skipped { let _ = writeln!(output, " - {skipped}"); } - // An empty plan has nothing to approve, so a dry run says nothing about a next step. - if options.dry_run - && !uninstall::plan_is_empty(plan) - && let Some(footer) = audience.dry_run_footer() - { - let _ = writeln!(output); - let _ = writeln!(output, "{footer}"); + if options.dry_run { + if let Some(advice) = plan.refusal_advice() { + // Whoever reads it, a refused dry run says what clears the refusal + // instead of a next step: there is none until it is cleared. + let _ = writeln!(output); + let _ = writeln!(output, "This uninstall would be refused. {advice}"); + } else if !uninstall::plan_is_empty(plan) + && let Some(footer) = audience.dry_run_footer() + { + // An empty plan has nothing to approve, so a dry run says nothing + // about a next step. + let _ = writeln!(output); + let _ = writeln!(output, "{footer}"); + } } output } -/// Caches that ROCm CLI causes to be filled but does not own, so uninstall -/// leaves them in place. +/// Caches that ROCm CLI causes to be filled but does not own. /// /// These are usually the largest things on disk after an install, so a plan /// that stays silent about them reads as a clean slate it does not deliver. -/// Only paths that exist and sit outside everything already being removed are -/// reported, so the notes stay truthful as caches move under the data -/// directory. -fn shared_cache_notes(paths: &AppPaths) -> Vec { - let removed_roots = [ - paths.config_dir.clone(), - paths.data_dir.clone(), - paths.cache_dir.clone(), - ]; - shared_cache_notes_for(&removed_roots, &shared_cache_candidates()) -} - -/// The pure part of [`shared_cache_notes`], so the filtering is testable without -/// depending on the caller's real environment. -fn shared_cache_notes_for( - removed_roots: &[PathBuf], - candidates: &[(PathBuf, &'static str)], +/// Each one that exists is reported either way: left in place when it sits +/// outside every root being removed, or deleted when it sits inside one — the +/// case where staying silent would be worst, because a root pointed at +/// something like `~/.cache` takes these caches with it. +fn shared_cache_notes(planned: &[UninstallPlanEntry]) -> Vec { + shared_cache_notes_for(planned, &shared_cache_candidates()) +} + +/// A shared cache, named the two ways a plan may need to talk about it. +pub(crate) struct SharedCache { + pub(crate) path: PathBuf, + /// Leads the "left in place" note, which ends "... not removed: ". + pub(crate) kept: &'static str, + /// What the cache is, for the "will be deleted" warning. + pub(crate) name: &'static str, + /// Why losing it matters, as a sentence. + pub(crate) loss: &'static str, + /// `it` or `them`, to agree with `name`. + pub(crate) pronoun: &'static str, +} + +/// The pure part of [`shared_cache_notes`], so the classification is testable +/// without depending on the caller's real environment. +/// +/// A planned root only takes a cache with it when it is a real directory: a +/// root that is a symlink is unlinked, never followed, so what sits behind it +/// survives. Containment is judged on resolved paths when both resolve, so a +/// cache reached through a linked ancestor is still recognised as inside. +pub(crate) fn shared_cache_notes_for( + planned: &[UninstallPlanEntry], + candidates: &[SharedCache], ) -> Vec { - candidates + let removed_dirs: Vec<&UninstallPlanEntry> = planned .iter() - .filter(|(path, _)| path.exists()) - .filter(|(path, _)| !removed_roots.iter().any(|root| path.starts_with(root))) - .map(|(path, description)| format!("{description} not removed: {}", path.display())) - .collect() + // `symlink_metadata` reports a symlink as not a directory. + .filter(|entry| fs::symlink_metadata(&entry.path).is_ok_and(|metadata| metadata.is_dir())) + .collect(); + let inside = |cache: &Path, root: &Path| match (cache.canonicalize(), root.canonicalize()) { + (Ok(cache), Ok(root)) => cache.starts_with(root), + _ => cache.starts_with(root), + }; + + let mut deleted = Vec::new(); + let mut kept = Vec::new(); + for cache in candidates.iter().filter(|cache| cache.path.exists()) { + if let Some(root) = removed_dirs + .iter() + .find(|root| inside(&cache.path, &root.path)) + { + deleted.push(format!( + "{} WILL BE DELETED: {} is inside the {} folder being removed ({}). {} \ + Re-run with --keep-{} to keep {}.", + cache.name, + cache.path.display(), + root.kind, + root.path.display(), + cache.loss, + root.kind, + cache.pronoun, + )); + } else { + kept.push(format!( + "{} not removed: {}", + cache.kept, + cache.path.display() + )); + } + } + // Deletions first: they are the notes a reader must not skim past. + deleted.extend(kept); + deleted } -/// The shared caches worth reporting, with why each is left alone. -fn shared_cache_candidates() -> Vec<(PathBuf, &'static str)> { +/// The shared caches worth reporting, with why each matters. +fn shared_cache_candidates() -> Vec { let mut candidates = Vec::new(); // `uv` writes to `UV_CACHE_DIR` when set, otherwise its own default. Read it @@ -408,10 +859,13 @@ fn shared_cache_candidates() -> Vec<(PathBuf, &'static str)> { let uv_cache = env_path("UV_CACHE_DIR") .or_else(|| rocm_core::runtime_home_dir().map(|home| home.join(".cache").join("uv"))); if let Some(path) = uv_cache { - candidates.push(( + candidates.push(SharedCache { path, - "the uv package cache is shared with other uv projects on this computer and is", - )); + kept: "the uv package cache is shared with other uv projects on this computer and is", + name: "the uv package cache", + loss: "It is shared with other uv projects on this computer.", + pronoun: "it", + }); } let hf_cache = env_path("HF_HOME") @@ -422,10 +876,13 @@ fn shared_cache_candidates() -> Vec<(PathBuf, &'static str)> { .map(|home| home.join(".cache").join("huggingface").join("hub")) }); if let Some(path) = hf_cache { - candidates.push(( + candidates.push(SharedCache { path, - "downloaded model files are slow to fetch again and may include your own, so they are", - )); + kept: "downloaded model files are slow to fetch again and may include your own, so they are", + name: "downloaded model files", + loss: "They are slow to fetch again and may include your own.", + pronoun: "them", + }); } candidates @@ -504,7 +961,7 @@ fn is_dev_binary_layout(path: &Path) -> bool { /// components drops exactly those spellings (plus repeated separators and /// interior `.`), none of which otherwise change which entry is named. `..` is /// kept: dropping it lexically would change the meaning through a link. -fn entry_path(path: &Path) -> PathBuf { +pub(crate) fn entry_path(path: &Path) -> PathBuf { path.components().collect() } @@ -580,7 +1037,8 @@ pub(crate) fn remove_path(path: &Path) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use crate::tests::test_paths; + use crate::tests::{ScopedTestEnv, test_paths}; + use serde_json::json; fn plan_with_a_binary() -> UninstallPlan { UninstallPlan { @@ -653,7 +1111,7 @@ mod tests { } } - /// The assistant's preview has no flag to offer, so it must not point at a + /// The assistant's preview has no command line to offer, so it must not point at a /// command line it cannot run; what it can truthfully say is that removal /// needs approval (`lifecycle_read_mutate_split_is_honest` in `tool_policy.rs` pins /// that its own `uninstall` is an approval action). It does not say "these @@ -671,27 +1129,114 @@ mod tests { assert!(!output.contains("these items"), "{output}"); } - /// A cache that has moved inside a directory uninstall already removes must - /// not be reported as "not removed" — the note would be false. + fn test_shared_cache(path: PathBuf) -> super::SharedCache { + super::SharedCache { + path, + kept: "the uv package cache is shared with other uv projects on this computer and is", + name: "the uv package cache", + loss: "It is shared with other uv projects on this computer.", + pronoun: "it", + } + } + + fn planned_root(kind: &'static str, path: PathBuf) -> super::UninstallPlanEntry { + super::UninstallPlanEntry { + kind, + path, + planned: super::PlannedAs::Unchecked, + } + } + + /// A shared cache inside a root uninstall removes is deleted with it, so the + /// plan must say so — loudly, with the flag that keeps it — rather than + /// drop the note it would otherwise print. This is the `~/.cache` case: + /// the warning used to vanish exactly when the cache was about to go. #[test] - fn shared_cache_notes_skip_paths_already_being_removed() { + fn shared_cache_inside_a_removed_root_is_reported_as_deleted() { let root = std::env::temp_dir().join(format!("rocm-shared-cache-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); - let data = root.join("data"); - let inside = data.join("uv-cache"); + let cache = root.join("dot-cache"); + let inside = cache.join("uv"); std::fs::create_dir_all(&inside).unwrap(); - let notes = shared_cache_notes_for( - &[root.join("config"), data, root.join("cache")], - &[(inside, "the uv package cache")], + let notes = super::shared_cache_notes_for( + &[planned_root("cache", cache.clone())], + &[test_shared_cache(inside.clone())], ); + let _ = std::fs::remove_dir_all(&root); + + assert_eq!(notes.len(), 1, "{notes:?}"); + let note = ¬es[0]; + assert!(note.contains("WILL BE DELETED"), "{note}"); + assert!(note.contains(&inside.display().to_string()), "{note}"); + assert!(note.contains(&cache.display().to_string()), "{note}"); + // The advice is checked against the plan in + // `uninstall_keep_flag_named_by_the_shared_cache_warning_keeps_it`. + assert!(note.contains("--keep-cache"), "{note}"); + } + + /// The flag the warning names really keeps the cache: with it, the root + /// leaves the plan and the same cache is reported as left in place. + #[test] + fn uninstall_keep_flag_named_by_the_shared_cache_warning_keeps_it() { + let root = std::env::temp_dir().join(format!("rocm-shared-keep-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: root.join("data"), + cache_dir: root.join("dot-cache"), + }; + let inside = paths.cache_dir.join("uv"); + std::fs::create_dir_all(&inside).unwrap(); + let options = super::UninstallOptions { + keep_binaries: true, + keep_cache: true, + ..super::UninstallOptions::default() + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &options, + None, + ) + .unwrap(); + let notes = super::shared_cache_notes_for(&plan.actions, &[test_shared_cache(inside)]); + let _ = std::fs::remove_dir_all(&root); assert!( - notes.is_empty(), - "a cache inside a removed directory must not be reported: {notes:?}" + plan.actions.iter().all(|entry| entry.kind != "cache"), + "{plan:?}" ); + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].contains("not removed"), "{notes:?}"); + } + + /// A root that is a symlink is unlinked, never followed, so a cache behind + /// it survives and must not be reported as deleted. + #[test] + #[cfg(unix)] + fn shared_cache_behind_a_linked_root_is_not_reported_as_deleted() { + let root = std::env::temp_dir().join(format!("rocm-shared-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let real = root.join("real-cache"); + let inside = real.join("uv"); + std::fs::create_dir_all(&inside).unwrap(); + let link = root.join("cache-link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let notes = super::shared_cache_notes_for( + &[planned_root("cache", link)], + &[test_shared_cache(link_join_uv(&root))], + ); let _ = std::fs::remove_dir_all(&root); + + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].contains("not removed"), "{notes:?}"); + } + + #[cfg(unix)] + fn link_join_uv(root: &Path) -> PathBuf { + root.join("cache-link").join("uv") } /// A cache that exists outside everything being removed is reported, with @@ -702,10 +1247,11 @@ mod tests { let _ = std::fs::remove_dir_all(&root); let outside = root.join("elsewhere").join("uv"); std::fs::create_dir_all(&outside).unwrap(); + std::fs::create_dir_all(root.join("data")).unwrap(); - let notes = shared_cache_notes_for( - &[root.join("data")], - &[(outside.clone(), "the uv package cache")], + let notes = super::shared_cache_notes_for( + &[planned_root("data", root.join("data"))], + &[test_shared_cache(outside.clone())], ); assert_eq!(notes.len(), 1, "{notes:?}"); @@ -722,13 +1268,1078 @@ mod tests { #[test] fn shared_cache_notes_ignore_missing_paths() { let missing = std::env::temp_dir().join("rocm-definitely-not-here-12345"); - let notes = shared_cache_notes_for( - &[std::env::temp_dir()], - &[(missing, "the uv package cache")], + let notes = super::shared_cache_notes_for( + &[planned_root("cache", std::env::temp_dir())], + &[test_shared_cache(missing)], ); assert!(notes.is_empty(), "{notes:?}"); } + /// `ROCM_CLI_DATA_DIR=/` used to plan `- data: /`. The root is refused, the + /// review names it, why, and the flag that clears it — and that flag does. + /// The "nothing was removed" half of the message is proven where removal + /// happens: `uninstall_refuses_and_removes_nothing_when_a_root_is_protected` + /// below and the `uninstall-17` E2E scenario. + #[test] + fn uninstall_plan_refuses_the_filesystem_root() { + let root = std::env::temp_dir().join(format!("rocm-refuse-root-{}", std::process::id())); + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: PathBuf::from("/"), + cache_dir: root.join("cache"), + }; + let options = super::UninstallOptions { + keep_binaries: true, + ..super::UninstallOptions::default() + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &options, + None, + ) + .unwrap(); + assert!( + plan.actions + .iter() + .all(|entry| entry.path != Path::new("/")), + "{plan:?}" + ); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].kind, "data"); + assert_eq!( + plan.refused[0].why, + rocm_core::ProtectedLocation::FilesystemRoot + ); + let error = plan.refusal_error().expect("a refusal error"); + assert!( + // The root prints in the host's own spelling (`\\` on Windows). + error.contains(&format!( + "data folder {} is the top of the filesystem", + plan.refused[0].path.display() + )), + "{error}" + ); + assert!(error.contains("--keep-data"), "{error}"); + let rendered = super::render_uninstall_plan( + &plan, + &super::UninstallOptions { + dry_run: true, + ..options + }, + super::PlanAudience::Captured, + ); + assert!( + rendered.contains(&format!( + " - data: {} is the top of the filesystem", + plan.refused[0].path.display() + )), + "{rendered}" + ); + assert!(!rendered.contains("Choose Review uninstall"), "{rendered}"); + + let keep = super::UninstallOptions { + keep_data: true, + ..options + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &keep, + None, + ) + .unwrap(); + assert!( + plan.refused.is_empty(), + "--keep-data must clear it: {plan:?}" + ); + } + + /// The home folder itself — `setup.therock_venv` set to `$HOME` reaches the + /// data root this way — is refused, and nothing at all is removed: not the + /// home folder, and not the other roots either. + #[test] + // Unix only: it needs a folder outside the sandbox home that is not another + // user's, and on Windows the temp folder is itself inside `C:\\Users\\`, + // where everything outside the sandbox home counts as another user's home. + #[cfg(unix)] + fn uninstall_refuses_and_removes_nothing_when_a_root_is_protected() { + let root = std::env::temp_dir().join(format!("rocm-refuse-home-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let home = root.join("users").join("home"); + std::fs::create_dir_all(home.join("Documents")).unwrap(); + std::fs::write(home.join("Documents").join("thesis.txt"), b"keep").unwrap(); + // A config folder ROCm CLI created (marked), so only the home folder is + // refused and the test can show that refusal still removes nothing. + rocm_core::create_marked_root(&root.join("config")).unwrap(); + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: PathBuf::from(format!("{}/", home.display())), + cache_dir: root.join("cache"), + }; + let options = super::UninstallOptions { + yes: true, + keep_binaries: true, + ..super::UninstallOptions::default() + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &options, + Some(&home), + ) + .unwrap(); + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let thesis_left = home.join("Documents").join("thesis.txt").is_file(); + let config_left = root.join("config").is_dir(); + let _ = std::fs::remove_dir_all(&root); + + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::Home); + let error = format!("{:#}", outcome.expect_err("a refused plan must not apply")); + assert!(error.contains("nothing was removed"), "{error}"); + assert!(error.contains("is your home folder"), "{error}"); + assert!(thesis_left, "the home folder was emptied"); + assert!(config_left, "a refused plan still removed another root"); + } + + fn refused_plan(root: &Path) -> super::UninstallPlan { + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: PathBuf::from("/"), + cache_dir: root.join("cache"), + }; + let sources = rocm_core::AppPathSources { + data: rocm_core::AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()), + ..rocm_core::AppPathSources::default() + }; + let options = super::UninstallOptions { + keep_binaries: true, + ..super::UninstallOptions::default() + }; + super::build_uninstall_plan_for_home(&paths, &sources, &options, None).unwrap() + } + + /// The refusal is decided before anything else in the command, and in + /// particular before the confirmation prompt: a refused uninstall must not + /// ask "Proceed?" first. + #[test] + fn a_refused_uninstall_stops_before_the_prompt() { + let root = std::env::temp_dir().join(format!("rocm-refuse-prompt-{}", std::process::id())); + let plan = refused_plan(&root); + let options = super::UninstallOptions { + keep_binaries: true, + ..super::UninstallOptions::default() + }; + let mut asked = false; + let outcome = crate::uninstall::run_uninstall_plan( + &plan, + &options, + || true, + || { + asked = true; + Ok(true) + }, + ); + let error = format!("{:#}", outcome.expect_err("a refused plan must fail")); + assert!(!asked, "the confirmation prompt ran before the refusal"); + assert!( + error.contains("uninstall refused, nothing was removed"), + "{error}" + ); + } + + /// A plan nothing refused still needs `--yes` or a person to say yes, through + /// the shared `require_yes_or_interactive` guard: with neither it is + /// refused before the prompt, and at a terminal the prompt decides. + /// Either way a "no" removes nothing. + #[test] + fn an_accepted_plan_needs_yes_or_a_terminal_answer() { + let root = std::env::temp_dir().join(format!("rocm-accept-gate-{}", std::process::id())); + let config = root.join("config"); + std::fs::create_dir_all(&config).unwrap(); + let plan = super::UninstallPlan { + actions: vec![planned_root("config", config.clone())], + ..super::UninstallPlan::default() + }; + let options = super::UninstallOptions { + keep_binaries: true, + ..super::UninstallOptions::default() + }; + + let mut asked = false; + let no_terminal = crate::uninstall::run_uninstall_plan( + &plan, + &options, + || false, + || { + asked = true; + Ok(true) + }, + ); + let asked_without_terminal = asked; + let declined = crate::uninstall::run_uninstall_plan( + &plan, + &options, + || true, + || { + asked = true; + Ok(false) + }, + ); + let config_left = config.is_dir(); + let _ = std::fs::remove_dir_all(&root); + + let error = format!("{:#}", no_terminal.expect_err("no --yes and no terminal")); + assert_eq!( + error, + "uninstall requires --yes outside an interactive terminal" + ); + assert!(!asked_without_terminal, "asked with no terminal to answer"); + assert!(declined.is_ok(), "{declined:?}"); + assert!(asked, "a terminal without --yes must be asked"); + assert!( + config_left, + "a refused or declined uninstall removed the config" + ); + } + + /// A dry run of a refused plan fails too, so a script that previews before + /// it removes does not read the refusal as a go-ahead. + #[test] + fn a_refused_dry_run_fails() { + let root = std::env::temp_dir().join(format!("rocm-refuse-dry-{}", std::process::id())); + let plan = refused_plan(&root); + let options = super::UninstallOptions { + dry_run: true, + keep_binaries: true, + ..super::UninstallOptions::default() + }; + let outcome = + crate::uninstall::run_uninstall_plan(&plan, &options, || true, || panic!("no prompt")); + let error = format!("{:#}", outcome.expect_err("a refused dry run must fail")); + assert!(error.contains("would be refused"), "{error}"); + } + + /// The refusal names where the folder came from, and points at that + /// setting as well as at the `--keep-` flag. + #[test] + fn a_refusal_names_the_setting_the_folder_came_from() { + let root = std::env::temp_dir().join(format!("rocm-refuse-source-{}", std::process::id())); + let plan = refused_plan(&root); + let error = plan.refusal_error().expect("refused"); + assert!( + error.contains(&format!( + "the data folder {} is the top of the filesystem (set by ROCM_CLI_DATA_DIR)", + plan.refused[0].path.display() + )), + "{error}" + ); + assert!( + error.contains( + "Point ROCM_CLI_DATA_DIR at a folder of ROCm CLI's own, or re-run with \ + --keep-data to leave it in place." + ), + "{error}" + ); + } + + /// The assistant's and dashboard's in-process `uninstall --dry-run` honours + /// the `--keep-` flag the refusal advises, so following the advice + /// there clears the refusal instead of repeating it. + #[test] + fn in_process_uninstall_dry_run_honours_the_advised_keep_flag() { + let root = std::env::temp_dir().join(format!("rocm-refuse-chat-{}", std::process::id())); + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: PathBuf::from("/"), + cache_dir: root.join("cache"), + }; + let sources = rocm_core::AppPathSources::default(); + let args = |extra: &[&str]| -> Vec { + ["--dry-run", "--keep-binaries"] + .iter() + .chain(extra) + .map(|arg| (*arg).to_owned()) + .collect() + }; + + let refused = + super::render_uninstall_dry_run_with(&paths, &sources, &args(&[]), None).unwrap(); + assert!(refused.contains("would be refused"), "{refused}"); + assert!(refused.contains("--keep-data"), "{refused}"); + + let kept = + super::render_uninstall_dry_run_with(&paths, &sources, &args(&["--keep-data"]), None) + .unwrap(); + assert!(!kept.contains("Refused"), "{kept}"); + assert!(!kept.contains("would be refused"), "{kept}"); + assert!( + kept.contains("data removal disabled by command line flag"), + "{kept}" + ); + + // And the in-process dispatcher hands it the flags. + let dispatched = crate::chat::run_rocm_read_only_in_process( + &paths, + &[ + "uninstall".to_owned(), + "--dry-run".to_owned(), + "--keep-binaries".to_owned(), + "--keep-data".to_owned(), + ], + ) + .unwrap(); + assert!(!dispatched.contains("Refused"), "{dispatched}"); + } + + /// Every `--keep-` the refusal can advise reaches the assistant's + /// preview: with the refused root set to `/`, the flag for that kind, and + /// only that one, clears the refusal. + #[test] + fn in_process_uninstall_dry_run_honours_every_keep_flag() { + let root = std::env::temp_dir().join(format!("rocm-keep-each-{}", std::process::id())); + let sources = rocm_core::AppPathSources::default(); + for kind in ["config", "data", "cache"] { + let at = |own: &str| { + if own == kind { + PathBuf::from("/") + } else { + root.join(own) + } + }; + let paths = AppPaths { + config_dir: at("config"), + data_dir: at("data"), + cache_dir: at("cache"), + }; + for flag in ["--keep-config", "--keep-data", "--keep-cache"] { + let args = ["--dry-run", "--keep-binaries", flag].map(str::to_owned); + let text = + super::render_uninstall_dry_run_with(&paths, &sources, &args, None).unwrap(); + let clears = flag == format!("--keep-{kind}"); + assert_eq!( + !text.contains("would be refused"), + clears, + "{kind} root at /, {flag}:\n{text}" + ); + } + } + } + + /// The approval-gated assistant/dashboard uninstall keeps the advised flag + /// on its way to the real command. + #[test] + fn approved_uninstall_keeps_the_keep_flags() { + let action = crate::chat::chat_rocm_command_action_from_args(vec![ + "uninstall".to_owned(), + "--keep-data".to_owned(), + ]) + .unwrap(); + let crate::chat::ChatRocmCommandAction::Approval { args, .. } = action else { + panic!("a real uninstall must be approval-gated"); + }; + assert!(args.iter().any(|arg| arg == "--keep-data"), "{args:?}"); + } + + /// A relative path from this process's working directory to `target`, built + /// from `..` segments, so a test can spell a folder relatively without + /// changing the (process-global) working directory. + #[cfg(unix)] + fn relative_from_cwd(target: &Path) -> PathBuf { + let cwd = std::env::current_dir().unwrap().canonicalize().unwrap(); + let target = target.canonicalize().unwrap(); + let mut rel = PathBuf::new(); + for _ in cwd.components().skip(1) { + rel.push(".."); + } + rel.join(target.strip_prefix("/").unwrap()) + } + + /// The text check alone let these through: `.` run from home and `..` run + /// from `~/proj` are relative, and home reached through a symlinked parent + /// (the `/home -> var/home` layout) is spelled differently from `$HOME`. + /// A real directory is also judged by where it really is. + #[test] + #[cfg(unix)] + fn home_is_refused_however_it_is_reached() { + let root = std::env::temp_dir().join(format!("rocm-refuse-reached-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let root = root.canonicalize().unwrap(); + let home = root.join("var").join("home").join("alice"); + std::fs::create_dir_all(home.join("proj")).unwrap(); + std::fs::write(home.join("keep.txt"), b"keep").unwrap(); + let _ = std::os::unix::fs::symlink(root.join("var").join("home"), root.join("home")); + + let spellings = [ + relative_from_cwd(&home), + relative_from_cwd(&home.join("proj")).join(".."), + root.join("home").join("alice"), + ]; + let options = super::UninstallOptions { + yes: true, + keep_binaries: true, + keep_config: true, + keep_cache: true, + ..super::UninstallOptions::default() + }; + let mut failures = Vec::new(); + for data_dir in &spellings { + let paths = AppPaths { + config_dir: root.join("config"), + data_dir: data_dir.clone(), + cache_dir: root.join("cache"), + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &options, + Some(&home), + ) + .unwrap(); + let refused_as_home = plan.refused.iter().any(|refused| { + refused.why == rocm_core::ProtectedLocation::Home && refused.resolved.is_some() + }); + if !refused_as_home { + failures.push(format!("{}: {plan:?}", data_dir.display())); + } + let _ = crate::uninstall::apply_uninstall_plan(&plan); + } + let kept = home.join("keep.txt").is_file(); + let _ = std::fs::remove_dir_all(&root); + assert!(kept, "home was emptied"); + assert!(failures.is_empty(), "not refused as home: {failures:#?}"); + } + + fn keep_binaries() -> super::UninstallOptions { + super::UninstallOptions { + yes: true, + keep_binaries: true, + ..super::UninstallOptions::default() + } + } + + fn data_only(data_dir: PathBuf, root: &Path) -> AppPaths { + AppPaths { + config_dir: root.join("no-config"), + data_dir, + cache_dir: root.join("no-cache"), + } + } + + fn sandbox(label: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("rocm-{label}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + root.canonicalize().unwrap() + } + + /// The review's dry run planned all of these for deletion. Each is refused + /// now, judged on the real host folders (plan only: nothing is removed). + #[test] + #[cfg(target_os = "linux")] + fn system_folders_the_review_found_are_refused() { + let root = std::env::temp_dir(); + for (folder, why) in [ + ("/usr/local", rocm_core::ProtectedLocation::System), + ("/etc/ssl", rocm_core::ProtectedLocation::System), + ("/usr/bin", rocm_core::ProtectedLocation::System), + ("/usr/lib", rocm_core::ProtectedLocation::System), + ("/var/lib", rocm_core::ProtectedLocation::SharedTopLevel), + ] { + if !Path::new(folder).is_dir() { + continue; + } + let plan = super::build_uninstall_plan_for_home( + &data_only(PathBuf::from(folder), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(Path::new("/home/alice")), + ) + .unwrap(); + assert!(plan.actions.is_empty(), "{folder}: {plan:?}"); + assert_eq!(plan.refused.len(), 1, "{folder}: {plan:?}"); + assert_eq!(plan.refused[0].why, why, "{folder}"); + } + } + + /// A real directory outside home without the marker is refused, and the + /// advice to create the marker is true: once it exists, the same plan goes + /// ahead and removes the folder. + #[test] + // Unix only: it needs a folder outside the sandbox home that is not another + // user's, and on Windows the temp folder is itself inside `C:\\Users\\`, + // where everything outside the sandbox home counts as another user's home. + #[cfg(unix)] + fn creating_the_advised_marker_clears_the_refusal() { + let root = sandbox("marker-advice"); + let home = root.join("users").join("home"); + std::fs::create_dir_all(&home).unwrap(); + let data = root.join("srv").join("rocm"); + std::fs::create_dir_all(&data).unwrap(); + let paths = data_only(data.clone(), &root); + let sources = rocm_core::AppPathSources::default(); + + let plan = + super::build_uninstall_plan_for_home(&paths, &sources, &keep_binaries(), Some(&home)) + .unwrap(); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::NotMarked); + let error = plan.refusal_error().unwrap(); + let marker = data.join(rocm_core::ROCM_CLI_ROOT_MARKER); + let advised = format!( + "f this folder belongs to ROCm CLI, create {}", + marker.display() + ); + assert!(error.contains(&advised), "{error}"); + + // Follow the advice. + std::fs::write(&marker, b"").unwrap(); + let plan = + super::build_uninstall_plan_for_home(&paths, &sources, &keep_binaries(), Some(&home)) + .unwrap(); + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let left = data.exists(); + let _ = std::fs::remove_dir_all(&root); + assert!(plan.refused.is_empty(), "{plan:?}"); + assert!(outcome.is_ok(), "{outcome:?}"); + assert!(!left, "the marked folder was not removed"); + } + + /// "Point ROCM_CLI_DATA_DIR at a folder of ROCm CLI's own" is advice that + /// works: the same uninstall with the variable repointed is not refused. + #[test] + fn pointing_the_named_variable_elsewhere_clears_the_refusal() { + let root = sandbox("point-advice"); + let home = root.join("home"); + std::fs::create_dir_all(home.join(".rocm").join("data")).unwrap(); + let sources = rocm_core::AppPathSources { + data: rocm_core::AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()), + ..rocm_core::AppPathSources::default() + }; + let refused = super::build_uninstall_plan_for_home( + &data_only(home.clone(), &root), + &sources, + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let error = refused.refusal_error().unwrap(); + assert!( + error.contains("Point ROCM_CLI_DATA_DIR at a folder of ROCm CLI's own"), + "{error}" + ); + + let repointed = super::build_uninstall_plan_for_home( + &data_only(home.join(".rocm").join("data"), &root), + &sources, + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert!(repointed.refused.is_empty(), "{repointed:?}"); + assert_eq!(repointed.actions.len(), 1, "{repointed:?}"); + } + + /// When the folder came from `setup.therock_venv`, the advice leads with + /// `--keep-data` and warns that moving the setting would orphan the SDK — + /// and `--keep-data` clears the refusal. + #[test] + // Unix only: it needs a folder outside the sandbox home that is not another + // user's, and on Windows the temp folder is itself inside `C:\\Users\\`, + // where everything outside the sandbox home counts as another user's home. + #[cfg(unix)] + fn a_therock_venv_refusal_advises_keep_data_first() { + let root = sandbox("venv-advice"); + let home = root.join("users").join("home"); + std::fs::create_dir_all(&home).unwrap(); + let sources = rocm_core::AppPathSources { + data: rocm_core::AppPathSource::TheRockVenv(root.join("config.json")), + ..rocm_core::AppPathSources::default() + }; + let paths = data_only(home.clone(), &root); + let plan = + super::build_uninstall_plan_for_home(&paths, &sources, &keep_binaries(), Some(&home)) + .unwrap(); + let advice = plan.refusal_advice().unwrap(); + let keep = super::UninstallOptions { + keep_data: true, + ..keep_binaries() + }; + let kept = + super::build_uninstall_plan_for_home(&paths, &sources, &keep, Some(&home)).unwrap(); + // With a second way out (an unmarked prefix outside home), --keep-data + // still comes first. + let prefix = root.join("sdk"); + std::fs::create_dir_all(&prefix).unwrap(); + let unmarked = super::build_uninstall_plan_for_home( + &data_only(prefix, &root), + &sources, + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let unmarked_advice = unmarked.refusal_advice().unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert!( + advice.starts_with("Re-run with --keep-data to leave it in place."), + "{advice}" + ); + assert!( + unmarked_advice.starts_with("Re-run with --keep-data to leave it in place, or if"), + "{unmarked_advice}" + ); + assert!(advice.contains("would orphan the ROCm SDK"), "{advice}"); + assert!(!advice.contains("point setup.therock_venv"), "{advice}"); + assert!(kept.refused.is_empty(), "{kept:?}"); + } + + /// A real directory whose location cannot be resolved is refused rather + /// than judged by its spelling alone. + #[test] + fn an_unresolvable_root_is_refused() { + let root = sandbox("unresolvable"); + let home = root.join("home"); + std::fs::create_dir_all(home.join("data")).unwrap(); + let fail: &dyn Fn(&Path) -> std::io::Result = + &|_| Err(std::io::Error::other("cannot resolve")); + let plan = super::build_uninstall_plan_with( + &data_only(home.join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + fail, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!( + plan.refused[0].why, + rocm_core::ProtectedLocation::Unresolvable + ); + } + + /// HOME is spelled through a symlinked parent (`/home -> var/home`) and the + /// data folder is the real path: only comparing against the RESOLVED home + /// shows they are the same folder, and it is refused as home, not merely + /// as an unmarked folder. + #[test] + #[cfg(unix)] + fn the_real_home_is_refused_when_home_is_spelled_through_a_link() { + let root = sandbox("resolved-home"); + let real_home = root.join("var").join("home").join("alice"); + std::fs::create_dir_all(&real_home).unwrap(); + std::os::unix::fs::symlink(root.join("var").join("home"), root.join("home")).unwrap(); + let home_as_set = root.join("home").join("alice"); + let plan = super::build_uninstall_plan_for_home( + &data_only(real_home, &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home_as_set), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::Home); + } + + /// A system location that is itself a link (Silverblue: `/media -> run/media`) + /// protects where it really is: a folder under its target is refused as a + /// system location although the target is not on the list as written. The + /// resolver is injected so the layout can be built in a sandbox. + #[test] + #[cfg(unix)] + fn a_system_root_reached_through_its_link_target_is_refused() { + let root = sandbox("linked-system-root"); + let home = root.join("users").join("home"); + let real_mnt = root.join("var").join("mnt"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(real_mnt.join("data")).unwrap(); + let mnt_target = real_mnt.clone(); + let resolve: &dyn Fn(&Path) -> std::io::Result = &move |path: &Path| { + if path == Path::new("/media") { + Ok(mnt_target.clone()) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + let plan = super::build_uninstall_plan_with( + &data_only(real_mnt.join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + resolve, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::System); + } + + /// A root spelled beside home that really is inside it — Windows spells the + /// temp folder with the home folder's short 8.3 name (`RUNNER~1`) — is + /// judged by where it really is and planned; a real folder in another + /// user's home is still refused. Here a link stands in for the short name. + #[test] + #[cfg(unix)] + fn a_root_spelled_beside_home_but_inside_it_is_planned() { + let root = sandbox("short-name-home"); + let users = root.join("users"); + let home = users.join("home"); + let data = home.join(".rocm").join("data"); + std::fs::create_dir_all(&data).unwrap(); + let short = users.join("HOME~1"); + std::os::unix::fs::symlink(&home, &short).unwrap(); + let other = users.join("bob").join("data"); + std::fs::create_dir_all(&other).unwrap(); + + let own = super::build_uninstall_plan_for_home( + &data_only(short.join(".rocm").join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let bobs = super::build_uninstall_plan_for_home( + &data_only(other, &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + + assert!(own.refused.is_empty(), "{own:?}"); + assert_eq!(own.actions.len(), 1, "{own:?}"); + assert_eq!(bobs.refused.len(), 1, "{bobs:?}"); + assert_eq!( + bobs.refused[0].why, + rocm_core::ProtectedLocation::OtherUsersHome + ); + } + + /// Check, then act, for a root that was a symbolic link at review time: + /// replaced by a real folder while the prompt was open, it must not be + /// removed recursively; the same goes for a file that became a folder. + #[test] + #[cfg(unix)] + fn a_link_or_file_root_that_became_a_folder_is_not_removed() { + let root = sandbox("link-became-dir"); + let home = root.join("users").join("home"); + std::fs::create_dir_all(&home).unwrap(); + let target = root.join("target"); + std::fs::create_dir_all(&target).unwrap(); + let link = home.join("cache"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let file = home.join("config"); + std::fs::write(&file, b"settings").unwrap(); + let paths = AppPaths { + config_dir: file.clone(), + data_dir: home.join("no-data"), + cache_dir: link.clone(), + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + assert_eq!(plan.actions.len(), 2, "{plan:?}"); + + // The swaps, as if they happened while the prompt was open. + std::fs::remove_file(&link).unwrap(); + std::fs::create_dir_all(&link).unwrap(); + std::fs::write(link.join("precious.txt"), b"keep").unwrap(); + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let precious = link.join("precious.txt").is_file(); + + std::fs::remove_dir_all(&link).unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir_all(&file).unwrap(); + std::fs::write(file.join("precious.txt"), b"keep").unwrap(); + let file_outcome = crate::uninstall::apply_uninstall_plan(&plan); + let file_precious = file.join("precious.txt").is_file(); + let _ = std::fs::remove_dir_all(&root); + + assert!( + precious, + "a link replaced by a folder was removed recursively" + ); + let error = format!("{:#}", outcome.expect_err("must stop")); + assert!( + error.contains("was a symbolic link when reviewed"), + "{error}" + ); + assert!( + file_precious, + "a file replaced by a folder was removed recursively" + ); + let error = format!("{:#}", file_outcome.expect_err("must stop")); + assert!(error.contains("was a file when reviewed"), "{error}"); + } + + /// A symlink root is unlinked only where the review saw it: if the folder + /// holding it is swapped for a link to somewhere else, a link of the same + /// name there is not touched. + #[test] + #[cfg(unix)] + fn a_link_root_whose_folder_moved_is_not_unlinked() { + let root = sandbox("link-parent-moved"); + let home = root.join("users").join("home"); + let holder = home.join("holder"); + std::fs::create_dir_all(&holder).unwrap(); + std::os::unix::fs::symlink(root.join("target"), holder.join("cache")).unwrap(); + let elsewhere = root.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + std::os::unix::fs::symlink(root.join("theirs"), elsewhere.join("cache")).unwrap(); + let plan = super::build_uninstall_plan_for_home( + &AppPaths { + config_dir: home.join("no-config"), + data_dir: home.join("no-data"), + cache_dir: holder.join("cache"), + }, + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + assert_eq!(plan.actions.len(), 1, "{plan:?}"); + std::fs::rename(&holder, home.join("holder-old")).unwrap(); + std::os::unix::fs::symlink(&elsewhere, &holder).unwrap(); + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let theirs_left = std::fs::symlink_metadata(elsewhere.join("cache")).is_ok(); + let _ = std::fs::remove_dir_all(&root); + assert!( + theirs_left, + "the link in the swapped-in folder was unlinked" + ); + let error = format!("{:#}", outcome.expect_err("must stop")); + assert!(error.contains("folder holding it now resolves"), "{error}"); + } + + /// A planned folder that is already gone when its turn comes (inside one + /// removed earlier, or removed by hand during the prompt) is skipped, and + /// the rest of the plan still runs. + #[test] + fn a_planned_folder_already_gone_is_skipped() { + let root = sandbox("already-gone"); + let home = root.join("users").join("home"); + let config = home.join(".rocm").join("config"); + let data = home.join(".rocm").join("data"); + std::fs::create_dir_all(&config).unwrap(); + std::fs::create_dir_all(&data).unwrap(); + let paths = AppPaths { + config_dir: config.clone(), + data_dir: data.clone(), + cache_dir: home.join("no-cache"), + }; + let plan = super::build_uninstall_plan_for_home( + &paths, + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + assert_eq!(plan.actions.len(), 2, "{plan:?}"); + std::fs::remove_dir_all(&config).unwrap(); + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let data_left = data.exists(); + let _ = std::fs::remove_dir_all(&root); + assert!(outcome.is_ok(), "{outcome:?}"); + assert!(!data_left, "the rest of the plan did not run"); + } + + /// Check, then act: a parent swapped for a symlink between the review and + /// the removal must not redirect the removal to another folder. + #[test] + #[cfg(unix)] + fn a_root_that_moved_after_the_review_is_not_removed() { + let root = sandbox("check-then-act"); + let home = root.join("home"); + let parent = home.join("parent"); + std::fs::create_dir_all(parent.join("data")).unwrap(); + let elsewhere = root.join("elsewhere"); + std::fs::create_dir_all(elsewhere.join("data")).unwrap(); + std::fs::write(elsewhere.join("data").join("precious"), b"keep").unwrap(); + let plan = super::build_uninstall_plan_for_home( + &data_only(parent.join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + assert_eq!(plan.actions.len(), 1, "{plan:?}"); + + // The swap, as if it happened while the prompt was open. + std::fs::rename(&parent, home.join("parent-old")).unwrap(); + std::os::unix::fs::symlink(&elsewhere, &parent).unwrap(); + + let outcome = crate::uninstall::apply_uninstall_plan(&plan); + let precious = elsewhere.join("data").join("precious").is_file(); + let _ = std::fs::remove_dir_all(&root); + assert!(precious, "the removal followed the swapped-in link"); + let error = format!( + "{:#}", + outcome.expect_err("a moved root must stop the removal") + ); + assert!(error.contains("now resolves to"), "{error}"); + } + + /// `discover_with_sources` against real environment and config state: + /// `setup.therock_venv` moves the data and cache folders and is named as + /// their source; a parent's forwarded sources win for pinned folders. + #[test] + fn discover_with_sources_reads_the_real_environment_and_config() { + let root = sandbox("discover-sources"); + let config = root.join("config"); + let sdk = root.join("sdk"); + std::fs::create_dir_all(&config).unwrap(); + std::fs::write( + config.join("config.json"), + serde_json::to_vec(&json!({ "setup": { "therock_venv": sdk } })).unwrap(), + ) + .unwrap(); + // Every lock that guards the `ROCM_CLI_*` variables: `ScopedTestEnv` + // has its own, other tests that set them hold the shared process lock, + // and a built-in engine call rewrites them under the engine lock. + let _process_env = crate::test_support::PROCESS_ENV_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _engine_env = crate::engine_ipc::builtin_engine_env_test_lock(); + let mut env = ScopedTestEnv::new(); + env.set("ROCM_CLI_CONFIG_DIR", &config.display().to_string()); + env.clear("ROCM_CLI_DATA_DIR"); + env.clear("ROCM_CLI_CACHE_DIR"); + env.clear(rocm_core::APP_PATH_SOURCES_ENV); + let (paths, sources) = AppPaths::discover_with_sources().unwrap(); + + // A parent pins the data folder and forwards where it came from. + let forwarded_json = + serde_json::to_string(&rocm_core::ForwardedAppPathSources::for_paths(&paths)).unwrap(); + env.set("ROCM_CLI_DATA_DIR", &paths.data_dir.display().to_string()); + env.set(rocm_core::APP_PATH_SOURCES_ENV, &forwarded_json); + let (_, forwarded) = AppPaths::discover_with_sources().unwrap(); + // Stale or forged: the variable now names a different folder than + // the forwarded entry describes, so the entry is ignored. + env.set( + "ROCM_CLI_DATA_DIR", + &root.join("elsewhere").display().to_string(), + ); + let (_, stale) = AppPaths::discover_with_sources().unwrap(); + env.set("ROCM_CLI_DATA_DIR", &paths.data_dir.display().to_string()); + env.clear(rocm_core::APP_PATH_SOURCES_ENV); + let (_, unforwarded) = AppPaths::discover_with_sources().unwrap(); + drop(env); + assert_eq!( + stale.data, + rocm_core::AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()) + ); + let _ = std::fs::remove_dir_all(&root); + + let venv = rocm_core::AppPathSource::TheRockVenv(config.join("config.json")); + assert_eq!(paths.data_dir, sdk); + assert_eq!( + sources.config, + rocm_core::AppPathSource::Env("ROCM_CLI_CONFIG_DIR".to_owned()) + ); + assert_eq!(sources.data, venv); + assert_eq!(sources.cache, venv); + assert_eq!(forwarded.data, venv); + assert_eq!(forwarded.cache, venv); + assert_eq!( + unforwarded.data, + rocm_core::AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()) + ); + // With no cache setting, the cache folder follows the data folder, so + // the data folder's setting is named for it, not the default location. + assert_eq!( + unforwarded.cache, + rocm_core::AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()) + ); + } + + /// The dashboard and assistant path: with `setup.therock_venv` set to the + /// home folder, `rocm_command uninstall --dry-run` (in-process) names + /// `setup.therock_venv` and advises `--keep-data`, never a variable the + /// user did not set; and a `rocm` child started for an approved command is + /// told the same sources. + #[test] + // Unix only: it needs a folder outside the sandbox home that is not another + // user's, and on Windows the temp folder is itself inside `C:\\Users\\`, + // where everything outside the sandbox home counts as another user's home. + #[cfg(unix)] + fn the_dashboard_path_names_the_setting_the_user_made() { + let root = sandbox("dash-sources"); + let home = root.join("home"); + let config = root.join("config"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&config).unwrap(); + std::fs::write( + config.join("config.json"), + serde_json::to_vec(&json!({ "setup": { "therock_venv": home } })).unwrap(), + ) + .unwrap(); + // Every lock that guards the `ROCM_CLI_*` variables: `ScopedTestEnv` + // has its own, other tests that set them hold the shared process lock, + // and a built-in engine call rewrites them under the engine lock. + let _process_env = crate::test_support::PROCESS_ENV_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _engine_env = crate::engine_ipc::builtin_engine_env_test_lock(); + let mut env = ScopedTestEnv::new(); + env.set("HOME", &home.display().to_string()); + env.set("ROCM_CLI_CONFIG_DIR", &config.display().to_string()); + env.set( + "ROCM_CLI_CACHE_DIR", + &root.join("cache").display().to_string(), + ); + env.clear("ROCM_CLI_DATA_DIR"); + env.clear(rocm_core::APP_PATH_SOURCES_ENV); + let paths = AppPaths::discover().unwrap(); + let shown = crate::chat::run_internal_mcp_call( + &paths, + "rocm_command", + json!({ "args": ["uninstall", "--dry-run", "--keep-binaries"] }), + false, + ) + .unwrap(); + let child = crate::engine_runtime_select::rocm_child_app_path_env(&paths); + // An interactive shell or an engine gets the folders, not the sources. + let mut shell = std::process::Command::new("true"); + paths.apply_env(&mut shell); + let shell_gets_sources = shell + .get_envs() + .any(|(key, _)| key == rocm_core::APP_PATH_SOURCES_ENV); + assert!( + !shell_gets_sources, + "sources were passed to a non-rocm child" + ); + let forwarded = child + .iter() + .find(|(key, _)| *key == rocm_core::APP_PATH_SOURCES_ENV) + .map(|(_, value)| value.to_string_lossy().into_owned()); + drop(env); + let _ = std::fs::remove_dir_all(&root); + + let text = shown.to_string(); + assert!(text.contains("set by setup.therock_venv"), "{text}"); + assert!(text.contains("Re-run with --keep-data"), "{text}"); + assert!(!text.contains("ROCM_CLI_DATA_DIR"), "{text}"); + let forwarded: rocm_core::ForwardedAppPathSources = + serde_json::from_str(&forwarded.expect("sources forwarded")).unwrap(); + assert!( + matches!( + forwarded.data.source, + rocm_core::AppPathSource::TheRockVenv(_) + ), + "{forwarded:?}" + ); + assert_eq!(forwarded.data.path, paths.data_dir); + } + #[test] fn uninstall_binary_matcher_includes_packaged_codex_binary() { assert!(is_rocm_install_entry_name("rocm-codex")); @@ -785,7 +2396,7 @@ mod tests { keep_binaries: true, ..UninstallOptions::default() }; - let plan = build_uninstall_plan(&paths, &options); + let plan = build_uninstall_plan(&paths, &rocm_core::AppPathSources::default(), &options); let _ = fs::remove_dir_all(&root); let plan = plan?; @@ -854,13 +2465,25 @@ mod tests { }; set_helper_facts(&paths, false, false); - let none = helper_warnings(&build_uninstall_plan(&paths, &options).expect("plan")); + let none = helper_warnings( + &build_uninstall_plan(&paths, &rocm_core::AppPathSources::default(), &options) + .expect("plan"), + ); set_helper_facts(&paths, true, false); - let enabled_dead = helper_warnings(&build_uninstall_plan(&paths, &options).expect("plan")); + let enabled_dead = helper_warnings( + &build_uninstall_plan(&paths, &rocm_core::AppPathSources::default(), &options) + .expect("plan"), + ); set_helper_facts(&paths, false, true); - let idle = helper_warnings(&build_uninstall_plan(&paths, &options).expect("plan")); + let idle = helper_warnings( + &build_uninstall_plan(&paths, &rocm_core::AppPathSources::default(), &options) + .expect("plan"), + ); set_helper_facts(&paths, true, true); - let outlives = helper_warnings(&build_uninstall_plan(&paths, &options).expect("plan")); + let outlives = helper_warnings( + &build_uninstall_plan(&paths, &rocm_core::AppPathSources::default(), &options) + .expect("plan"), + ); let _ = std::fs::remove_dir_all(&root); assert!(none.is_empty(), "{none:?}"); diff --git a/crates/rocm-core/src/config.rs b/crates/rocm-core/src/config.rs index d6a6cbce20..b203cda9f2 100644 --- a/crates/rocm-core/src/config.rs +++ b/crates/rocm-core/src/config.rs @@ -647,6 +647,9 @@ impl RocmCliConfig { /// "no settings". pub fn save(&self, paths: &AppPaths) -> Result<()> { let path = paths.config_path(); + // Saving the config is often what first brings the config folder into + // being, so it is created as ROCm CLI's own (marked) when this is. + crate::runtime::create_marked_root(&paths.config_dir)?; let bytes = serde_json::to_vec_pretty(self).context("failed to serialize rocm-cli config")?; serde_json::from_slice::(&bytes).with_context(|| { @@ -1461,6 +1464,35 @@ last_installed_runtime_id = "therock-release" /// supported platforms without needing permissions a root CI lane ignores — /// the same device `write_file_atomically_cleans_up_temp_when_the_rename_fails` /// uses in `rocm_core::atomic_write`. + /// Saving the config often creates the config folder; when it does, the + /// folder is marked as ROCm CLI's own, so `rocm uninstall` can later remove + /// it outside the home folder. A config folder that already existed is not + /// marked. + #[test] + fn the_config_folder_a_save_creates_is_marked_and_an_existing_one_is_not() -> Result<()> { + let (root, fresh) = temp_app_paths("config-save-marks-root"); + RocmCliConfig::default().save(&fresh)?; + let fresh_marked = fresh + .config_dir + .join(crate::runtime::ROCM_CLI_ROOT_MARKER) + .is_file(); + let (other_root, existing) = temp_app_paths("config-save-keeps-existing-root"); + fs::create_dir_all(&existing.config_dir)?; + RocmCliConfig::default().save(&existing)?; + let existing_marked = existing + .config_dir + .join(crate::runtime::ROCM_CLI_ROOT_MARKER) + .exists(); + let _ = fs::remove_dir_all(&root); + let _ = fs::remove_dir_all(&other_root); + assert!( + fresh_marked, + "the config folder a save created is not marked" + ); + assert!(!existing_marked, "an existing config folder was marked"); + Ok(()) + } + #[test] fn a_config_save_that_cannot_publish_cleans_up_its_temp_file() -> Result<()> { let (root, paths) = temp_app_paths("config-save-rename-fails"); diff --git a/crates/rocm-core/src/confirm.rs b/crates/rocm-core/src/confirm.rs index e5fa9f9a03..419ab6f700 100644 --- a/crates/rocm-core/src/confirm.rs +++ b/crates/rocm-core/src/confirm.rs @@ -149,10 +149,12 @@ pub fn require_yes_or_interactive(yes: bool, action: &str) -> Result { require_yes_or_interactive_with(yes, action, interactive_terminal) } -/// [`require_yes_or_interactive`] with the terminal probe injected, so the -/// refusal is testable without depending on how the test runner's streams are -/// wired. The probe is only called when `yes` is false. -fn require_yes_or_interactive_with( +/// [`require_yes_or_interactive`] with the terminal probe injected. +/// +/// The refusal is then testable without depending on how the test runner's +/// streams are wired. The probe is only called when `yes` is false. Public for +/// a caller whose own tests drive the confirmation path past this guard. +pub fn require_yes_or_interactive_with( yes: bool, action: &str, interactive: impl FnOnce() -> bool, diff --git a/crates/rocm-core/src/lib.rs b/crates/rocm-core/src/lib.rs index a8181620d0..6c5166401e 100644 --- a/crates/rocm-core/src/lib.rs +++ b/crates/rocm-core/src/lib.rs @@ -94,7 +94,9 @@ pub use config::{ SetupConfig, TELEMETRY_MODE_LOCAL, TELEMETRY_MODE_OFF, TelemetryConfig, WatcherMode, WatcherUserConfig, builtin_watcher, builtin_watchers, }; -pub use confirm::{interactive_terminal, require_yes_or_interactive}; +pub use confirm::{ + interactive_terminal, require_yes_or_interactive, require_yes_or_interactive_with, +}; pub use crypto::{ generate_rsa_signing_keypair, sign_rsa_pkcs1_sha256_signature, verify_rsa_pkcs1_sha256_signature, @@ -181,7 +183,9 @@ pub use net::{ read_http_response_bounded, write_all_tcp_stream, }; pub use paths::{ - AppPaths, CACHE_DIR_ENV, CONFIG_DIR_ENV, DATA_DIR_ENV, ENGINE_ENVS_ROOT_ENV, engine_plugin_dirs, + APP_PATH_SOURCES_ENV, AppPathSource, AppPathSources, AppPaths, CACHE_DIR_ENV, CONFIG_DIR_ENV, + DATA_DIR_ENV, ENGINE_ENVS_ROOT_ENV, ForwardedAppPathSources, PinnedAppPathSource, + engine_plugin_dirs, }; pub use proc_lifecycle::{ IdentityState, KillScope, MANAGED_STOP_GRACE, ProcessIdentity, RecordedPidOutcome, @@ -215,23 +219,26 @@ pub use rocm_install::{LegacyRocmSummary, detect_legacy_rocm_sdk, detect_legacy_ use rocm_install::{RocmInstall, discover_rocm_installs, rocm_install_version}; use runtime::env_path_override; pub use runtime::{ - RUNTIME_LIBRARY_PATH_ENV, RuntimeHost, RuntimePlatform, current_executable_path, - default_cache_dir, default_config_dir, default_data_dir, default_interactive_shell_program, - install_root_has_payload, managed_logs_dir, managed_pip_cache_dir, managed_runtime_cache_dir, - managed_runtime_data_root, managed_tools_dir, managed_uv_cache_dir, - normalize_runtime_path_for_host, normalize_runtime_path_for_storage, - normalize_runtime_path_text_for_host, normalize_runtime_path_text_for_platform, - normalize_runtime_path_text_for_storage, platform_binary_name, prepend_runtime_path, - resolve_path_through_symlinks, runtime_directory_label, runtime_drive_root_for_key, - runtime_drive_roots, runtime_exe_suffix, runtime_home_dir, runtime_install_root_is_protected, - runtime_is_linux, runtime_is_windows, runtime_os_name, runtime_path_for_child, - runtime_path_for_windows_child, runtime_path_is_same_or_inside, runtime_path_list_join, - runtime_path_list_split, runtime_path_sort_key, runtime_path_text_is_absolute_for_host, - runtime_path_text_is_absolute_for_platform, runtime_paths_equivalent, + ProtectedLocation, ROCM_CLI_ROOT_MARKER, RUNTIME_LIBRARY_PATH_ENV, RuntimeHost, + RuntimePlatform, UninstallRootVerdict, canonicalize_for_compare, create_marked_root, + current_executable_path, default_cache_dir, default_config_dir, default_data_dir, + default_interactive_shell_program, install_root_has_payload, managed_logs_dir, + managed_pip_cache_dir, managed_runtime_cache_dir, managed_runtime_data_root, managed_tools_dir, + managed_uv_cache_dir, mark_root, normalize_runtime_path_for_host, + normalize_runtime_path_for_storage, normalize_runtime_path_text_for_host, + normalize_runtime_path_text_for_platform, normalize_runtime_path_text_for_storage, + platform_binary_name, prepend_runtime_path, resolve_path_through_symlinks, + runtime_directory_label, runtime_drive_root_for_key, runtime_drive_roots, runtime_exe_suffix, + runtime_home_dir, runtime_is_linux, runtime_is_windows, runtime_os_name, + runtime_path_for_child, runtime_path_for_windows_child, runtime_path_is_same_or_inside, + runtime_path_list_join, runtime_path_list_split, runtime_path_sort_key, + runtime_path_text_is_absolute_for_host, runtime_path_text_is_absolute_for_platform, + runtime_paths_equivalent, runtime_protected_location, runtime_protected_location_for_home, runtime_python_activation_hint, runtime_python_activation_script, runtime_python_bin_dir_name, runtime_python_env_bin_dir, runtime_python_env_root_for_executable, runtime_python_executable_in_env, runtime_python_executable_name, - runtime_rocm_library_filename, shell_command_for_host, user_runtime_dir, + runtime_rocm_library_filename, shell_command_for_host, uninstall_root_verdict, + uninstall_system_roots, user_runtime_dir, windows_system_drive, }; pub use service_identity::{ServiceId, generate_service_id}; pub use service_record::{ diff --git a/crates/rocm-core/src/paths.rs b/crates/rocm-core/src/paths.rs index ee4a6f1a07..671c80ce24 100644 --- a/crates/rocm-core/src/paths.rs +++ b/crates/rocm-core/src/paths.rs @@ -9,15 +9,15 @@ //! and engine plugin directories. use anyhow::{Context, Result}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; use crate::runtime::env_path_override; use crate::runtime::{ - default_cache_dir, default_config_dir, default_data_dir, managed_runtime_cache_dir, - managed_runtime_data_root, normalize_runtime_path_for_host, + create_marked_root, default_cache_dir, default_config_dir, default_data_dir, + managed_runtime_cache_dir, managed_runtime_data_root, normalize_runtime_path_for_host, }; /// The `ROCM_CLI_*_DIR` overrides, one field per root, each `None` when unset. @@ -48,6 +48,139 @@ pub const DATA_DIR_ENV: &str = "ROCM_CLI_DATA_DIR"; /// The variable that moves the cache root. pub const CACHE_DIR_ENV: &str = "ROCM_CLI_CACHE_DIR"; +/// Where one of the [`AppPaths`] folders came from, so a message about it can +/// name the setting to change. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum AppPathSource { + /// An environment variable such as `ROCM_CLI_DATA_DIR`. + Env(String), + /// `setup.therock_venv` in the config file at this path. + TheRockVenv(PathBuf), + /// The platform default. + Default, +} + +impl AppPathSource { + /// Phrased to stand alone in parentheses. + #[must_use] + pub fn describe(&self) -> String { + match self { + Self::Env(name) => format!("set by {name}"), + Self::TheRockVenv(config) => { + format!("set by setup.therock_venv in {}", config.display()) + } + Self::Default => "the default location".to_owned(), + } + } +} + +/// Where each of the three [`AppPaths`] folders came from. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AppPathSources { + pub config: AppPathSource, + pub data: AppPathSource, + pub cache: AppPathSource, +} + +impl Default for AppPathSources { + fn default() -> Self { + Self { + config: AppPathSource::Default, + data: AppPathSource::Default, + cache: AppPathSource::Default, + } + } +} + +/// Carries [`AppPathSources`] from a `rocm` process to a `rocm` child it starts. +/// +/// A parent that runs `rocm` for the dashboard or the assistant pins the +/// child's folders with the three `ROCM_CLI_*_DIR` variables, so the child +/// would otherwise report every folder as "set by ROCM_CLI_*_DIR" — a setting +/// the user never made and cannot change. Each entry carries the folder it +/// describes, and the child takes it only while that folder's variable still +/// names exactly that folder — so a stale or hand-written value cannot rename +/// the source of a folder it does not describe. +pub const APP_PATH_SOURCES_ENV: &str = "ROCM_CLI_APP_PATH_SOURCES"; + +/// One folder's source, with the folder it applies to. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PinnedAppPathSource { + pub path: PathBuf, + pub source: AppPathSource, +} + +/// What a parent `rocm` passes in [`APP_PATH_SOURCES_ENV`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ForwardedAppPathSources { + pub config: PinnedAppPathSource, + pub data: PinnedAppPathSource, + pub cache: PinnedAppPathSource, +} + +impl ForwardedAppPathSources { + /// `paths` pinned with where each folder came from. + #[must_use] + pub fn for_paths(paths: &AppPaths) -> Self { + let sources = AppPathSources::for_paths(paths); + let pin = |path: &Path, source: AppPathSource| PinnedAppPathSource { + path: path.to_path_buf(), + source, + }; + Self { + config: pin(&paths.config_dir, sources.config), + data: pin(&paths.data_dir, sources.data), + cache: pin(&paths.cache_dir, sources.cache), + } + } +} + +impl AppPathSources { + /// Where `paths`' folders came from: discovery's answer for each folder + /// that discovery would choose today, and the variable that pins it for + /// any folder it would not (a caller-chosen folder the parent pins). + pub fn for_paths(paths: &AppPaths) -> Self { + let Ok((discovered, sources)) = AppPaths::discover_with_sources() else { + return Self::pinned(); + }; + let pick = |given: &Path, found: &Path, source: AppPathSource, var: &str| { + if given == found { + source + } else { + AppPathSource::Env(var.to_owned()) + } + }; + Self { + config: pick( + &paths.config_dir, + &discovered.config_dir, + sources.config, + "ROCM_CLI_CONFIG_DIR", + ), + data: pick( + &paths.data_dir, + &discovered.data_dir, + sources.data, + "ROCM_CLI_DATA_DIR", + ), + cache: pick( + &paths.cache_dir, + &discovered.cache_dir, + sources.cache, + "ROCM_CLI_CACHE_DIR", + ), + } + } + + fn pinned() -> Self { + Self { + config: AppPathSource::Env("ROCM_CLI_CONFIG_DIR".to_owned()), + data: AppPathSource::Env("ROCM_CLI_DATA_DIR".to_owned()), + cache: AppPathSource::Env("ROCM_CLI_CACHE_DIR".to_owned()), + } + } +} + impl AppPaths { /// The three `ROCM_CLI_*_DIR` variables that make a child process run on /// these roots, in the order config, data, cache. [`Self::discover`] reads @@ -69,6 +202,67 @@ impl AppPaths { } } + /// [`AppPaths::discover`], plus where each folder came from, decided by the + /// same rules: an environment variable wins; otherwise `setup.therock_venv` + /// moves the data folder, and the cache folder with it unless + /// `ROCM_CLI_CACHE_DIR` is set; otherwise the default. A folder pinned by + /// a parent `rocm` reports the source the parent passed in + /// [`APP_PATH_SOURCES_ENV`]. + pub fn discover_with_sources() -> Result<(Self, AppPathSources)> { + let config_overridden = env_path_override("ROCM_CLI_CONFIG_DIR").is_some(); + let data_overridden = env_path_override("ROCM_CLI_DATA_DIR").is_some(); + let cache_overridden = env_path_override("ROCM_CLI_CACHE_DIR").is_some(); + let paths = Self::discover()?; + // `discover` has already read the config and failed on one it cannot + // read, so this second read agrees with it. + let managed = + !data_overridden && matches!(configured_managed_root_from_config(&paths), Ok(Some(_))); + let from_venv = || AppPathSource::TheRockVenv(paths.config_path()); + let forwarded = std::env::var(APP_PATH_SOURCES_ENV) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()); + // Honoured only while the variable still names the folder the entry + // was written for. + let env_or_forwarded = + |var: &str, pick: fn(&ForwardedAppPathSources) -> &PinnedAppPathSource| { + let pinned = forwarded.as_ref().map(pick).filter(|pinned| { + env_path_override(var).is_some_and(|value| value == pinned.path) + }); + pinned.map_or_else( + || AppPathSource::Env(var.to_owned()), + |pinned| pinned.source.clone(), + ) + }; + let data = if data_overridden { + env_or_forwarded("ROCM_CLI_DATA_DIR", |f| &f.data) + } else if managed { + from_venv() + } else { + AppPathSource::Default + }; + let sources = AppPathSources { + config: if config_overridden { + env_or_forwarded("ROCM_CLI_CONFIG_DIR", |f| &f.config) + } else { + AppPathSource::Default + }, + cache: if cache_overridden { + env_or_forwarded("ROCM_CLI_CACHE_DIR", |f| &f.cache) + } else if data_overridden { + // With no cache setting of its own the cache folder follows + // the data folder (`from_overrides`), so the data folder's + // setting is what moved it. + data.clone() + } else if managed { + from_venv() + } else { + AppPathSource::Default + }, + data, + }; + Ok((paths, sources)) + } + /// Resolve the config, data and cache dirs from the environment and /// `config.json`. /// @@ -163,6 +357,7 @@ impl AppPaths { } pub fn ensure(&self) -> Result<()> { + self.ensure_marked_roots()?; for dir in [ &self.config_dir, &self.data_dir, @@ -183,6 +378,16 @@ impl AppPaths { Ok(()) } + /// The three roots first, each marked with [`ROCM_CLI_ROOT_MARKER`](crate::runtime::ROCM_CLI_ROOT_MARKER) if + /// this call creates it, so `rocm uninstall` can later recognise a root + /// outside the home folder as ROCm CLI's own. + fn ensure_marked_roots(&self) -> Result<()> { + for root in [&self.config_dir, &self.data_dir, &self.cache_dir] { + create_marked_root(root)?; + } + Ok(()) + } + pub fn engine_dir(&self, engine: &str) -> PathBuf { self.data_dir.join("engines").join(engine) } @@ -608,6 +813,7 @@ mod tests { use super::*; use crate::RocmCliConfig; + use crate::runtime::ROCM_CLI_ROOT_MARKER; use crate::test_support::temp_app_paths; /// `env_vars` and `discover` share one constant per name, so they cannot @@ -683,6 +889,30 @@ mod tests { Ok(()) } + /// `ensure` marks each of the three roots it creates, and leaves a root + /// that already existed unmarked: ROCm CLI did not create that one. + #[test] + fn ensure_marks_only_the_roots_it_creates() { + let (root, paths) = temp_app_paths("ensure-marks"); + fs::create_dir_all(&paths.config_dir).unwrap(); + paths.ensure().unwrap(); + let marked = |dir: &Path| dir.join(ROCM_CLI_ROOT_MARKER).is_file(); + let config = marked(&paths.config_dir); + let data = marked(&paths.data_dir); + let cache = marked(&paths.cache_dir); + // Running again does not mark the folder that was there first. + paths.ensure().unwrap(); + let config_again = marked(&paths.config_dir); + fs::remove_dir_all(root).ok(); + assert!(!config, "a pre-existing config folder was marked"); + assert!( + !config_again, + "a second ensure marked a folder it did not create" + ); + assert!(data, "the data folder ensure created is not marked"); + assert!(cache, "the cache folder ensure created is not marked"); + } + #[test] fn audit_events_path_lives_under_data_audit() { let (_root, paths) = temp_app_paths("audit-path"); diff --git a/crates/rocm-core/src/runtime.rs b/crates/rocm-core/src/runtime.rs index 6d3e8fbb39..9b61a2a5e9 100644 --- a/crates/rocm-core/src/runtime.rs +++ b/crates/rocm-core/src/runtime.rs @@ -570,14 +570,16 @@ fn split_runtime_path_anchor(value: &str, platform: RuntimePlatform) -> (&str, & /// `canonicalize` has nothing to resolve. /// /// This is NOT symlink-safe, and the gap is not merely theoretical. Because -/// [`runtime_install_root_is_protected`] exempts anything inside the user's +/// [`runtime_protected_location`] exempts anything inside the user's /// home before it consults the protected-root list, a symlink the user owns is /// enough: with `$HOME/link -> /etc`, the path `$HOME/link/child` is lexically /// inside home, so the guard reports it removable while the kernel lands in /// `/etc`. Resolving lexically is strictly better than the raw-text comparison /// it replaces — it closes every *spelling* of a protected path — but it does /// not close that hole, and closing it needs a decision about canonicalizing -/// the part of the path that does exist, which is a separate change. +/// the part of the path that does exist. `rocm uninstall`'s own roots close it +/// by judging where each folder really is as well (`uninstall_root_verdict` +/// on the resolved path); the runtime-folder rule here still does not. fn lexically_resolved_runtime_path_text(value: &str, platform: RuntimePlatform) -> String { let (anchor, rest) = split_runtime_path_anchor(value, platform); let anchored = !anchor.is_empty(); @@ -690,34 +692,418 @@ fn strip_managed_runtime_leaf(path: &Path) -> Option { runtimes_dir.parent().map(Path::to_path_buf) } -pub fn runtime_install_root_is_protected(path: &Path) -> bool { - let path = normalize_runtime_path_for_host(path); - if let Some(home) = runtime_home_dir() { - let home = normalize_runtime_path_for_host(&home); - if runtime_path_is_same_or_inside(&path, &home) && !runtime_paths_equivalent(&path, &home) { - return false; +/// Why a folder must never be recursively deleted by ROCm CLI. +/// +/// Returned by [`runtime_protected_location`] and [`uninstall_root_verdict`] +/// so a caller that refuses can say *why* from the same value it decided on, +/// instead of restating the rule. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProtectedLocation { + /// The top of a filesystem: `/`, or a drive root such as `C:\` on Windows. + FilesystemRoot, + /// The user's home folder itself. + Home, + /// A folder that contains the user's home folder, such as `/home`. + ContainsHome, + /// A system location (`/usr`, `/etc`, `C:\Windows`, ...). For runtime + /// folders this includes anything inside one of + /// [`runtime_protected_location`]'s roots; for `rocm uninstall`'s roots it + /// includes anything inside one of [`uninstall_root_verdict`]'s. + System, + /// Another user's home folder, or something inside one. + OtherUsersHome, + /// A folder many programs share, such as anything directly under `/` + /// (`/opt`, `/srv`), `/var/lib`, `/tmp`, or a mounted drive (`/mnt/d`). + SharedTopLevel, + /// A real directory outside the user's home that does not carry the + /// [`ROCM_CLI_ROOT_MARKER`] ROCm CLI writes into the roots it creates. + NotMarked, + /// A real directory whose location could not be resolved, so it cannot be + /// shown not to be one of the above. Only `rocm uninstall` reports this. + Unresolvable, +} + +impl ProtectedLocation { + /// What the folder is, phrased to follow "it is". + #[must_use] + pub const fn describe(self) -> &'static str { + match self { + Self::FilesystemRoot => "the top of the filesystem", + Self::Home => "your home folder", + Self::ContainsHome => "a folder that contains your home folder", + Self::System => "a protected system location", + Self::OtherUsersHome => "another user's home folder", + Self::SharedTopLevel => "a folder shared by other programs", + Self::NotMarked => "outside your home folder and not marked as ROCm CLI's own", + Self::Unresolvable => "a folder whose real location could not be resolved", } } +} - if runtime_is_windows() { - let system_roots = ["C:/Windows", "C:/Program Files", "C:/Program Files (x86)"]; - return system_roots - .iter() - .map(Path::new) - .any(|root| runtime_path_is_same_or_inside(&path, root)); +/// The file ROCm CLI writes into the roots it creates. +/// +/// Config, data and cache roots (and an SDK `--prefix`) get it, so +/// `rocm uninstall` can tell a folder of its own outside the home folder from +/// one that merely happens to be named. +pub const ROCM_CLI_ROOT_MARKER: &str = ".rocm-cli-root"; + +/// Create `dir` (and its parents), marking it if this call created it. +/// +/// The folder itself is made with `create_dir`, which fails when anything is +/// already there, so a folder someone else made — even a moment earlier — is +/// never marked: ROCm CLI did not create it and has no claim to remove it. A +/// failure to write the marker is only a warning (see [`mark_root`]). +pub fn create_marked_root(dir: &Path) -> Result<()> { + create_marked_root_with(dir, write_root_marker) +} + +fn create_marked_root_with( + dir: &Path, + write_marker: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result<()> { + if let Some(parent) = dir.parent().filter(|parent| !parent.as_os_str().is_empty()) { + std::fs::create_dir_all(parent) + .with_context(|| format!("failed to create {}", parent.display()))?; + } + match std::fs::create_dir(dir) { + Ok(()) => { + if let Err(error) = write_marker(dir) { + warn_root_unmarked(dir, &error); + } + Ok(()) + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && dir.is_dir() => Ok(()), + Err(error) => Err(error).with_context(|| format!("failed to create {}", dir.display())), } +} - if runtime_paths_equivalent(&path, Path::new("/")) { - return true; +/// Mark `dir`, which ROCm CLI has just created, as its own. +/// +/// Best effort: a marker that cannot be written is reported and otherwise +/// ignored. Failing the command would gain nothing — the folder would exist on +/// the next run and so never be marked — and an unmarked folder only means +/// `rocm uninstall` asks for the marker before removing it. +pub fn mark_root(dir: &Path) { + if let Err(error) = write_root_marker(dir) { + warn_root_unmarked(dir, &error); + } +} + +fn write_root_marker(dir: &Path) -> std::io::Result<()> { + std::fs::write( + dir.join(ROCM_CLI_ROOT_MARKER), + "This folder was created by ROCm CLI; `rocm uninstall` may remove it.\n", + ) +} + +fn warn_root_unmarked(dir: &Path, error: &std::io::Error) { + eprintln!( + "warning: could not write {} ({error}); `rocm uninstall` will ask for it before \ + removing {}", + dir.join(ROCM_CLI_ROOT_MARKER).display(), + dir.display() + ); +} + +/// Why `path` is protected, if it is, judged against the current user's home. +pub fn runtime_protected_location(path: &Path) -> Option { + runtime_protected_location_for_home(path, runtime_home_dir().as_deref()) +} + +/// [`runtime_protected_location`] with the home folder passed in, so a caller +/// (or a test) can judge a path against a home other than the process's own. +/// +/// Anything strictly inside `home` is never protected, so a user install under +/// `~/.rocm` stays removable even when home itself sits under a protected root +/// (`/root` for a root user). Home itself, and every folder that contains it, +/// is protected: removing either deletes everything the user owns. A `home` +/// that is itself a filesystem root grants no exemption, or it would exempt +/// every folder on the machine. Anything else inside a system location is +/// protected too. +pub fn runtime_protected_location_for_home( + path: &Path, + home: Option<&Path>, +) -> Option { + protected_location_on(path, home, RuntimePlatform::current()) +} + +const fn system_roots(platform: RuntimePlatform) -> &'static [&'static str] { + if platform.is_windows() { + &["C:/Windows", "C:/Program Files", "C:/Program Files (x86)"] + } else { + &[ + "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/opt", "/proc", "/root", "/sbin", + "/sys", "/usr", "/var", + ] + } +} + +/// What the user's own home folder says about a path, when it says anything. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HomeDecision { + /// Inside the home folder: removable. + Inside, + /// The home folder itself, or a folder containing it. + Refused(ProtectedLocation), +} + +/// The home-folder part of both rules: `None` when home does not decide. +fn own_home_decides_on( + path: &Path, + home: Option<&Path>, + platform: RuntimePlatform, +) -> Option { + let home = home.filter(|home| !is_filesystem_root_on(home, platform))?; + if runtime_paths_equivalent_on(path, home, platform) { + return Some(HomeDecision::Refused(ProtectedLocation::Home)); + } + if runtime_path_is_same_or_inside_on(path, home, platform) { + return Some(HomeDecision::Inside); + } + if runtime_path_is_same_or_inside_on(home, path, platform) { + return Some(HomeDecision::Refused(ProtectedLocation::ContainsHome)); + } + None +} + +fn protected_location_on( + path: &Path, + home: Option<&Path>, + platform: RuntimePlatform, +) -> Option { + if is_filesystem_root_on(path, platform) { + return Some(ProtectedLocation::FilesystemRoot); + } + match own_home_decides_on(path, home, platform) { + Some(HomeDecision::Inside) => return None, + Some(HomeDecision::Refused(why)) => return Some(why), + None => {} } + system_roots(platform) + .iter() + .map(Path::new) + .any(|root| runtime_path_is_same_or_inside_on(path, root, platform)) + .then_some(ProtectedLocation::System) +} + +/// What `rocm uninstall` may do with one of its config, data or cache roots. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UninstallRootVerdict { + /// Removable as it is: inside the user's own home. + Allowed, + /// Never removable. + Refused(ProtectedLocation), + /// Removable only if it carries [`ROCM_CLI_ROOT_MARKER`]: somewhere outside + /// the user's home that is none of the refused places (`/opt`, `/var`, + /// `/srv`, a second disk, ...). + NeedsMarker, +} + +/// The drive Windows is installed on (`C:` unless `SystemDrive` or `windir` +/// says otherwise). +#[must_use] +pub fn windows_system_drive() -> String { + let from_env = |name: &str| { + std::env::var(name) + .ok() + .and_then(|value| value.get(..2).map(str::to_owned)) + .filter(|drive| drive.as_bytes()[0].is_ascii_alphabetic() && drive.ends_with(':')) + }; + from_env("SystemDrive") + .or_else(|| from_env("windir")) + .unwrap_or_else(|| "C:".to_owned()) +} - [ - "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/opt", "/proc", "/root", "/sbin", - "/sys", "/usr", "/var", - ] - .iter() - .map(Path::new) - .any(|root| runtime_path_is_same_or_inside(&path, root)) +/// The locations `rocm uninstall` refuses at AND inside, as written. +#[must_use] +pub fn uninstall_system_roots() -> Vec { + uninstall_system_roots_on(RuntimePlatform::current(), &windows_system_drive()) +} + +fn uninstall_system_roots_on(platform: RuntimePlatform, system_drive: &str) -> Vec { + if platform.is_windows() { + [ + "Windows", + "Program Files", + "Program Files (x86)", + "ProgramData", + ] + .iter() + .map(|name| PathBuf::from(format!("{system_drive}/{name}"))) + .collect() + } else { + [ + "/usr", + "/etc", + "/boot", + "/bin", + "/sbin", + "/lib", + "/lib32", + "/lib64", + "/libx32", + "/sys", + "/proc", + "/dev", + "/run", + "/media", + "/snap", + "/mnt/wsl", + "/mnt/wslg", + ] + .iter() + .map(PathBuf::from) + .collect() + } +} + +/// Folders whose children are users' homes: `/home`, `/Users`, the system +/// drive's `Users`, and the folder the user's own home sits in (unless that is +/// a filesystem root, which would make every folder a "sibling"). +fn homes_parents_on( + home: Option<&Path>, + platform: RuntimePlatform, + system_drive: &str, +) -> Vec { + let mut parents = if platform.is_windows() { + vec![PathBuf::from(format!("{system_drive}/Users"))] + } else { + vec![PathBuf::from("/home"), PathBuf::from("/Users")] + }; + if let Some(parent) = home + .filter(|home| !is_filesystem_root_on(home, platform)) + .and_then(Path::parent) + .filter(|parent| !is_filesystem_root_on(parent, platform)) + { + parents.push(parent.to_path_buf()); + } + parents +} + +/// What `rocm uninstall` may do with the root `path`, judged against `home`. +/// +/// In order: `/` (or a drive root) is refused; the user's own home is refused, +/// as is any folder containing it, while anything inside it is allowed; the +/// [`uninstall_system_roots`] and anything inside them are refused, as are +/// `extra_system_roots` (the caller passes their resolved spellings, so +/// `/lib -> usr/lib` and `/usr/lib` are judged alike); another user's home or +/// anything inside one is refused; anything else needs the marker. +pub fn uninstall_root_verdict( + path: &Path, + home: Option<&Path>, + extra_system_roots: &[PathBuf], +) -> UninstallRootVerdict { + uninstall_root_verdict_on( + path, + home, + extra_system_roots, + RuntimePlatform::current(), + &windows_system_drive(), + ) +} + +fn uninstall_root_verdict_on( + path: &Path, + home: Option<&Path>, + extra_system_roots: &[PathBuf], + platform: RuntimePlatform, + system_drive: &str, +) -> UninstallRootVerdict { + use UninstallRootVerdict::{Allowed, NeedsMarker, Refused}; + if is_filesystem_root_on(path, platform) { + return Refused(ProtectedLocation::FilesystemRoot); + } + // Before the home allowance, so a home inside a system location (an odd + // HOME such as `/usr/sbin`) does not open that location up. + let parts = absolute_parts_on(path, platform); + if uninstall_system_roots_on(platform, system_drive) + .iter() + .chain(extra_system_roots) + .any(|root| runtime_path_is_same_or_inside_on(path, root, platform)) + || parts.as_deref().is_some_and(is_wsl_drive_system_folder) + { + return Refused(ProtectedLocation::System); + } + match own_home_decides_on(path, home, platform) { + Some(HomeDecision::Inside) => return Allowed, + Some(HomeDecision::Refused(why)) => return Refused(why), + None => {} + } + if !platform.is_windows() && parts.as_deref().is_some_and(is_shared_top_level) { + return Refused(ProtectedLocation::SharedTopLevel); + } + if homes_parents_on(home, platform, system_drive) + .iter() + .any(|parent| runtime_path_is_same_or_inside_on(path, parent, platform)) + || parts.as_deref().is_some_and(is_wsl_drive_users_folder) + { + return Refused(ProtectedLocation::OtherUsersHome); + } + NeedsMarker +} + +/// The components of an absolute path after `.`/`..` resolution, or `None` +/// for a relative one (which the caller judges again once resolved). +fn absolute_parts_on(path: &Path, platform: RuntimePlatform) -> Option> { + let resolved = comparable_runtime_path_text(path, platform); + let (anchor, rest) = split_runtime_path_anchor(&resolved, platform); + (!anchor.is_empty()).then(|| { + rest.split('/') + .filter(|part| !part.is_empty()) + .map(str::to_owned) + .collect() + }) +} + +/// Folders many programs share, refused rather than offered the marker: +/// anything directly under `/`, `/var/{lib,cache,log,tmp}`, and a mounted +/// drive or disk (`/mnt/`, as WSL mounts `C:` at `/mnt/c`). +fn is_shared_top_level(parts: &[String]) -> bool { + match parts { + [_] => true, + [first, second] if first == "var" => { + matches!(second.as_str(), "lib" | "cache" | "log" | "tmp") + } + [first, _] => first == "mnt", + _ => false, + } +} + +/// `/mnt/` as WSL mounts a Windows drive. +fn is_wsl_drive(parts: &[String]) -> bool { + parts.len() >= 2 + && parts[0] == "mnt" + && parts[1].len() == 1 + && parts[1].as_bytes()[0].is_ascii_alphabetic() +} + +/// A Windows system folder seen through WSL: `/mnt//Windows`, +/// `Program Files*` or `ProgramData`, or anything inside one. +fn is_wsl_drive_system_folder(parts: &[String]) -> bool { + is_wsl_drive(parts) + && parts.get(2).is_some_and(|folder| { + matches!( + folder.to_ascii_lowercase().as_str(), + "windows" | "program files" | "program files (x86)" | "programdata" + ) + }) +} + +/// Windows users' homes seen through WSL: `/mnt//Users` and below. +fn is_wsl_drive_users_folder(parts: &[String]) -> bool { + is_wsl_drive(parts) + && parts + .get(2) + .is_some_and(|folder| folder.eq_ignore_ascii_case("users")) +} + +/// `/`, a Windows drive root such as `C:/`, or a UNC share root: anchored, +/// with nothing above it once `.`, `..` and repeated separators are resolved +/// (`//..` is `/`). +fn is_filesystem_root_on(path: &Path, platform: RuntimePlatform) -> bool { + let resolved = comparable_runtime_path_text(path, platform); + let (anchor, rest) = split_runtime_path_anchor(&resolved, platform); + !anchor.is_empty() && rest.trim_matches('/').is_empty() } /// Whether an install root holds anything the install put there. @@ -879,6 +1265,15 @@ pub fn normalize_runtime_path_text_for_host(value: &str) -> String { normalize_runtime_path_text(value) } +/// `fs::canonicalize`, minus the verbatim `\\?\` prefix Windows adds. +/// +/// So the result compares with ordinary paths. For a path that exists; unlike +/// [`resolve_path_through_symlinks`] it resolves `..` through the filesystem. +pub fn canonicalize_for_compare(path: &Path) -> std::io::Result { + path.canonicalize() + .map(|resolved| crate::disk_space::strip_verbatim_prefix(&resolved)) +} + /// Resolve `path` to the real location on disk, keeping any trailing components /// that do not exist yet. /// @@ -1593,7 +1988,7 @@ mod tests { /// `windows_containment_sees_through_spelling_and_case` above exercises the /// Windows path-resolution rules from a Linux host, but only through the /// platform-parameterised helpers. The public gate itself, - /// [`runtime_install_root_is_protected`], still decides which protected-root + /// [`runtime_protected_location`], still decides which protected-root /// list to consult by reading [`runtime_is_windows()`] — a compile-time /// answer — so its Windows arm is reachable only when this binary is /// actually running on Windows. Not `#[cfg(unix)]`-gated, so it compiles @@ -1618,7 +2013,7 @@ mod tests { let accepted: Vec = spellings .into_iter() - .filter(|path| !runtime_install_root_is_protected(path)) + .filter(|path| runtime_protected_location(path).is_none()) .map(|path| path.display().to_string()) .collect(); @@ -1627,7 +2022,7 @@ mod tests { // ── Properties: the recursive-delete guard ───────────────────── // - // `runtime_install_root_is_protected` is the single source of truth for + // `runtime_protected_location` is the runtime-folder rule for // "may ROCm CLI `remove_dir_all` this folder?". Everything below states a // contract it must satisfy for EVERY spelling of a path, because the whole // point of the guard is that it is handed a path somebody (or something) @@ -1638,12 +2033,118 @@ mod tests { // Unix-only: the protected-root list the guard consults is the Unix one, // and `runtime_is_windows()` is decided at compile time, so the Windows // branch cannot be exercised from here. All pure and in-process. + /// A folder that already exists when ROCm CLI asks for it — even one + /// created a moment earlier by someone else — is not marked; one this call + /// creates is. A marker that cannot be written is a warning, not an error. + #[test] + fn create_marked_root_marks_only_what_it_creates_and_never_fails_on_the_marker() { + let root = std::env::temp_dir().join(format!( + "rocm-core-marked-root-{}-{}", + std::process::id(), + crate::unix_time_millis() + )); + let theirs = root.join("theirs"); + std::fs::create_dir_all(&theirs).unwrap(); + create_marked_root(&theirs).unwrap(); + let theirs_marked = theirs.join(ROCM_CLI_ROOT_MARKER).exists(); + + let ours = root.join("a").join("ours"); + create_marked_root(&ours).unwrap(); + let ours_marked = ours.join(ROCM_CLI_ROOT_MARKER).is_file(); + + let unwritable = root.join("unwritable"); + let outcome = + create_marked_root_with(&unwritable, |_| Err(std::io::Error::other("read-only"))); + let created = unwritable.is_dir(); + std::fs::remove_dir_all(&root).ok(); + + assert!(!theirs_marked, "a folder that already existed was marked"); + assert!(ours_marked, "the folder this call created is not marked"); + assert!( + outcome.is_ok(), + "a failed marker write failed the call: {outcome:?}" + ); + assert!(created); + } + + /// Serializes the tests that set `SystemDrive`/`windir`. + static SYSTEM_DRIVE_ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// The system drive comes from `SystemDrive`, then `windir`, then `C:`. + #[test] + fn windows_system_drive_reads_the_environment() { + let _guard = SYSTEM_DRIVE_ENV_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let drive = { + let _a = crate::test_env::RestoredEnvVar::set("SystemDrive", Path::new("D:")); + let _b = crate::test_env::RestoredEnvVar::set("windir", Path::new("E:\\Windows")); + windows_system_drive() + }; + let from_windir = { + let _a = crate::test_env::RestoredEnvVar::set("SystemDrive", Path::new("")); + let _b = crate::test_env::RestoredEnvVar::set("windir", Path::new("E:\\Windows")); + windows_system_drive() + }; + let fallback = { + let _a = crate::test_env::RestoredEnvVar::set("SystemDrive", Path::new("not a drive")); + let _b = crate::test_env::RestoredEnvVar::set("windir", Path::new("")); + windows_system_drive() + }; + assert_eq!(drive, "D:"); + assert_eq!(from_windir, "E:"); + assert_eq!(fallback, "C:"); + } + + /// The drive root is the filesystem root on Windows, judged from any + /// host, in every spelling; on Linux `C:/` is an ordinary relative name. + /// The system drive is a parameter, not a fixed `C:`. Not `cfg(unix)`: + /// the platform is a parameter, so this runs on every lane. + #[test] + fn windows_roots_follow_the_system_drive() { + use UninstallRootVerdict::{Allowed, NeedsMarker, Refused}; + let windows = RuntimePlatform::Windows; + for root in ["C:/", "C:\\", "c:/", "C:/Windows/..", "//server/share/"] { + assert!(is_filesystem_root_on(Path::new(root), windows), "{root}"); + } + for not_root in ["C:/Windows", "//server/share/dir"] { + assert!( + !is_filesystem_root_on(Path::new(not_root), windows), + "{not_root}" + ); + } + assert!(!is_filesystem_root_on( + Path::new("C:/"), + RuntimePlatform::Linux + )); + let home = Some(Path::new("D:/Users/alice")); + for (path, expected) in [ + ("C:\\", Refused(ProtectedLocation::FilesystemRoot)), + ("D:/Windows/System32", Refused(ProtectedLocation::System)), + ( + "d:/program files (x86)/x", + Refused(ProtectedLocation::System), + ), + ("D:/ProgramData/rocm", Refused(ProtectedLocation::System)), + ("D:/Users/bob", Refused(ProtectedLocation::OtherUsersHome)), + ("D:/Users/alice/rocm", Allowed), + ("C:/Windows/rocm", NeedsMarker), + ("E:/rocm-cli", NeedsMarker), + ] { + assert_eq!( + uninstall_root_verdict_on(Path::new(path), home, &[], windows, "D:"), + expected, + "{path}" + ); + } + } + #[cfg(unix)] mod delete_guard_properties { use super::*; use proptest::prelude::*; - /// The Unix roots `runtime_install_root_is_protected` refuses, restated + /// The Unix roots `runtime_protected_location` refuses, restated /// here so a property compares the guard against the policy rather than /// against itself. const PROTECTED_ROOTS: [&str; 13] = [ @@ -1673,7 +2174,7 @@ mod tests { /// property of the generators, not of this function's logic, so it is /// asserted rather than merely assumed — a generator change that starts /// seeding relative text would otherwise desync the oracle from - /// `runtime_install_root_is_protected` (which does handle relative + /// `runtime_protected_location` (which does handle relative /// paths) without a single property failing to say so. fn lexically_resolved(path: &str) -> String { assert!( @@ -1751,7 +2252,7 @@ mod tests { let reported: Vec<(String, bool)> = spellings .into_iter() .map(|text| { - let protected = runtime_install_root_is_protected(Path::new(&text)); + let protected = runtime_protected_location(Path::new(&text)).is_some(); (text, protected) }) .collect(); @@ -1863,7 +2364,7 @@ mod tests { prop_assume!(lexically_protected(&text)); prop_assert!( - runtime_install_root_is_protected(Path::new(&text)), + runtime_protected_location(Path::new(&text)).is_some(), "{text} resolves to {} but was reported removable", lexically_resolved(&text) ); @@ -1884,7 +2385,7 @@ mod tests { prop_assume!(exempt_as_user_owned(&text)); prop_assert!( - !runtime_install_root_is_protected(Path::new(&text)), + runtime_protected_location(Path::new(&text)).is_none(), "{text} resolves to {} but was refused", lexically_resolved(&text) ); @@ -1921,6 +2422,379 @@ mod tests { ); } + /// The runtime-folder rule against an oracle restated from its + /// policy: `/` is the filesystem root; home is home; anything + /// strictly inside home is free; a folder containing home protects + /// it; otherwise the system list and everything inside it decides. + /// Home is drawn too, including `/` (which must exempt nothing). + #[test] + fn the_runtime_rule_agrees_with_its_policy_for_any_home( + text in path_text(proptest::sample::select(policy_seeds())), + home in proptest::sample::select(policy_homes()), + ) { + let resolved = lexically_resolved(&text); + prop_assert_eq!( + runtime_protected_location_for_home(Path::new(&text), Some(Path::new(&home))), + runtime_policy(&resolved, &home), + "{} resolves to {}, home {}", text, resolved, home + ); + } + + /// `rocm uninstall`'s rule against an oracle restated from its + /// policy (see [`uninstall_policy`]), over seeds that include other + /// users' homes, `/mnt` drives, `/run`, `/srv`, `/usr/local` and + /// deeper system descendants, for several homes, and with extra + /// (resolved) system roots drawn too. + #[test] + fn the_uninstall_rule_agrees_with_its_policy_for_any_home( + text in path_text(proptest::sample::select(policy_seeds())), + home in proptest::sample::select(policy_homes()), + extras in proptest::sample::subsequence( + vec!["/opt/vendor", "/var/opt", "/srv/shared"], + 0..=3, + ), + ) { + let resolved = lexically_resolved(&text); + let extra_roots: Vec = extras.iter().map(PathBuf::from).collect(); + prop_assert_eq!( + uninstall_root_verdict_on( + Path::new(&text), + Some(Path::new(&home)), + &extra_roots, + RuntimePlatform::Linux, + "C:", + ), + uninstall_policy(&resolved, &home, &extras), + "{} resolves to {}, home {}, extras {:?}", text, resolved, home, extras + ); + } + } + + const FIXED_HOME: &str = "/home/alice"; + + /// Restated from the policy, not imported from the code under test. + const UNINSTALL_SYSTEM: [&str; 17] = [ + "/usr", + "/etc", + "/boot", + "/bin", + "/sbin", + "/lib", + "/lib32", + "/lib64", + "/libx32", + "/sys", + "/proc", + "/dev", + "/run", + "/media", + "/snap", + "/mnt/wsl", + "/mnt/wslg", + ]; + + fn policy_homes() -> Vec { + [FIXED_HOME, "/", "/root", "/var/lib/svc", "/usr/sbin"] + .map(str::to_owned) + .to_vec() + } + + fn policy_seeds() -> Vec { + let mut seeds: Vec = PROTECTED_ROOTS + .iter() + .chain(UNINSTALL_SYSTEM.iter()) + .map(|root| (*root).to_owned()) + .collect(); + seeds.extend( + [ + "/", + "/home", + FIXED_HOME, + "/home/alice/.rocm", + "/home/alicex", + "/home/bob", + "/Users/carol", + "/mnt", + "/mnt/c", + "/mnt/c/Windows/System32", + "/mnt/d/Program Files/x", + "/mnt/c/Users/bob", + "/mnt/d/rocm", + "/mnt/data/rocm", + "/usr/local", + "/usr/sbin/x", + "/usr/lib/x86_64-linux-gnu", + "/etc/ssl/certs", + "/var/lib", + "/var/log", + "/var/tmp/rocm", + "/var/lib/svc/.rocm", + "/var/lib/postgres", + "/var/cache/rocm-cli", + "/var/opt/x", + "/opt", + "/opt/rocm-cli", + "/opt/vendor/x", + "/srv/rocm", + "/srv/shared/x", + "/tmp", + "/tmp/rocm", + ] + .map(str::to_owned), + ); + seeds + } + + /// The home-folder part of both policies, for resolved absolute text. + /// `None`: home does not decide. `Some(Ok(()))`: inside home, allowed. + /// `Some(Err(why))`: refused because of home. + fn home_policy(resolved: &str, home: &str) -> Option> { + if home == "/" { + return None; + } + if resolved == home { + return Some(Err(ProtectedLocation::Home)); + } + if lexically_same_or_inside(resolved, home) { + return Some(Ok(())); + } + if home.starts_with(&format!("{resolved}/")) { + return Some(Err(ProtectedLocation::ContainsHome)); + } + None + } + + fn runtime_policy(resolved: &str, home: &str) -> Option { + if resolved == "/" { + return Some(ProtectedLocation::FilesystemRoot); + } + if let Some(verdict) = home_policy(resolved, home) { + return verdict.err(); + } + PROTECTED_ROOTS + .iter() + .any(|root| lexically_same_or_inside(resolved, root)) + .then_some(ProtectedLocation::System) + } + + /// In order: `/` is refused; the system list (and any extra resolved + /// system roots) is refused at and inside, before any home allowance; + /// your home and anything holding it are refused, anything inside it + /// is allowed; shared top-level folders (directly under `/`, + /// `/var/{lib,cache,log,tmp}`, `/mnt/`) are refused; other users' + /// homes (under `/home`, `/Users`, beside your own, or a WSL drive's + /// `Users`) are refused; anything else needs the marker. A WSL drive's + /// Windows system folders count as system locations. + fn uninstall_policy(resolved: &str, home: &str, extras: &[&str]) -> UninstallRootVerdict { + use UninstallRootVerdict::{Allowed, NeedsMarker, Refused}; + if resolved == "/" { + return Refused(ProtectedLocation::FilesystemRoot); + } + let parts: Vec<&str> = resolved + .split('/') + .filter(|part| !part.is_empty()) + .collect(); + let wsl_drive = parts.len() >= 2 + && parts[0] == "mnt" + && parts[1].len() == 1 + && parts[1].chars().all(|c| c.is_ascii_alphabetic()); + let wsl_folder = |names: &[&str]| { + wsl_drive + && parts + .get(2) + .is_some_and(|folder| names.contains(&folder.to_ascii_lowercase().as_str())) + }; + if UNINSTALL_SYSTEM + .iter() + .chain(extras.iter()) + .any(|root| lexically_same_or_inside(resolved, root)) + || wsl_folder(&[ + "windows", + "program files", + "program files (x86)", + "programdata", + ]) + { + return Refused(ProtectedLocation::System); + } + if let Some(verdict) = home_policy(resolved, home) { + return verdict.map_or_else(Refused, |()| Allowed); + } + let shared = parts.len() == 1 + || (parts.len() == 2 + && (parts[0] == "mnt" + || (parts[0] == "var" + && ["lib", "cache", "log", "tmp"].contains(&parts[1])))); + if shared { + return Refused(ProtectedLocation::SharedTopLevel); + } + let mut homes_parents = vec!["/home".to_owned(), "/Users".to_owned()]; + if home != "/" { + let parent = home.rsplit_once('/').map_or("/", |(parent, _)| parent); + if !parent.is_empty() && parent != "/" { + homes_parents.push(parent.to_owned()); + } + } + if homes_parents + .iter() + .any(|parent| lexically_same_or_inside(resolved, parent)) + || wsl_folder(&["users"]) + { + return Refused(ProtectedLocation::OtherUsersHome); + } + NeedsMarker + } + + /// One example per class, so each stays named even if the generator + /// is retuned. + #[test] + fn each_uninstall_class_is_decided_as_the_policy_says() { + use UninstallRootVerdict::{Allowed, NeedsMarker, Refused}; + let home = Some(Path::new(FIXED_HOME)); + for (path, expected) in [ + ("/", Refused(ProtectedLocation::FilesystemRoot)), + ("/home/alice", Refused(ProtectedLocation::Home)), + ("/home", Refused(ProtectedLocation::ContainsHome)), + ("/home/alice/.rocm/data", Allowed), + ("/usr/local", Refused(ProtectedLocation::System)), + ("/etc/ssl", Refused(ProtectedLocation::System)), + ("/usr/lib", Refused(ProtectedLocation::System)), + ("/run/user/1000", Refused(ProtectedLocation::System)), + ("/mnt/c/Windows", Refused(ProtectedLocation::System)), + ("/mnt/wsl/x", Refused(ProtectedLocation::System)), + ("/opt", Refused(ProtectedLocation::SharedTopLevel)), + ("/srv", Refused(ProtectedLocation::SharedTopLevel)), + ("/tmp", Refused(ProtectedLocation::SharedTopLevel)), + ("/mnt", Refused(ProtectedLocation::SharedTopLevel)), + ("/mnt/d", Refused(ProtectedLocation::SharedTopLevel)), + ("/var/lib", Refused(ProtectedLocation::SharedTopLevel)), + ("/var/log", Refused(ProtectedLocation::SharedTopLevel)), + ("/home/bob", Refused(ProtectedLocation::OtherUsersHome)), + ("/Users/carol/x", Refused(ProtectedLocation::OtherUsersHome)), + ( + "/mnt/c/Users/bob", + Refused(ProtectedLocation::OtherUsersHome), + ), + ("/mnt/d/rocm", NeedsMarker), + ("/var/lib/rocm-cli", NeedsMarker), + ("/opt/rocm-cli", NeedsMarker), + ("/tmp/rocm", NeedsMarker), + ] { + assert_eq!( + uninstall_root_verdict_on( + Path::new(path), + home, + &[], + RuntimePlatform::Linux, + "C:" + ), + expected, + "{path}" + ); + } + // Beside a home that is not under /home: still another user's. + assert_eq!( + uninstall_root_verdict_on( + Path::new("/srv/users/bob"), + Some(Path::new("/srv/users/alice")), + &[], + RuntimePlatform::Linux, + "C:" + ), + Refused(ProtectedLocation::OtherUsersHome) + ); + // A home inside a system location does not open it up. + assert_eq!( + uninstall_root_verdict_on( + Path::new("/usr/sbin/x"), + Some(Path::new("/usr/sbin")), + &[], + RuntimePlatform::Linux, + "C:" + ), + Refused(ProtectedLocation::System) + ); + // A resolved spelling of a system root the caller passes in is + // refused like the root itself (`/mnt -> var/mnt` on Silverblue + // makes `/var/mnt` the real `/mnt`; `/lib -> usr/lib` likewise). + assert_eq!( + uninstall_root_verdict_on( + Path::new("/var/usr-real/lib"), + home, + &[PathBuf::from("/var/usr-real")], + RuntimePlatform::Linux, + "C:" + ), + Refused(ProtectedLocation::System) + ); + } + + /// The cases the issue reported, plus the root-user and root-home + /// shapes, pinned as examples. + #[test] + fn home_and_its_ancestors_are_named_for_what_they_are() { + let home = Some(Path::new(FIXED_HOME)); + let cases: [(&str, Option); 11] = [ + ("/", Some(ProtectedLocation::FilesystemRoot)), + ("//", Some(ProtectedLocation::FilesystemRoot)), + ("//..", Some(ProtectedLocation::FilesystemRoot)), + ("/home/alice", Some(ProtectedLocation::Home)), + ("/home/alice/", Some(ProtectedLocation::Home)), + ("/home/alice/.rocm/..", Some(ProtectedLocation::Home)), + ("/home", Some(ProtectedLocation::ContainsHome)), + ("/home/alice/.cache", None), + ("/home/alicex", None), + ("/usr/local", Some(ProtectedLocation::System)), + ("/tmp/rocm", None), + ]; + for (path, expected) in cases { + assert_eq!( + runtime_protected_location_for_home(Path::new(path), home), + expected, + "{path}" + ); + } + } + + /// Root's home sits under a protected root; it is refused as a home, + /// and what is inside it stays removable. + #[test] + fn a_root_users_home_is_refused_as_a_home() { + let home = Some(Path::new("/root")); + assert_eq!( + runtime_protected_location_for_home(Path::new("/root"), home), + Some(ProtectedLocation::Home) + ); + assert_eq!( + runtime_protected_location_for_home(Path::new("/root/.rocm"), home), + None + ); + } + + /// A home of `/` must not exempt the whole machine. + #[test] + fn a_home_at_the_filesystem_root_exempts_nothing() { + let home = Some(Path::new("/")); + assert_eq!( + runtime_protected_location_for_home(Path::new("/etc"), home), + Some(ProtectedLocation::System) + ); + assert_eq!( + runtime_protected_location_for_home(Path::new("/"), home), + Some(ProtectedLocation::FilesystemRoot) + ); + } + + /// The public gate refuses the real home, which it used to report as + /// removable. + #[test] + fn the_public_gate_refuses_the_users_own_home() { + let home = runtime_home_dir().expect("a home directory"); + assert!( + runtime_protected_location(&home).is_some(), + "{}", + home.display() + ); } } } diff --git a/crates/rocm-dash-tui/src/app/slash.rs b/crates/rocm-dash-tui/src/app/slash.rs index a5ef8ff8e9..f0ae9ecdfb 100644 --- a/crates/rocm-dash-tui/src/app/slash.rs +++ b/crates/rocm-dash-tui/src/app/slash.rs @@ -236,19 +236,26 @@ impl AppState { )); } else { let real = saw_apply; - let argv: Vec<&str> = if real { - vec!["uninstall"] - } else { - vec!["uninstall", "--dry-run"] - }; - self.slash_tool = Some(rocm_cmd_request( - &argv, - if real { - "uninstall" - } else { - "uninstall --dry-run" - }, - )); + let mut argv: Vec<&str> = vec!["uninstall"]; + // The `--keep-*` flags (and `--force-dev-binaries`) pass + // through, in both modes: a + // refused uninstall's advice is to re-run with one, and a + // dashboard that dropped it could never follow that advice. + argv.extend(flags.iter().copied().filter(|flag| { + matches!( + *flag, + "--keep-binaries" + | "--keep-config" + | "--keep-data" + | "--keep-cache" + | "--force-dev-binaries" + ) + })); + if !real { + argv.push("--dry-run"); + } + let label = argv.join(" "); + self.slash_tool = Some(rocm_cmd_request(&argv, label)); } } "setup" => { @@ -1149,6 +1156,64 @@ mod tests { ); } + /// A refused uninstall advises `Re-run with --keep-`. Both the + /// preview and the real run must carry that flag to the CLI, or the advice + /// cannot be followed from the dashboard. (That the flag then clears the + /// refusal is proven against the CLI: `rocm`'s + /// `in_process_uninstall_dry_run_honours_the_advised_keep_flag` and the + /// `uninstall-17` E2E scenario.) + #[test] + fn slash_uninstall_passes_keep_flags_through() { + let mut s = st(); + assert_eq!( + s.handle_slash_command("/uninstall --keep-data"), + SlashOutcome::Handled + ); + let req = s.slash_tool.take().expect("a dry-run request"); + assert_eq!( + req.args, + serde_json::json!({ "args": ["uninstall", "--keep-data", "--dry-run"] }) + ); + assert_eq!(req.label, "uninstall --keep-data --dry-run"); + + assert_eq!( + s.handle_slash_command("/uninstall --apply --keep-data --keep-cache"), + SlashOutcome::Handled + ); + let req = s.slash_tool.take().expect("a real request"); + assert_eq!( + req.args, + serde_json::json!({ "args": ["uninstall", "--keep-data", "--keep-cache"] }) + ); + + // Every flag the CLI takes is passed on, in the order typed. + assert_eq!( + s.handle_slash_command( + "/uninstall --keep-binaries --keep-config --keep-data --keep-cache" + ), + SlashOutcome::Handled + ); + let req = s.slash_tool.take().expect("a dry-run request"); + assert_eq!( + req.args, + serde_json::json!({ "args": [ + "uninstall", "--keep-binaries", "--keep-config", "--keep-data", + "--keep-cache", "--dry-run" + ] }) + ); + + // `--force-dev-binaries` is passed on too, not silently dropped. + assert_eq!( + s.handle_slash_command("/uninstall --apply --force-dev-binaries"), + SlashOutcome::Handled + ); + let req = s.slash_tool.take().expect("a real request"); + assert_eq!( + req.args, + serde_json::json!({ "args": ["uninstall", "--force-dev-binaries"] }) + ); + } + #[test] fn slash_uninstall_conflicting_flags_is_guided() { let mut s = st(); diff --git a/docs/architecture.md b/docs/architecture.md index 124a86c6e7..580fc40fec 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -126,9 +126,9 @@ Each per-crate module inventory lists one file per line. Flat inventories (every - [`therock/wheel_plan.rs`](../apps/rocm/src/therock/wheel_plan.rs) — full domain extraction, a leaf child of `therock.rs` (split out of `install_wheel_runtime`) that builds on `therock/python.rs` and `therock/resolve.rs` for the Python decision and the resolution it prints: the `sdk install` plan a wheel install prints, key by key. `WheelPlan` carries the facts, `write_wheel_plan` writes the lines a preview and a real install share, and `write_dry_run_tail` the lines only a preview adds (the `uv` commands it would run and the manifest path). `PlanStack` is the one place the plan differs: `Resolved` carries the package specs, runtime key, install folder and manifest path, and `NeedsUv` (a ROCm 10 preview on a host with no `uv`, see `UnresolvedPipRuntime` in `therock/resolve/wheel.rs`) prints those as `not resolved by this preview` and adds the `resolution_note:` line, so one writer serves both and a line the plan gains appears in both. `unresolved_wheel_preview` renders the second kind whole. `therock.rs` reads it through `pub(super)` items; it reads the provenance, host-note and `venv_python_path` helpers back from `therock.rs`. - [`therock/update.rs`](../apps/rocm/src/therock/update.rs) — full domain extraction, a child of `therock.rs` that builds on `therock/family.rs`, `therock/process.rs`, `therock/python.rs`, `therock/resolve.rs`, `therock/source.rs` and `therock/version.rs`, on [`runtime_registry.rs`](../apps/rocm/src/runtime_registry.rs) for the manifests and on rocm-core's [`atomic_write.rs`](../crates/rocm-core/src/atomic_write.rs) for the startup-check record (split out of `therock.rs`): whether an installed runtime has something newer, and the bounded startup check that asks. `runtime_update_plan` resolves the latest source for one runtime, and `runtime_update_check` does the same for a caller that changes nothing (the report, the JSON, the startup check and an apply's preview): given a wheel runtime that records no usable Python, the plan prepares a managed Python (an apply needs one) while the check works the wheel tag out from the interpreter the layout requires and carries a `python_note` instead (`resolve_latest_for_manifest` re-resolves a wheel runtime through `resolve_pip_runtime_with_timeout` and a tarball one through `resolve_tarball_artifact_with_timeout`, on the layout `manifest_source_layout` reads back from the manifest) and `runtime_freshness` classifies it (`RuntimeFreshness`: up to date, update available, repair available when the installed composition is not the one a fresh install would record, or ahead of the index) into a `RuntimeUpdatePlan`. `render_update_report` and `render_update_json` (the form the dashboard's update check parses) present the plans, and `maybe_refresh_startup_update_check` keeps one `StartupUpdateCheckRecord` in the cache so the check runs at most once every twelve hours, under a two-second download timeout. `runtime_key` and `wheel_runtime_key`, which name the install a plan targets, stay in `therock.rs`; whether a replacement's root is installed is `rocm_core::install_root_has_payload`. `render_update_report`, `render_update_json`, `runtime_update_plan`, `runtime_update_check` and `maybe_refresh_startup_update_check` are `pub(crate)` and, with `RuntimeUpdatePlan`, which [`update_cmd.rs`](../apps/rocm/src/update_cmd.rs) reads its verdict from, re-exported by `therock.rs`; `RuntimeFreshness`, `runtime_freshness` and `select_startup_update_manifest` are `pub(super)` for the version property tests, and the rest is private. - [`therock/test_support.rs`](../apps/rocm/src/therock/test_support.rs) — test-only (`#[cfg(test)]`), a child of `therock.rs`: fixtures shared by the `therock` child modules' tests and the tests left in `therock.rs` (`test_paths`, `test_runtime_manifest`, `write_test_runtime_manifest`, `family_for_test`, and `RestoredEnv`, which sets or removes process environment variables for one test and puts them back on drop, so a caller holds `PROCESS_ENV_TEST_LOCK` for as long as it holds one). Separate from the crate-level [`test_support.rs`](../apps/rocm/src/test_support.rs), which holds the fixtures every module's tests share, such as `PROCESS_ENV_TEST_LOCK` and the background-helper fixtures `runtime_state` and `set_helper_facts`. -- [`tool_policy.rs`](../apps/rocm/src/tool_policy.rs) — the chat assistant's tool-call policy: which `rocm` commands and bridge tools a model may request, which run immediately and which need the user's approval first. It owns `ChatRocmCommandAction` (read-only, or approval with the titles the approval prompt shows) and `ChatToolApprovalRequest`, the validators (`validate_chat_tool_call`, the `validate_chat_*_tool_call` family, `validate_required_chat_string`, `validate_optional_chat_integer`, `reject_control_characters_in_tool_arguments` (which refuses a model-supplied tool name or argument carrying a terminal control character, for every tool except `rocm_command`, whose argv `normalized_chat_rocm_command_args` screens entry by entry), `validate_serve_command_safety`, the four rules a model-proposed `serve` must satisfy (no public bind, no CPU device, a loopback host, `--managed` without `--foreground`), and `validate_chat_rocm_command_safety`, which applies them to a `serve` argv and also refuses a system install folder (`chat_install_prefix_is_system`)), the classifiers (`chat_rocm_command_action`, `chat_rocm_command_action_from_args`, `chat_install_driver_action`, `canonicalize_chat_rocm_command`, `normalized_chat_rocm_command_args`, `chat_tool_call_is_read_only`), `chat_tool_approval_request`, and the readers that turn a tool call into its argv and one-line command (`rocm_chat_tool_requested_args`, `rocm_chat_tool_requested_command`, with `push_optional_json_cli_arg` and `json_string`). It moved verbatim from `chat.rs` with the tests that exercise only these items. It depends on [`rocm_argv.rs`](../apps/rocm/src/rocm_argv.rs), `providers::ChatToolCall`, `service_launch::is_loopback_host`, `services_text::validate_service_id`, `shell_quote::has_terminal_control_character`, `therock::RuntimeVersionSelector` and `driver_install::host_install_driver_only_reports`, none of which imports `chat`, so `freeform_planner.rs` calls `validate_serve_command_safety` and `validate_chat_rocm_command_safety` here instead of through `chat`, and keeps no copy of the serve rules. `chat.rs`'s child modules call into it and `chat.rs` re-exports `validate_chat_tool_call`, `chat_tool_call_is_read_only` and `chat_tool_approval_request` (read by `dash_seam.rs`), and `ChatRocmCommandAction`, `chat_install_driver_action`, `chat_rocm_command_action_from_args` and `rocm_chat_tool_requested_args`, which only other modules' tests read as `crate::chat::` (`driver_plan.rs`, `system_packages.rs`). -- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns types: `uninstall()`, the refusal of the hidden `--force` (`reject_force`, which `main.rs` calls from the `uninstall` dispatch arm), plus the installer `PATH` undo, the removal of the fish completion script the Linux installer recorded writing (`plan_completion_removals`, which takes only a regular `completions/rocm.fish` whose first line is the installer's marker naming this install folder, tied to `install.sh` by a test; `execute_plan` rechecks the file before removing it and reports a removal failure as a warning instead of stopping, for the `SHELL_COMPLETIONS_KIND` plan entries it adds), and running-executable deletion. The shared plan type and its file-removal helpers live in [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) below instead, because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them too. The two modules depend on each other: `uninstall_plan.rs` reads this module's `pub(crate)` `PathEdit`, `PATH_EDIT_RECORD`, `plan_path_edits`, `plan_is_empty`, `removal_count` and `render_extra_plan`. -- [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) — mechanical relocation, shares crate-visible types (Phase 6f, ROCMAI-212): the uninstall-plan types (`UninstallOptions`, `UninstallPlan`, `UninstallPlanEntry`), the `PlanAudience` a rendered plan is written for (a person at a terminal, a captured caller, or the assistant's preview), which decides what the dry-run footer says comes next, building the plan (`build_uninstall_plan`, `plan_installed_binaries`, and the installed-binary/shared-cache discovery helpers behind them), rendering it (`render_uninstall_dry_run`, which renders for the assistant, and `render_uninstall_plan`), the `[y/N]` confirmation prompt (`confirm_uninstall`), and the filesystem removal primitive both [`uninstall.rs`](../apps/rocm/src/uninstall.rs) and [`storage.rs`](../apps/rocm/src/storage.rs) call to carry a plan out (`remove_path`, and the entry-resolution helpers behind it). Kept separate from `uninstall.rs` rather than folded into it, since `uninstall.rs`'s own doc comment and name both describe `uninstall()`'s exclusive logic (the installer `PATH` undo and running-executable deletion), while this module's plan/render/removal helpers are shared with `storage.rs`. `main.rs` (`UninstallOptions`), `uninstall.rs` (which also imports `PlanAudience` and picks it from `interactive_terminal`), `storage.rs`, `runtimes_cmd.rs`, `chat/mcp_bridge.rs` (which calls `render_uninstall_dry_run` and does not import `PlanAudience`), and [`deletion_properties.rs`](../apps/rocm/src/deletion_properties.rs) (Unix-only property tests, which render as `PlanAudience::Captured`) each import the subset of these `pub(crate)` types and helpers they need; see this module's own doc comment for which symbol each one uses. +- [`tool_policy.rs`](../apps/rocm/src/tool_policy.rs) — the chat assistant's tool-call policy: which `rocm` commands and bridge tools a model may request, which run immediately and which need the user's approval first. It owns `ChatRocmCommandAction` (read-only, or approval with the titles the approval prompt shows) and `ChatToolApprovalRequest`, the validators (`validate_chat_tool_call`, the `validate_chat_*_tool_call` family, `validate_required_chat_string`, `validate_optional_chat_integer`, `reject_control_characters_in_tool_arguments` (which refuses a model-supplied tool name or argument carrying a terminal control character, for every tool except `rocm_command`, whose argv `normalized_chat_rocm_command_args` screens entry by entry), `validate_serve_command_safety`, the four rules a model-proposed `serve` must satisfy (no public bind, no CPU device, a loopback host, `--managed` without `--foreground`), and `validate_chat_rocm_command_safety`, which applies them to a `serve` argv and also refuses a protected install folder and says why (`chat_install_prefix_protection`)), the classifiers (`chat_rocm_command_action`, `chat_rocm_command_action_from_args`, `chat_install_driver_action`, `canonicalize_chat_rocm_command`, `normalized_chat_rocm_command_args`, `chat_tool_call_is_read_only`), `chat_tool_approval_request`, and the readers that turn a tool call into its argv and one-line command (`rocm_chat_tool_requested_args`, `rocm_chat_tool_requested_command`, with `push_optional_json_cli_arg` and `json_string`). It moved verbatim from `chat.rs` with the tests that exercise only these items. It depends on [`rocm_argv.rs`](../apps/rocm/src/rocm_argv.rs), `providers::ChatToolCall`, `service_launch::is_loopback_host`, `services_text::validate_service_id`, `shell_quote::has_terminal_control_character`, `therock::RuntimeVersionSelector` and `driver_install::host_install_driver_only_reports`, none of which imports `chat`, so `freeform_planner.rs` calls `validate_serve_command_safety` and `validate_chat_rocm_command_safety` here instead of through `chat`, and keeps no copy of the serve rules. `chat.rs`'s child modules call into it and `chat.rs` re-exports `validate_chat_tool_call`, `chat_tool_call_is_read_only` and `chat_tool_approval_request` (read by `dash_seam.rs`), and `ChatRocmCommandAction`, `chat_install_driver_action`, `chat_rocm_command_action_from_args` and `rocm_chat_tool_requested_args`, which only other modules' tests read as `crate::chat::` (`driver_plan.rs`, `system_packages.rs`). +- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns types: `uninstall()`, the refusal of the hidden `--force` (`reject_force`, which `main.rs` calls from the `uninstall` dispatch arm), `run_uninstall_plan` (refuse, confirm through rocm-core's `require_yes_or_interactive_with`, remove) and `apply_uninstall_plan` (the one step that deletes; it refuses a plan with a protected root on its own and checks each entry again before anything changes, a fish completion script by its own softer rule), plus the installer `PATH` undo, the removal of the fish completion script the Linux installer recorded writing (`plan_completion_removals`, which takes only a regular `completions/rocm.fish` whose first line is the installer's marker naming this install folder, tied to `install.sh` by a test; `execute_plan` rechecks the file before removing it and reports a removal failure as a warning instead of stopping, for the `SHELL_COMPLETIONS_KIND` plan entries it adds), and running-executable deletion. The shared plan type and its file-removal helpers live in [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) below instead, because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them too. The two modules depend on each other: `uninstall_plan.rs` reads this module's `pub(crate)` `PathEdit`, `PATH_EDIT_RECORD`, `plan_path_edits`, `plan_is_empty`, `removal_count` and `render_extra_plan`; this module reads `uninstall_plan.rs`'s `PlannedAs` and `entry_path` to check each entry again before removing it. +- [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) — mechanical relocation, shares crate-visible types (Phase 6f, ROCMAI-212): the uninstall-plan types (`UninstallOptions`, `UninstallPlan`, `UninstallPlanEntry`, `PlannedAs`, `RefusedRoot`), the `PlanAudience` a rendered plan is written for (a person at a terminal, a captured caller, or the assistant's preview), which decides what the dry-run footer says comes next, building the plan (`build_uninstall_plan`, `plan_installed_binaries`, `judge_uninstall_root`, which refuses a protected config/data/cache root into `UninstallPlan::refused`, and the installed-binary/shared-cache discovery helpers behind them), rendering it (`render_uninstall_dry_run`, which renders for the assistant, and `render_uninstall_plan`), the `[y/N]` confirmation prompt (`confirm_uninstall`), and the filesystem removal primitive both [`uninstall.rs`](../apps/rocm/src/uninstall.rs) and [`storage.rs`](../apps/rocm/src/storage.rs) call to carry a plan out (`remove_path`, and the entry-resolution helpers behind it). Kept separate from `uninstall.rs` rather than folded into it, since `uninstall.rs`'s own doc comment and name both describe `uninstall()`'s exclusive logic (the installer `PATH` undo and running-executable deletion), while this module's plan/render/removal helpers are shared with `storage.rs`. `main.rs` (`UninstallOptions`), `uninstall.rs` (which also imports `PlanAudience` and picks it from `interactive_terminal`), `storage.rs`, `runtimes_cmd.rs`, `chat/mcp_bridge.rs` (which calls `render_uninstall_dry_run` and does not import `PlanAudience`), and [`deletion_properties.rs`](../apps/rocm/src/deletion_properties.rs) (Unix-only property tests, which render as `PlanAudience::Captured`) each import the subset of these `pub(crate)` types and helpers they need; see this module's own doc comment for which symbol each one uses. - [`update_cmd.rs`](../apps/rocm/src/update_cmd.rs) — mechanical relocation, dispatch-adjacent, no owned types (Phase 6f, ROCMAI-210): `rocm update`'s command handler (`update()`, the body of the `update` arm of `dispatch()`) and its rendering/activation logic — the read-only status report (`render_update_text`, `append_update_surfaces`), the predicate deciding whether `update` should route into the mutating path instead of that report (`update_should_preview_or_apply`), applying a runtime update (`apply_runtime_update`, a thin wrapper that hands `apply_runtime_update_with` the check and the plan from `therock/update.rs`, so a unit test can run the choice between them on any platform; `append_update_activate_summary`), and the update-source/installed-runtime pickers behind it (`select_runtime_update_source`, `select_installed_update_runtime`). `const ROLLBACK_RECOVERY_HINT` stays in `main.rs` as a shared crate-root constant, because callers outside this module also use it ([`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs)'s `RuntimesCommand::Activate` handler and [`runtime_install_finalize.rs`](../apps/rocm/src/runtime_install_finalize.rs)'s `render_sdk_install_success`); this module reaches it via its `use crate::{...};` import, the same way `gpu_policy.rs`'s `device_policy_name` stays in `main.rs`. `update()` is `pub(crate)` and called from [`main.rs`](../apps/rocm/src/main.rs)'s `dispatch()` through a re-import (`use crate::update_cmd::update;`), and calls `update_should_preview_or_apply`, `apply_runtime_update` and `render_update_text` itself; `render_update_text` is also `pub(crate)` and read from [`chat/mcp_bridge.rs`](../apps/rocm/src/chat/mcp_bridge.rs) (the read-only `rocm update` handling), while `apply_runtime_update` and `update_should_preview_or_apply` keep the `pub(crate)` they had when `dispatch()` called them directly, though only `update()` calls them now; `select_runtime_update_source` is also `pub(crate)`, read from [`therock_version_proptests.rs`](../apps/rocm/src/therock_version_proptests.rs)'s property tests via `crate::update_cmd::select_runtime_update_source`. `append_update_surfaces`, `append_update_activate_summary`, and `select_installed_update_runtime` have no callers outside this module and stay private. The cluster's regression tests live in `update_cmd.rs`'s own `mod tests`, reaching shared fixtures (`test_paths`, `test_runtime_manifest_for_update`, `write_test_pip_runtime`) through `crate::tests::`/`crate::test_support::` the same way other mechanically relocated modules do. Further `apps/rocm` modules, not part of the `main.rs` split: diff --git a/docs/manual-testing.md b/docs/manual-testing.md index a2eb7dd454..47e379c1e1 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -1556,3 +1556,99 @@ anything. Finally, `rocm diagnose --report --model /:Q4_K_M --context-size 8192` prints the report with no model section, and stderr says that `--model, --context-size were ignored` and nothing about the model was fetched. + +## 13. Uninstall Safety + +Run these in a throwaway home on Linux or WSL, never against your real one, and +only with `--dry-run` where the step says so. Each block starts a fresh sandbox: + +```bash +export SANDBOX=$(mktemp -d) +export HOME=$SANDBOX/users/home ROCM_CLI_CONFIG_DIR=$SANDBOX/users/home/.rocm/config \ + ROCM_CLI_DATA_DIR=$SANDBOX/users/home/.rocm/data ROCM_CLI_CACHE_DIR=$SANDBOX/users/home/.rocm/cache +mkdir -p "$HOME/Documents" "$ROCM_CLI_CONFIG_DIR" +echo keep > "$HOME/Documents/keep.txt" +``` + +A protected data folder is refused (dry run only): + +```bash +ROCM_CLI_DATA_DIR=/ rocm uninstall --dry-run --keep-binaries +``` + +Expected result: the review lists `data: / is the top of the filesystem (set +by ROCM_CLI_DATA_DIR)` under "Refused", never under the items to remove, ends +with `This uninstall would be refused. Point ROCM_CLI_DATA_DIR at a folder of +ROCm CLI's own, or re-run with --keep-data ...`, and the command exits +non-zero. + +The home folder as the data folder is refused for real, and the advised flag +works: + +```bash +ROCM_CLI_DATA_DIR=$HOME rocm uninstall --yes --keep-binaries +ROCM_CLI_DATA_DIR=$HOME rocm uninstall --yes --keep-binaries --keep-data +``` + +Expected result: the first command exits non-zero with `uninstall refused, +nothing was removed: the data folder is your home folder (set by +ROCM_CLI_DATA_DIR) ...`, and `$HOME/Documents/keep.txt` and the config folder +are both still there. The second exits 0, removes the config folder, and leaves +`keep.txt` alone. + +The same holds when the setting does not spell out the home folder: + +```bash +(cd "$HOME" && ROCM_CLI_DATA_DIR=. rocm uninstall --yes --keep-binaries) +``` + +Expected result: exit non-zero with `the data folder . is your home folder +(set by ROCM_CLI_DATA_DIR; resolves to )`, and `keep.txt` is still there. + +In the dashboard, `/uninstall --keep-data` previews and `/uninstall --apply +--keep-data` runs the uninstall with the data folder left out; with +`ROCM_CLI_DATA_DIR=$HOME` the preview no longer reports a refusal. With +`setup.therock_venv` pointing at the home folder instead (and +`ROCM_CLI_DATA_DIR` unset), the dashboard's refusal names +`setup.therock_venv`, not `ROCM_CLI_DATA_DIR`, and leads with `--keep-data`. + +A folder outside the home folder needs ROCm CLI's marker: + +```bash +mkdir -p "$SANDBOX/srv/rocm" +ROCM_CLI_DATA_DIR=$SANDBOX/srv/rocm rocm uninstall --dry-run --keep-binaries +touch "$SANDBOX/srv/rocm/.rocm-cli-root" +ROCM_CLI_DATA_DIR=$SANDBOX/srv/rocm rocm uninstall --dry-run --keep-binaries +``` + +Expected result: the first preview refuses the data folder as `outside your +home folder and not marked as ROCm CLI's own` and names the +`.rocm-cli-root` file to create; after creating it, the second lists the data +folder for removal. A system folder such as `/usr/local`, or a shared one such +as `/var/lib` or `/opt`, is refused in a dry run whatever is in it, and the +refusal does not offer the marker. + +A shared cache inside the cache folder is named as deleted (dry run): + +```bash +mkdir -p "$HOME/.cache/uv" "$HOME/.cache/huggingface/hub" +ROCM_CLI_CACHE_DIR=$HOME/.cache rocm uninstall --dry-run --keep-binaries +``` + +Expected result: under "Please review", `the uv package cache WILL BE DELETED` +and `downloaded model files WILL BE DELETED`, each naming the cache folder and +`--keep-cache`. With the default cache folder the same two caches are reported +as `not removed` instead. + +A symlinked cache folder written with a trailing slash is unlinked, not +emptied: + +```bash +mkdir -p "$SANDBOX/real-cache" && touch "$SANDBOX/real-cache/keep" +ln -s "$SANDBOX/real-cache" "$SANDBOX/rocm-cache" +ROCM_CLI_CACHE_DIR=$SANDBOX/rocm-cache/ \ + rocm uninstall --yes --keep-binaries --keep-config --keep-data +``` + +Expected result: exit 0, `removed cache /rocm-cache`, the link is +gone, and `real-cache/keep` is still there. diff --git a/docs/testing.md b/docs/testing.md index 099e834a28..255c9dacdb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1748,6 +1748,29 @@ The default is 256 cases; `ROCM_DELETION_PROP_CASES` raises it for a deeper local run, and a lower value is ignored. They are Unix-only because they plant symlinks. +The uninstall properties also point roots at the sandbox's own home folder +(directly, relative to the working directory, through `..`, and through a +symlinked parent folder) and plant shared caches inside and outside the +removed roots. They check that a +protected root refuses the whole uninstall and removes nothing, that no file +ROCm CLI did not create is deleted, and that the review says a shared cache +WILL BE DELETED exactly when the removal deletes it. + +The protected-location rules live in `rocm-core` and are property-tested +there against oracles restated from each policy, over seeds that include other +users' homes, `/mnt`, `/run`, `/srv`, `/usr/local` and deeper system +descendants, for several homes (including `/`). Runtime folders are refused +inside the runtime system list; `rocm uninstall`'s roots are refused inside its +own list (checked before any home allowance), at shared top-level folders and +mounted drives, and in other users' homes, and need the `.rocm-cli-root` +marker anywhere else outside home: + +```bash +cargo test -p rocm-core --lib runtime::tests::delete_guard_properties +cargo test -p rocm --bin rocm uninstall_ +cargo test -p rocm --bin rocm shared_cache +``` + The `uninstall-NN` E2E scenarios (`features/uninstall.feature`) check the same behaviour through the built binary, confined to the scenario's own folder, including a folder that cannot be checked stopping the uninstall before @@ -1760,7 +1783,7 @@ empty plan even at one, name no next step (`uninstall-08`, `uninstall-09`). A mistyped `--force` is refused with a pointer to `--yes`, and a near miss of it is not answered with `--force-dev-binaries` (`uninstall-10`); the help starts its examples with a dry run (`uninstall-11`). The assistant's uninstall preview -ends differently, since it has no flag to offer: it says removal needs approval, +ends differently, since it has no command line to offer: it says removal needs approval, which `lifecycle_read_mutate_split_is_honest` in [tool_policy.rs](../apps/rocm/src/tool_policy.rs) backs. `uninstall-13` to `uninstall-15` drive the confirmation prompt under a pseudo-terminal, which is the only way to reach it, and pin the shared `[y/N]` @@ -1769,6 +1792,14 @@ with Ctrl-D, and for a plain no, each together with the config folder being left in place. They run on the default mock lane; the helper's other callers (`rocm fix`, the SDK-overwrite prompt) share it and are covered by its unit tests in [confirm.rs](../crates/rocm-core/src/confirm.rs). +`uninstall-16` to `uninstall-21` cover the protected-location refusal, each +asserting the message together with the folders it leaves: the top of the +filesystem as the data folder (`uninstall-16`), the home folder, with the +advised `--keep-data` then succeeding (`uninstall-17`), shared caches inside the +cache folder named as deleted (`uninstall-18`), a data folder of `.` run from +home (`uninstall-19`), an unmarked folder outside home cleared by the marker +the refusal names (`uninstall-20`), and the dashboard's approved-command path +naming `setup.therock_venv` (`uninstall-21`). The `uninstall` command does not start the file logger, which would otherwise create the data folder's `logs` folder before the plan is built: diff --git a/engines/vllm/src/install.rs b/engines/vllm/src/install.rs index 26453cb1ac..0baf492bc8 100644 --- a/engines/vllm/src/install.rs +++ b/engines/vllm/src/install.rs @@ -525,8 +525,7 @@ fn vllm_rocm10_discover_remaining_install_args( /// need the same `ignore-error-codes` treatment here. There is no CLI flag or /// env var for it, only this config file. fn write_vllm_index_uv_config(paths: &AppPaths, build: &VllmRocmDiscoverBuild) -> Result { - std::fs::create_dir_all(&paths.cache_dir) - .with_context(|| format!("failed to create {}", paths.cache_dir.display()))?; + rocm_core::create_marked_root(&paths.cache_dir)?; let path = paths.cache_dir.join("vllm-rocm10-uv.toml"); let contents = format!( "[[index]]\nurl = \"{}\"\nignore-error-codes = [403]\n", diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 147f0455e3..1e8e2b2f19 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -7,8 +7,10 @@ Feature: Uninstall # the mock lane every PR. # # Every scenario passes --keep-binaries (the binary under test must survive) - # and points HOME, the uv cache and the Hugging Face cache at the scenario's - # own folder, so an uninstall can never reach the runner's shared caches. + # and points HOME, the cache folder, the uv cache and the Hugging Face cache + # at the scenario's own folder, so an uninstall can never reach the runner's + # shared caches. The one setting that names a folder outside it, a data + # folder of `/`, is only ever previewed with --dry-run. # # The link scenarios are Linux-only, and the behaviour they pin is only # claimed for Linux: on Windows a directory symlink or junction needs @@ -187,3 +189,71 @@ Feature: Uninstall Then the uninstall is reported as cancelled And the user is not told the answer was misunderstood And the config folder still holds the user's files + + # Linux-only: on Windows `/` names the current drive's root and renders as + # `\`, so this line would read differently. The Windows drive-root refusal is + # covered only by rocm-core's `a_windows_drive_root_is_the_filesystem_root` + # unit test, not end to end. + @id:uninstall-filesystem-root-refused @requires-os:linux + Scenario: uninstall-16 - A data folder set to the top of the filesystem is refused + Given the data folder is set to the top of the filesystem + When the user previews an uninstall + Then the uninstall is refused because the data folder "/" is "the top of the filesystem" + And the refusal names ROCM_CLI_DATA_DIR as where the data folder came from + And the refusal advises re-running with --keep-data + + @id:uninstall-home-refused-nothing-removed + Scenario: uninstall-17 - A data folder set to the home folder is refused, nothing is removed, and the advised flag works + Given the data folder is set to the user's home folder, which holds the user's files + When the user uninstalls + Then the uninstall is refused because the data folder "" is "your home folder" + And the refusal says nothing was removed + And the refusal advises re-running with --keep-data + And the user's files in the home folder are still there + And the config folder is still there + When the user uninstalls again with the flag the refusal advised + Then the uninstall succeeds + And the user's files in the home folder are still there + And the config folder is gone + + @id:uninstall-shared-cache-inside-root-warned + Scenario: uninstall-18 - Shared caches inside the cache folder are named as deleted before anything is removed + Given the cache folder is set to the user's own cache folder, which holds the uv and model caches + When the user previews an uninstall + Then the review warns that the uv and model caches will be deleted with the cache folder + And the uv cache is still there after the preview + + # The text of `.` is not the home folder, but the folder it names is. Linux- + # only like uninstall-01/-02 in what it claims: the resolution goes through + # the same symlink-following call, which nothing verifies on Windows. + @id:uninstall-dot-from-home-refused @requires-os:linux + Scenario: uninstall-19 - A data folder of `.` run from the home folder is refused and nothing is removed + Given the data folder is set to `.`, and the user is in their home folder, which holds their files + When the user uninstalls from their home folder + Then the refusal says the data folder "." resolves to the home folder + And the refusal says nothing was removed + And the user's files in the home folder are still there + And the config folder is still there + + # A real folder outside the home folder is only removed when ROCm CLI marked + # it as its own. The refusal says how to mark it; doing so clears it. + # Linux-only: on Windows the scenario root sits inside the runner's own user + # folder, where a folder outside the scenario home is another user's home. + @id:uninstall-unmarked-folder-refused-until-marked @requires-os:linux + Scenario: uninstall-20 - A data folder outside home without ROCm CLI's marker is refused until the advised marker exists + Given the data folder is a folder outside the home folder without ROCm CLI's marker + When the user previews an uninstall + Then the refusal advises creating the marker if the folder is ROCm CLI's + When the user creates the marker the refusal named + And the user previews an uninstall + Then the preview plans to remove the data folder + + # The dashboard and the assistant run an approved `rocm uninstall` as a + # child process with the folders pinned. The refusal must still name the + # setting the folder really came from. + @id:uninstall-dashboard-names-the-real-setting + Scenario: uninstall-21 - From the dashboard, a refusal names setup.therock_venv rather than a pinned variable + Given setup.therock_venv points at the user's home folder, which holds their files + When the dashboard runs an approved uninstall + Then the refusal names setup.therock_venv and advises --keep-data, not a variable the user never set + And the user's files in the home folder are still there diff --git a/tests/e2e-cucumber/tests/e2e/lifecycle_steps.rs b/tests/e2e-cucumber/tests/e2e/lifecycle_steps.rs index aa3d3d0fd4..5e579498ac 100644 --- a/tests/e2e-cucumber/tests/e2e/lifecycle_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/lifecycle_steps.rs @@ -689,10 +689,13 @@ async fn given_capture_user_path(world: &mut E2eWorld) { /// Seed isolated config/data/cache dirs with a marker so the installed-binary /// smoke can prove the CLI reads only them, not the real user state. fn seed_isolated_dirs(world: &mut E2eWorld) { - let root = root(world); - let config = root.join("smoke-config"); - let data = root.join("smoke-data"); - let cache = root.join("smoke-cache"); + // Inside the isolated HOME, where ROCm CLI's folders normally live: a + // folder beside HOME counts as another user's home to `rocm uninstall`, + // which refuses it whatever it holds. + let home = state(world).home_dir.clone(); + let config = home.join("smoke-config"); + let data = home.join("smoke-data"); + let cache = home.join("smoke-cache"); for dir in [&config, &data, &cache] { std::fs::create_dir_all(dir).expect("failed to create isolated smoke dir"); std::fs::write(dir.join("state-marker"), "seeded by the scenario\n") diff --git a/tests/e2e-cucumber/tests/e2e/runtime_steps.rs b/tests/e2e-cucumber/tests/e2e/runtime_steps.rs index 1bf377b496..78b014dd3b 100644 --- a/tests/e2e-cucumber/tests/e2e/runtime_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/runtime_steps.rs @@ -42,7 +42,13 @@ fn linked_runtimes_target(world: &E2eWorld) -> std::path::PathBuf { .path() .join("data") .join("real-runtimes"); - let resolved = real.canonicalize().unwrap_or(real); + canonical_without_verbatim(&real) +} + +/// `path` canonicalized, minus the verbatim `\\?\` prefix Windows adds (see +/// [`linked_runtimes_target`] for why), or `path` itself if it cannot be. +pub(crate) fn canonical_without_verbatim(path: &std::path::Path) -> std::path::PathBuf { + let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); let text = resolved.to_string_lossy(); if let Some(rest) = text.strip_prefix(r"\\?\UNC\") { return std::path::PathBuf::from(format!(r"\\{rest}")); diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 49a16b9436..c4c96609ca 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -5,10 +5,13 @@ //! Steps for `rocm uninstall` and the folders its plan removes. //! //! Black-box against the real binary. Every run is confined to the scenario's -//! isolated root: `--keep-binaries` so the binary under test survives, and HOME, -//! `UV_CACHE_DIR` and `HF_HOME` pointed inside the root so no uninstall can reach -//! a shared cache the runner keeps between scenarios. +//! isolated root: `--keep-binaries` so the binary under test survives, and +//! HOME, the cache folder, `UV_CACHE_DIR` and `HF_HOME` pointed inside the root +//! so no uninstall can reach a shared cache the runner keeps between +//! scenarios. The one setting that names a folder outside the root, a data +//! folder of `/`, is only ever used with `--dry-run`. +use std::ffi::OsString; use std::path::{Path, PathBuf}; use cucumber::{given, then, when}; @@ -36,16 +39,146 @@ fn link_target(world: &E2eWorld) -> PathBuf { root(world).join("relocated-cache") } -/// A real config folder in the isolated root, holding a file of the user's. +/// The scenario's config folder (absent until a step or the CLI creates it). fn config_dir(world: &E2eWorld) -> PathBuf { - root(world).join("rocm-config") + config_dir_at(root(world)) } -/// A cache setting the kernel cannot check: its parent is a link to itself. -fn looping_cache(world: &E2eWorld) -> PathBuf { - root(world).join("loop").join("cache") +/// Inside the scenario's home, where ROCm CLI's folders normally live: on +/// Windows the scenario root is itself under `C:\\Users\\`, so a folder +/// outside the scenario home would count as another user's home there. +fn config_dir_at(root: &Path) -> PathBuf { + home_at(root).join(".rocm").join("config") +} + +fn home_at(root: &Path) -> PathBuf { + root.join("users").join("home") +} + +/// The scenario's own HOME. +fn home(world: &E2eWorld) -> PathBuf { + // One level down, so the scenario's config/data/cache folders are not + // siblings of HOME (which `rocm uninstall` treats as other users' homes). + root(world).join("users").join("home") +} + +fn user_file_in_home(world: &E2eWorld) -> PathBuf { + home(world).join("Documents").join(USER_FILE) +} + +/// The scenario's config folder, as ROCm CLI would have left it: created by +/// the CLI and so carrying the marker that lets `rocm uninstall` remove a +/// folder outside the home folder. +fn plant_config_rocm_cli_created(world: &E2eWorld) { + let config = config_dir(world); + std::fs::create_dir_all(&config).expect("failed to create config"); + std::fs::write(config.join(".rocm-cli-root"), "created by ROCm CLI\n") + .expect("failed to mark config"); +} + +fn set_env(world: &mut E2eWorld, key: &'static str, value: impl Into) { + world.command_env.retain(|(existing, _)| *existing != key); + world.command_env.push((key, value.into())); +} + +/// The environment every run here gets: HOME (and USERPROFILE, which is where +/// Windows finds it), the config, data and cache folders, the uv cache and the +/// Hugging Face cache, all inside the scenario's own folder, so nothing a run +/// resolves can reach the runner's shared caches. A Given step overrides one +/// through `world.command_env`, which is kept (not consumed) so a scenario can +/// re-run the command with different flags. +fn isolated_env(world: &E2eWorld) -> Vec<(&'static str, OsString)> { + let root = root(world).to_path_buf(); + let home = home(world); + std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); + let mut env: Vec<(&'static str, OsString)> = vec![ + ("HOME", home.clone().into_os_string()), + // Windows reads the home folder from USERPROFILE first. + ("USERPROFILE", home.into_os_string()), + // Not the world's folders: the harness pre-creates those (so they are + // not ones ROCm CLI created, and carry no marker), and on CI its cache + // can be shared across scenarios, while an uninstall removes the cache + // folder. These start absent, as on a machine before ROCm CLI ran. + ("ROCM_CLI_CONFIG_DIR", config_dir_at(&root).into_os_string()), + ( + "ROCM_CLI_DATA_DIR", + home_at(&root).join(".rocm").join("data").into_os_string(), + ), + ( + "ROCM_CLI_CACHE_DIR", + home_at(&root).join(".rocm").join("cache").into_os_string(), + ), + ("UV_CACHE_DIR", root.join("uv-cache").into_os_string()), + ("HF_HOME", root.join("hf-home").into_os_string()), + ]; + for (key, value) in &world.command_env { + env.retain(|(existing, _)| existing != key); + env.push((key, value.clone())); + } + env +} + +/// [`isolated_env`] as text, for the pseudo-terminal runner. +fn isolated_env_text(world: &E2eWorld) -> Vec<(&'static str, String)> { + isolated_env(world) + .into_iter() + .map(|(key, value)| (key, value.to_string_lossy().into_owned())) + .collect() +} + +/// Run `rocm uninstall --keep-binaries ` confined to the scenario root. +fn run_uninstall(world: &mut E2eWorld, flags: &[&str]) { + run_uninstall_in(world, flags, None); +} + +/// [`run_uninstall`] with the working directory set, for a relative setting. +fn run_uninstall_in(world: &mut E2eWorld, flags: &[&str], cwd: Option<&Path>) { + let mut args = vec!["uninstall", "--keep-binaries"]; + args.extend_from_slice(flags); + assert_keeps_binaries(&args); + run_command_in(world, &args, cwd); +} + +/// Run `rocm ` confined to the scenario root (see [`isolated_env`]). +fn run_command_in(world: &mut E2eWorld, args: &[&str], cwd: Option<&Path>) { + let env = isolated_env(world); + let binary = crate::rocm_binary(); + let mut cmd = std::process::Command::new(&binary); + cmd.args(args); + if let Some(cwd) = cwd { + cmd.current_dir(cwd); + } + world.isolate_cmd(&mut cmd); + for (key, value) in env { + cmd.env(key, value); + } + let output = cmd + .output() + .unwrap_or_else(|e| panic!("failed to run {binary}: {e}")); + let rc = output.status.code().unwrap_or(-1); + let stdout = String::from_utf8_lossy(&output.stdout).to_string(); + crate::record_command(world.current_scenario.as_deref(), args, rc, &stdout); + world.cli_output = Some(stdout); + world.cli_stderr = Some(String::from_utf8_lossy(&output.stderr).to_string()); + world.cli_rc = Some(rc); } +/// Run `rocm` under a pseudo-terminal, confined to the scenario's folders like +/// every other uninstall here, so the command sees a terminal on both streams as +/// a person typing it would. +fn spawn_at_terminal(world: &E2eWorld, args: &[&str]) -> TuiSession { + assert_keeps_binaries(args); + let env = isolated_env_text(world); + let env = env + .iter() + .map(|(key, value)| (*key, value.as_str())) + .collect::>(); + TuiSession::spawn_with_env(world, args, &env) + .unwrap_or_else(|e| panic!("failed to run {args:?} at a terminal: {e}")) +} + +// ── Given ────────────────────────────────────────────────────────── + #[given("the cache folder is a link to another folder holding the user's files")] async fn cache_is_live_link(world: &mut E2eWorld) { let target = link_target(world); @@ -64,6 +197,11 @@ async fn cache_is_dangling_link(world: &mut E2eWorld) { E2eWorld::link_directory(&gone, &cache_link(world)).expect("failed to plant cache link"); } +/// A cache setting the kernel cannot check: its parent is a link to itself. +fn looping_cache(world: &E2eWorld) -> PathBuf { + root(world).join("loop").join("cache") +} + #[given("the config folder holds the user's files")] async fn config_holds_user_files(world: &mut E2eWorld) { let config = config_dir(world); @@ -77,99 +215,95 @@ async fn cache_behind_looping_link(world: &mut E2eWorld) { E2eWorld::link_directory(&looping, &looping).expect("failed to plant looping link"); } -/// HOME, the uv cache and the Hugging Face cache inside the scenario's own -/// folder, so nothing a run resolves can reach the runner's shared caches. -fn isolated_env(world: &E2eWorld) -> Vec<(&'static str, String)> { - let root = root(world); - let home = root.join("home"); - std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); - vec![ - ("HOME", home.display().to_string()), - ("UV_CACHE_DIR", root.join("uv-cache").display().to_string()), - ("HF_HOME", root.join("hf-home").display().to_string()), - ] +#[given("the data folder is set to the top of the filesystem")] +async fn data_is_filesystem_root(world: &mut E2eWorld) { + set_env(world, "ROCM_CLI_DATA_DIR", "/"); } -fn run_uninstall(world: &mut E2eWorld, keep: &[&str], settings: &[(&str, &str)]) { - run_uninstall_with(world, true, keep, settings); +#[given("the data folder is set to the user's home folder, which holds the user's files")] +async fn data_is_home(world: &mut E2eWorld) { + let file = user_file_in_home(world); + std::fs::create_dir_all(file.parent().expect("parent")).expect("failed to create home"); + std::fs::write(&file, "user data").expect("failed to write user file"); + // The config folder exists too, so a refusal that still removed the other + // roots would show. + plant_config_rocm_cli_created(world); + let home = home(world); + set_env(world, "ROCM_CLI_DATA_DIR", home); } -/// `confirmed: false` leaves `--yes` off, so the run reaches the confirmation -/// gate; the harness gives the binary no terminal, which is the case the gate -/// has to refuse. -fn run_uninstall_with( - world: &mut E2eWorld, - confirmed: bool, - keep: &[&str], - settings: &[(&str, &str)], -) { - let mut args = vec!["uninstall", "--keep-binaries"]; - if confirmed { - args.push("--yes"); - } - args.extend_from_slice(keep); - run_uninstall_args(world, &args, settings); -} - -/// Run `rocm` with exactly `args`, confined to the scenario's own folders like -/// every other uninstall here. -fn run_uninstall_args(world: &mut E2eWorld, args: &[&str], settings: &[(&str, &str)]) { - assert_keeps_binaries(args); - let isolated = isolated_env(world); - let mut envs = isolated - .iter() - .map(|(name, value)| (*name, value.as_str())) - .collect::>(); - envs.extend_from_slice(settings); - let (stdout, stderr, rc) = crate::run_rocm_with_env(world, args, &envs); - world.cli_output = Some(stdout); - world.cli_stderr = Some(stderr); - world.cli_rc = Some(rc); +#[given( + "the cache folder is set to the user's own cache folder, which holds the uv and model caches" +)] +async fn cache_holds_shared_caches(world: &mut E2eWorld) { + let dot_cache = home(world).join(".cache"); + let uv = dot_cache.join("uv"); + let hf = dot_cache.join("huggingface"); + std::fs::create_dir_all(&uv).expect("failed to create uv cache"); + std::fs::create_dir_all(hf.join("hub")).expect("failed to create model cache"); + std::fs::write(uv.join("blob"), "wheel").expect("failed to write uv blob"); + set_env(world, "ROCM_CLI_CACHE_DIR", dot_cache); + set_env(world, "UV_CACHE_DIR", uv); + set_env(world, "HF_HOME", hf); } -fn run_cache_only_uninstall(world: &mut E2eWorld, cache_setting: &str) { - run_uninstall( - world, - &["--keep-config", "--keep-data"], - &[("ROCM_CLI_CACHE_DIR", cache_setting)], - ); -} +// ── When ─────────────────────────────────────────────────────────── #[when("the user uninstalls only the cache, writing its folder with a trailing slash")] async fn uninstall_cache_trailing_slash(world: &mut E2eWorld) { let setting = format!("{}/", cache_link(world).display()); - run_cache_only_uninstall(world, &setting); + set_env(world, "ROCM_CLI_CACHE_DIR", setting); + run_uninstall(world, &["--yes", "--keep-config", "--keep-data"]); } #[when("the user uninstalls only the cache")] async fn uninstall_cache(world: &mut E2eWorld) { - let setting = cache_link(world).display().to_string(); - run_cache_only_uninstall(world, &setting); + let setting = cache_link(world); + set_env(world, "ROCM_CLI_CACHE_DIR", setting); + run_uninstall(world, &["--yes", "--keep-config", "--keep-data"]); } #[when("the user uninstalls the config and the cache")] async fn uninstall_config_and_cache(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - let cache = looping_cache(world).display().to_string(); - run_uninstall( - world, - &["--keep-data"], - &[ - ("ROCM_CLI_CONFIG_DIR", &config), - ("ROCM_CLI_CACHE_DIR", &cache), - ], + let cache = looping_cache(world); + set_env(world, "ROCM_CLI_CACHE_DIR", cache); + run_uninstall(world, &["--yes", "--keep-data"]); +} + +#[when("the user previews an uninstall")] +async fn preview_uninstall(world: &mut E2eWorld) { + run_uninstall(world, &["--dry-run"]); +} + +#[when("the user uninstalls")] +async fn uninstall_everything(world: &mut E2eWorld) { + run_uninstall(world, &["--yes"]); +} + +#[when("the user uninstalls again with the flag the refusal advised")] +async fn uninstall_with_advised_flag(world: &mut E2eWorld) { + // Take the flag from the message rather than restating it, so this proves + // the advice the user actually reads. + let message = format!( + "{}{}", + world.cli_output.as_deref().unwrap_or(""), + world.cli_stderr.as_deref().unwrap_or("") ); + let flag = message + .split("e-run with ") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .filter(|word| word.starts_with("--keep-")) + .unwrap_or_else(|| panic!("the refusal named no `re-run with --keep-...`:\n{message}")) + .to_owned(); + run_uninstall(world, &["--yes", &flag]); } #[when("the user uninstalls the config without confirming")] async fn uninstall_config_unconfirmed(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - run_uninstall_with( - world, - false, - &["--keep-data", "--keep-cache"], - &[("ROCM_CLI_CONFIG_DIR", &config)], - ); + // No `--yes`, so the run reaches the confirmation gate; the harness gives + // the binary no terminal, which is the case the gate has to refuse. + run_uninstall(world, &["--keep-data", "--keep-cache"]); } /// Run `rocm uninstall` of the config folder only, without `--yes`, under a real @@ -179,29 +313,7 @@ async fn uninstall_config_unconfirmed(world: &mut E2eWorld) { /// refused first); a pseudo-terminal is the only way to answer it. The screen /// the user would be looking at is kept as the scenario's output. async fn answer_uninstall_prompt(world: &mut E2eWorld, keys: &str) { - let root = root(world).to_path_buf(); - let home = root.join("home"); - std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); - let home = home.display().to_string(); - let uv = root.join("uv-cache").display().to_string(); - let hf = root.join("hf-home").display().to_string(); - let config = config_dir(world).display().to_string(); - let mut session = TuiSession::spawn_with_env( - world, - &[ - "uninstall", - "--keep-binaries", - "--keep-data", - "--keep-cache", - ], - &[ - ("HOME", home.as_str()), - ("UV_CACHE_DIR", uv.as_str()), - ("HF_HOME", hf.as_str()), - ("ROCM_CLI_CONFIG_DIR", config.as_str()), - ], - ) - .unwrap_or_else(|e| panic!("failed to open the uninstall prompt: {e}")); + let mut session = spawn_at_terminal(world, &config_only_args(false)); session .wait_for_screen("Proceed with uninstall? [y/N]:", default_timeout()) .await @@ -311,14 +423,9 @@ async fn cancellation_on_its_own_line(world: &mut E2eWorld) { ); } -/// The scenario's own home folder, standing in for the user's. -fn home_dir(world: &E2eWorld) -> PathBuf { - root(world).join("home") -} - -/// The cache folder a default install in [`home_dir`] uses (`~/.rocm/cache`). +/// The cache folder a default install in [`home`] uses (`~/.rocm/cache`). fn default_cache(world: &E2eWorld) -> PathBuf { - home_dir(world).join(".rocm").join("cache") + home(world).join(".rocm").join("cache") } /// Where the cache folder belongs when only the config and data folders are @@ -334,7 +441,7 @@ fn data_cache(world: &E2eWorld) -> PathBuf { /// runner's. fn run_without_cache_setting(world: &mut E2eWorld, args: &[&str]) { let root = root(world).to_path_buf(); - let home = home_dir(world); + let home = home(world); std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); let home = home.display().to_string(); let uv = root.join("uv-cache").display().to_string(); @@ -364,6 +471,15 @@ async fn data_cache_holds_file(world: &mut E2eWorld) { let cache = data_cache(world); std::fs::create_dir_all(&cache).expect("failed to create the data folder's cache folder"); std::fs::write(cache.join("cached.bin"), "cached").expect("failed to write cache file"); + // The harness's config and data folders sit outside the scenario's home, + // where `rocm uninstall` removes only a folder ROCm CLI marked as its own. + // They stand for an install ROCm CLI created, so they carry its marker, + // and so does the cache folder it would have created inside the data one. + let paths = world.app_paths(); + for folder in [paths.config_dir, paths.data_dir, cache] { + std::fs::write(folder.join(".rocm-cli-root"), "created by ROCm CLI\n") + .expect("failed to mark the folder as ROCm CLI's own"); + } } #[when("the user asks what ROCm CLI keeps on disk with only the config and data folders set")] @@ -447,7 +563,7 @@ fn state_folders(world: &E2eWorld) -> Vec { paths.config_dir, paths.data_dir.clone(), paths.data_dir.join("cache"), - home_dir(world).join(".rocm"), + home(world).join(".rocm"), ] } @@ -495,6 +611,8 @@ async fn still_no_folders(world: &mut E2eWorld) { } } +// ── Then ─────────────────────────────────────────────────────────── + fn output(world: &E2eWorld) -> &str { world .cli_output @@ -502,14 +620,22 @@ fn output(world: &E2eWorld) -> &str { .expect("no CLI output captured - did the When step run?") } +fn stderr(world: &E2eWorld) -> &str { + world.cli_stderr.as_deref().unwrap_or("") +} + +const fn rc(world: &E2eWorld) -> i32 { + world.cli_rc.expect("no exit code captured") +} + #[then("the uninstall succeeds")] async fn uninstall_succeeds(world: &mut E2eWorld) { - let rc = world.cli_rc.expect("no exit code captured"); assert!( - rc == 0, - "uninstall must exit 0, got {rc}\nstdout:\n{}\nstderr:\n{}", + rc(world) == 0, + "uninstall must exit 0, got {}\nstdout:\n{}\nstderr:\n{}", + rc(world), output(world), - world.cli_stderr.as_deref().unwrap_or("") + stderr(world) ); } @@ -548,16 +674,307 @@ async fn target_intact(world: &mut E2eWorld) { ); } -#[then("the uninstall fails")] -async fn uninstall_fails(world: &mut E2eWorld) { - let rc = world.cli_rc.expect("no exit code captured"); +#[then(expr = "the uninstall is refused because the data folder {string} is {string}")] +async fn refused_because(world: &mut E2eWorld, folder: String, why: String) { + let folder = if folder == "" { + home(world).display().to_string() + } else { + folder + }; + let stdout = output(world); assert!( - rc != 0, - "uninstall must fail, got exit 0\nstdout:\n{}", + rc(world) != 0, + "a refused uninstall must fail, got exit 0:\n{stdout}" + ); + // The review lists the root under "Refused", with the reason, and never in + // the would-be-removed list. + // Followed by where the folder came from, in parentheses. + let refused_line = format!(" - data: {folder} is {why} ("); + assert!( + stdout.lines().any(|line| line.starts_with(&refused_line)), + "expected `{refused_line}` in the review:\n{stdout}" + ); + let removed_line = format!(" - data: {folder}"); + assert!( + !stdout.lines().any(|line| line == removed_line), + "the refused root must not be listed for removal:\n{stdout}" + ); +} + +#[then("the refusal advises re-running with --keep-data")] +async fn refusal_advises_keep_data(world: &mut E2eWorld) { + let message = format!("{}{}", output(world), stderr(world)); + assert!( + message.contains("e-run with --keep-data to leave it in place."), + "the refusal must say how to proceed:\n{message}" + ); +} + +#[then("the refusal says nothing was removed")] +async fn refusal_says_nothing_removed(world: &mut E2eWorld) { + // Asserted together with the state in the steps that follow it in the + // scenario: the home file and the config folder are both still there. + assert!( + stderr(world).contains("uninstall refused, nothing was removed"), + "stderr:\n{}", + stderr(world) + ); +} + +#[then("the user's files in the home folder are still there")] +async fn home_files_intact(world: &mut E2eWorld) { + let file = user_file_in_home(world); + assert!( + file.is_file(), + "uninstall deleted {}:\n{}\n{}", + file.display(), + output(world), + stderr(world) + ); +} + +#[then("the config folder is still there")] +async fn config_intact(world: &mut E2eWorld) { + let config = config_dir(world); + assert!( + config.is_dir(), + "a refused uninstall removed {}:\n{}", + config.display(), output(world) ); } +#[then("the config folder is gone")] +async fn config_gone(world: &mut E2eWorld) { + let config = config_dir(world); + assert!( + !config.exists(), + "the uninstall did not remove {}:\n{}", + config.display(), + output(world) + ); +} + +#[then("the review warns that the uv and model caches will be deleted with the cache folder")] +async fn warns_shared_caches_deleted(world: &mut E2eWorld) { + let stdout = output(world); + let dot_cache = home(world).join(".cache"); + let uv = dot_cache.join("uv"); + let hub = dot_cache.join("huggingface").join("hub"); + for (name, path) in [ + ("the uv package cache", uv), + ("downloaded model files", hub), + ] { + let warning = format!( + "{name} WILL BE DELETED: {} is inside the cache folder being removed ({})", + path.display(), + dot_cache.display() + ); + assert!( + stdout.contains(&warning), + "expected `{warning}` in the review:\n{stdout}" + ); + assert!( + !stdout.contains(&format!("not removed: {}", path.display())), + "the review must not also call {} kept:\n{stdout}", + path.display() + ); + } + // Shown in the review, which precedes the confirmation prompt. + let review_ends = stdout.find("Left alone:").unwrap_or(stdout.len()); + assert!( + stdout + .find("WILL BE DELETED") + .is_some_and(|at| at < review_ends), + "the warning must be part of the review:\n{stdout}" + ); + assert!( + stdout.contains("Re-run with --keep-cache to keep"), + "the warning must say how to keep the caches:\n{stdout}" + ); +} + +#[then("the uv cache is still there after the preview")] +async fn uv_cache_intact(world: &mut E2eWorld) { + let blob = home(world).join(".cache").join("uv").join("blob"); + assert!(blob.is_file(), "a dry run deleted {}", blob.display()); + assert!( + rc(world) == 0, + "the preview must exit 0:\n{}", + stderr(world) + ); +} + +#[given( + "the data folder is set to `.`, and the user is in their home folder, which holds their files" +)] +async fn data_is_dot_in_home(world: &mut E2eWorld) { + let file = user_file_in_home(world); + std::fs::create_dir_all(file.parent().expect("parent")).expect("failed to create home"); + std::fs::write(&file, "user data").expect("failed to write user file"); + plant_config_rocm_cli_created(world); + set_env(world, "ROCM_CLI_DATA_DIR", "."); +} + +#[when("the user uninstalls from their home folder")] +async fn uninstall_from_home(world: &mut E2eWorld) { + let home = home(world); + run_uninstall_in(world, &["--yes"], Some(&home)); +} + +#[then(expr = "the refusal names {word} as where the data folder came from")] +async fn refusal_names_source(world: &mut E2eWorld, setting: String) { + let message = format!("{}{}", output(world), stderr(world)); + assert!( + message.contains(&format!("(set by {setting}")) + && message.contains(&format!("Point {setting} at a folder of ROCm CLI's own")), + "the refusal must name {setting} and say to change it:\n{message}" + ); +} + +#[then(expr = "the refusal says the data folder {string} resolves to the home folder")] +async fn refusal_says_resolves_to_home(world: &mut E2eWorld, folder: String) { + let stdout = output(world); + let home = crate::e2e::runtime_steps::canonical_without_verbatim(&home(world)); + let line = format!( + " - data: {folder} is your home folder (set by ROCM_CLI_DATA_DIR; resolves to {})", + home.display() + ); + assert!( + stdout.lines().any(|l| l == line), + "expected `{line}` in the review:\n{stdout}" + ); + assert!(rc(world) != 0, "a refused uninstall must fail:\n{stdout}"); +} + +// ── The marker, and the dashboard's path ─────────────────────────── + +/// A data folder outside the home folder that ROCm CLI did not mark. +fn unmarked_data(world: &E2eWorld) -> PathBuf { + root(world).join("srv").join("rocm") +} + +#[given("the data folder is a folder outside the home folder without ROCm CLI's marker")] +async fn data_is_unmarked(world: &mut E2eWorld) { + let data = unmarked_data(world); + std::fs::create_dir_all(&data).expect("failed to create data folder"); + std::fs::write(data.join("keep.txt"), "user data").expect("failed to write"); + set_env(world, "ROCM_CLI_DATA_DIR", data); +} + +#[then("the refusal advises creating the marker if the folder is ROCm CLI's")] +async fn advises_marker(world: &mut E2eWorld) { + let stdout = output(world); + let marker = crate::e2e::runtime_steps::canonical_without_verbatim(&unmarked_data(world)) + .join(".rocm-cli-root"); + assert!(rc(world) != 0, "a refused preview must fail:\n{stdout}"); + assert!( + stdout.contains(&format!( + "if this folder belongs to ROCm CLI, create {}", + marker.display() + )), + "the refusal must name the marker to create:\n{stdout}" + ); +} + +#[when("the user creates the marker the refusal named")] +async fn create_advised_marker(world: &mut E2eWorld) { + // The marker the refusal names for the data folder, taken from the + // message itself, so this follows the advice the user reads. + let stdout = output(world).to_owned(); + let data = crate::e2e::runtime_steps::canonical_without_verbatim(&unmarked_data(world)); + let marker = stdout + .split("create ") + .skip(1) + .filter_map(|rest| rest.split(", or").next()) + .map(str::trim) + .find(|path| Path::new(path).parent() == Some(data.as_path())) + .unwrap_or_else(|| panic!("no marker path for {} in:\n{stdout}", data.display())) + .to_owned(); + std::fs::write(&marker, "").unwrap_or_else(|e| panic!("cannot create {marker}: {e}")); +} + +#[then("the preview plans to remove the data folder")] +async fn preview_plans_data(world: &mut E2eWorld) { + let stdout = output(world); + assert!( + rc(world) == 0, + "the preview must succeed now:\n{stdout}\n{}", + stderr(world) + ); + let line = format!(" - data: {}", unmarked_data(world).display()); + assert!( + stdout.lines().any(|l| l == line), + "expected `{line}` in the review:\n{stdout}" + ); + assert!(!stdout.contains("Refused"), "{stdout}"); +} + +#[given("setup.therock_venv points at the user's home folder, which holds their files")] +async fn venv_is_home(world: &mut E2eWorld) { + let file = user_file_in_home(world); + std::fs::create_dir_all(file.parent().expect("parent")).expect("failed to create home"); + std::fs::write(&file, "user data").expect("failed to write user file"); + let config = config_dir(world); + plant_config_rocm_cli_created(world); + std::fs::write( + config.join("config.json"), + serde_json::to_vec(&serde_json::json!({ "setup": { "therock_venv": home(world) } })) + .expect("json"), + ) + .expect("failed to write config.json"); + // An empty value is "unset" to ROCm CLI, so discovery falls back to + // `setup.therock_venv` as it would for a user who never set the variable. + set_env(world, "ROCM_CLI_DATA_DIR", ""); +} + +#[when("the dashboard runs an approved uninstall")] +async fn dashboard_uninstall(world: &mut E2eWorld) { + // The same entry point the dashboard and the assistant use for an approved + // `rocm_command`: it starts a `rocm` child with the folders pinned. + let arguments = r#"{"args":["uninstall","--keep-binaries","--keep-cache"]}"#; + run_command_in( + world, + &[ + "mcp-call", + "rocm_command", + "--allow-mutation", + "--arguments-json", + arguments, + ], + None, + ); +} + +#[then( + "the refusal names setup.therock_venv and advises --keep-data, not a variable the user never set" +)] +async fn dashboard_refusal_names_venv(world: &mut E2eWorld) { + let stdout = output(world); + // `mcp-call` itself succeeds and reports the child's result as JSON; the + // approved `rocm uninstall` it ran must have failed. + let reply: serde_json::Value = serde_json::from_str(stdout.trim()) + .unwrap_or_else(|e| panic!("mcp-call did not print JSON ({e}):\n{stdout}")); + let child_exit = reply["structuredContent"]["exit_status"].as_i64(); + assert!( + child_exit.is_some_and(|code| code != 0) + && reply["isError"] == serde_json::Value::Bool(true), + "the approved uninstall must exit non-zero, got {child_exit:?}:\n{stdout}" + ); + assert!( + stdout.contains("set by setup.therock_venv"), + "the refusal must name setup.therock_venv:\n{stdout}" + ); + assert!( + stdout.contains("Re-run with --keep-data to leave it in place."), + "the refusal must advise --keep-data:\n{stdout}" + ); + assert!( + !stdout.contains("ROCM_CLI_DATA_DIR"), + "the refusal named a variable the user never set:\n{stdout}" + ); +} + #[then("the uninstall is refused and the user is told to confirm explicitly")] async fn uninstall_refused_without_yes(world: &mut E2eWorld) { let rc = world.cli_rc.expect("no exit code captured"); @@ -582,6 +999,16 @@ async fn uninstall_refused_without_yes(world: &mut E2eWorld) { ); } +#[then("the uninstall fails")] +async fn uninstall_fails(world: &mut E2eWorld) { + let rc = world.cli_rc.expect("no exit code captured"); + assert!( + rc != 0, + "uninstall must fail, got exit 0\nstdout:\n{}", + output(world) + ); +} + #[then("the error names the cache folder it could not check")] async fn error_names_cache(world: &mut E2eWorld) { let expected = format!( @@ -596,7 +1023,7 @@ async fn error_names_cache(world: &mut E2eWorld) { } #[then("the config folder still holds the user's files")] -async fn config_intact(world: &mut E2eWorld) { +async fn config_still_holds_user_files(world: &mut E2eWorld) { let file = config_dir(world).join(USER_FILE); assert!( file.is_file(), @@ -630,29 +1057,10 @@ fn config_only_args(dry_run: bool) -> Vec<&'static str> { args } -/// Run `rocm` under a pseudo-terminal, confined to the scenario's folders like -/// every other uninstall here, so the command sees a terminal on both streams as -/// a person typing it would. Answers its `[y/N]` prompt when `answer` is given. +/// Run `rocm` at a terminal (see [`spawn_at_terminal`]), answering its `[y/N]` +/// prompt when `answer` is given. async fn run_uninstall_at_terminal(world: &mut E2eWorld, args: &[&str], answer: Option<&str>) { - assert_keeps_binaries(args); - let root = root(world).to_path_buf(); - let home = root.join("home"); - std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); - let home = home.display().to_string(); - let uv = root.join("uv-cache").display().to_string(); - let hf = root.join("hf-home").display().to_string(); - let config = config_dir(world).display().to_string(); - let mut session = TuiSession::spawn_with_env( - world, - args, - &[ - ("HOME", home.as_str()), - ("UV_CACHE_DIR", uv.as_str()), - ("HF_HOME", hf.as_str()), - ("ROCM_CLI_CONFIG_DIR", config.as_str()), - ], - ) - .unwrap_or_else(|e| panic!("failed to run {args:?} at a terminal: {e}")); + let mut session = spawn_at_terminal(world, args); if let Some(answer) = answer { session .wait_for_screen("[y/N]:", default_timeout()) @@ -674,12 +1082,7 @@ async fn run_uninstall_at_terminal(world: &mut E2eWorld, args: &[&str], answer: #[when("the user dry-runs an uninstall of only the config")] async fn dry_run_config_only(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - run_uninstall_args( - world, - &config_only_args(true), - &[("ROCM_CLI_CONFIG_DIR", &config)], - ); + run_uninstall(world, &["--keep-data", "--keep-cache", "--dry-run"]); } #[when("the user dry-runs an uninstall of only the config at a terminal")] @@ -736,17 +1139,6 @@ async fn dry_run_lists_the_config(world: &mut E2eWorld) { ); } -#[then("the config folder is gone")] -async fn config_gone(world: &mut E2eWorld) { - let config = config_dir(world); - assert!( - std::fs::symlink_metadata(&config).is_err(), - "running it again as the dry run said did not remove {}:\n{}", - config.display(), - output(world) - ); -} - #[then("the dry run offers no step to remove anything")] async fn dry_run_offers_no_step(world: &mut E2eWorld) { let stdout = output(world); @@ -772,22 +1164,12 @@ async fn dry_run_offers_no_step(world: &mut E2eWorld) { /// refuses a call that would remove something instead of running it. #[when("the assistant previews an uninstall")] async fn assistant_previews_uninstall(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - let isolated = isolated_env(world); - let mut envs = isolated - .iter() - .map(|(name, value)| (*name, value.as_str())) - .collect::>(); - envs.push(("ROCM_CLI_CONFIG_DIR", &config)); let arguments = serde_json::json!({ "args": ["uninstall", "--dry-run"] }).to_string(); - let (stdout, stderr, rc) = crate::run_rocm_with_env( + run_command_in( world, &["mcp-call", "rocm_command", "--arguments-json", &arguments], - &envs, + None, ); - world.cli_output = Some(stdout); - world.cli_stderr = Some(stderr); - world.cli_rc = Some(rc); } /// What the preview printed: the command's own text inside the tool result. @@ -847,18 +1229,12 @@ async fn preview_says_removal_needs_approval(world: &mut E2eWorld) { #[when("the user uninstalls the config with --force")] async fn uninstall_with_force(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - let mut args = config_only_args(false); - args.push("--force"); - run_uninstall_args(world, &args, &[("ROCM_CLI_CONFIG_DIR", &config)]); + run_uninstall(world, &["--keep-data", "--keep-cache", "--force"]); } #[when("the user uninstalls the config with a near miss of --force")] async fn uninstall_with_near_miss_of_force(world: &mut E2eWorld) { - let config = config_dir(world).display().to_string(); - let mut args = config_only_args(false); - args.push("--forc"); - run_uninstall_args(world, &args, &[("ROCM_CLI_CONFIG_DIR", &config)]); + run_uninstall(world, &["--keep-data", "--keep-cache", "--forc"]); } #[then("the uninstall is refused and told to use --yes instead")] From 66f49399be4665480e49cac46dbbd0c4922ba27f Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Tue, 10 Nov 2026 17:17:46 +0200 Subject: [PATCH 2/7] fix(uninstall): bound the short-name allowance and pin each edge with a test A root spelled beside home but really inside it is judged by where it really is. That allowance now also covers a folder that resolves to home itself, so it is refused as the home folder rather than as another user's, and it no longer applies when home resolves to the top of the filesystem, where every folder is inside it. The tests now cover each condition that bounds it: a link spelled beside home stays another user's, a folder that is home itself is refused as home, home reached through a link still counts, a folder spelled under the users folder that really lives elsewhere keeps its refusal, a spelled system location stays refused whatever it resolves to, and a top-of-filesystem home grants nothing. Signed-off-by: Roman Inflianskas --- apps/rocm/src/uninstall_plan.rs | 103 ++++++++++++++++++++++++++++++-- 1 file changed, 99 insertions(+), 4 deletions(-) diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index c319c9bcb0..5d4ecbf0a1 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -354,11 +354,16 @@ pub(crate) fn judge_uninstall_root( } } -/// Whether the real directory `path` really sits inside the user's home, +/// Whether the real directory `path` really is the user's home or inside it, /// though spelled outside it — on Windows the temp folder is often spelled /// with the home folder's short 8.3 name (`C:\Users\RUNNER~1\...`), which by /// spelling alone is someone else's folder under `C:\Users`. Such a root is -/// judged by where it really is instead. +/// judged by where it really is instead, which allows it inside home and +/// refuses it as the home folder itself. +/// +/// A home that resolves to the top of the filesystem decides nothing: every +/// folder is inside it, so it cannot tell another user's folder from one of +/// the user's own. fn resolves_inside_own_home( path: &Path, home: Option<&Path>, @@ -370,8 +375,8 @@ fn resolves_inside_own_home( let Ok(resolved_home) = canonicalize(home) else { return false; }; - rocm_core::runtime_path_is_same_or_inside(&resolved, &resolved_home) - && !rocm_core::runtime_paths_equivalent(&resolved, &resolved_home) + resolved_home.parent().is_some() + && rocm_core::runtime_path_is_same_or_inside(&resolved, &resolved_home) } pub(crate) fn build_uninstall_plan( @@ -2019,6 +2024,96 @@ mod tests { ); } + /// The cases that bound the short-name allowance in + /// [`super::judge_uninstall_root`], each judged directly with the real + /// resolver unless it says otherwise. `users/` is home's parent, so by + /// spelling alone everything under it but home is another user's. + #[test] + #[cfg(unix)] + fn the_short_name_allowance_applies_only_to_a_real_folder_in_home() { + use rocm_core::ProtectedLocation::{Home, OtherUsersHome, System}; + let root = sandbox("short-name-bounds"); + let users = root.join("users"); + let home = users.join("home"); + let data = home.join(".rocm").join("data"); + std::fs::create_dir_all(&data).unwrap(); + let elsewhere = root.join("elsewhere").join("data"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let resolve: Canonicalize<'_> = &rocm_core::canonicalize_for_compare; + let judge = |path: &Path, home: &Path, resolve: Canonicalize<'_>| { + let metadata = std::fs::symlink_metadata(path).unwrap(); + super::judge_uninstall_root(path, &metadata, Some(home), resolve) + }; + let why = |judgment: &super::RootJudgment| match judgment { + super::RootJudgment::Refuse { why, .. } => Some(*why), + super::RootJudgment::Remove { .. } => None, + }; + + // A link spelled beside home, pointing into it, is still another + // user's: only a real folder is judged by where it is. + let link = users.join("LINK~1"); + std::os::unix::fs::symlink(&data, &link).unwrap(); + let as_link = judge(&link, &home, resolve); + + // A real folder spelled beside home that is home itself is refused + // as the home folder, by where it really is. + let alias = users.join("ALIAS~1"); + std::os::unix::fs::symlink(&users, &alias).unwrap(); + let home_itself = judge(&alias.join("home"), &home, resolve); + + // Home given through a link of its own still counts as home. + let home_link = root.join("home-link"); + std::os::unix::fs::symlink(&home, &home_link).unwrap(); + let through_linked_home = judge( + &alias.join("home").join(".rocm").join("data"), + &home_link, + resolve, + ); + + // A folder spelled under users/ that really is somewhere else + // entirely keeps the refusal its spelling earns. + let away = users.join("AWAY~1"); + std::os::unix::fs::symlink(elsewhere.parent().unwrap(), &away).unwrap(); + let spelled_away = judge(&away.join("data"), &home, resolve); + + // A system location is refused by its spelling even when it resolves + // into home; the resolver is told so, as no real `/usr` does. + let system = Path::new("/usr/rocm-short-name-test"); + let into_home = data.clone(); + let fake: &dyn Fn(&Path) -> std::io::Result = &move |path: &Path| { + if path == system { + Ok(into_home.clone()) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + let system_metadata = std::fs::symlink_metadata(&data).unwrap(); + let spelled_system = + super::judge_uninstall_root(system, &system_metadata, Some(&home), fake); + let _ = std::fs::remove_dir_all(&root); + + assert_eq!(why(&as_link), Some(OtherUsersHome), "{as_link:?}"); + assert_eq!(why(&home_itself), Some(Home), "{home_itself:?}"); + assert_eq!(why(&through_linked_home), None, "{through_linked_home:?}"); + assert_eq!(why(&spelled_away), Some(OtherUsersHome), "{spelled_away:?}"); + assert_eq!(why(&spelled_system), Some(System), "{spelled_system:?}"); + } + + /// With home at the top of the filesystem every folder is inside it, so + /// the allowance decides nothing and the spelling's refusal stands. + #[test] + fn a_home_at_the_filesystem_root_grants_no_short_name_allowance() { + let root = sandbox("short-name-root-home"); + let top = if cfg!(windows) { + Path::new(r"C:\") + } else { + Path::new("/") + }; + let resolve: Canonicalize<'_> = &rocm_core::canonicalize_for_compare; + assert!(!super::resolves_inside_own_home(&root, Some(top), resolve)); + let _ = std::fs::remove_dir_all(&root); + } + /// Check, then act, for a root that was a symbolic link at review time: /// replaced by a real folder while the prompt was open, it must not be /// removed recursively; the same goes for a file that became a folder. From e7472d4b4532fcc61ecc90567ab1d2981f84c1e0 Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Wed, 11 Nov 2026 11:28:40 +0200 Subject: [PATCH 3/7] fix(uninstall): answer review: true docs, one Windows root list, stricter marker and flags The runtime-folder rule now refuses the same Windows system folders as `rocm uninstall`, ProgramData included, on the system drive instead of a fixed C:, so `rocm runtimes uninstall` and `rocm storage remove-old-installs` are protected on a non-C: system too. Its Unix list stays different on purpose, and the comment now says why. The marker counts only as a plain file of the folder's own: a link named like it no longer marks a folder. The dashboard's /uninstall refuses a flag it does not pass through, with the flags it takes, instead of dropping it into a full removal, and passes a repeated flag once. The review's "Refused" heading no longer claims ROCm CLI never removes a listed folder, which was false for one cleared by the marker. Docs and comments that contradicted the code are corrected: the verdict's check order and its shared-folder step, a test doc attached to the wrong test, the properties header, the module's ownership note, the assistant preview's flags, and the scenario summary. uninstall-18 now also runs the uninstall with --keep-cache (the cache stays) and without it (the cache is gone), uninstall-21 checks the config folder survives, and the config-gone step no longer reads a dangling link as removed. Signed-off-by: Roman Inflianskas --- apps/rocm/src/runtime_uninstall.rs | 10 ++- apps/rocm/src/uninstall_plan.rs | 62 +++++++++++-- crates/rocm-core/src/config.rs | 20 ++--- crates/rocm-core/src/runtime.rs | 86 +++++++++++++------ crates/rocm-dash-tui/src/app/slash.rs | 63 +++++++++++--- docs/testing.md | 18 ++-- tests/e2e-cucumber/features/uninstall.feature | 17 ++-- .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 39 +++++++-- 8 files changed, 239 insertions(+), 76 deletions(-) diff --git a/apps/rocm/src/runtime_uninstall.rs b/apps/rocm/src/runtime_uninstall.rs index 3498ff6357..02e9cac47c 100644 --- a/apps/rocm/src/runtime_uninstall.rs +++ b/apps/rocm/src/runtime_uninstall.rs @@ -754,10 +754,12 @@ mod tests { assert!(err.to_string().contains("protected system location")); } - /// `rocm runtimes uninstall` and `rocm storage remove-old-installs` share - /// the protected-location predicate with `rocm uninstall`, so a runtime - /// whose `install_root` is the home folder itself (`--prefix ~`) is refused - /// too — and the refusal says it is the home folder, not a system location. + /// `rocm runtimes uninstall` and `rocm storage remove-old-installs` judge a + /// runtime folder by the runtime-folder rule (`runtime_protected_location`), + /// which refuses the home folder as `rocm uninstall`'s own rule does, so a + /// runtime whose `install_root` is the home folder itself (`--prefix ~`) is + /// refused — and the refusal says it is the home folder, not a system + /// location. #[test] fn ensure_runtime_install_root_refuses_the_home_folder_by_name() { // A fixed home, so the check cannot fall back to some other refusal diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 5d4ecbf0a1..0cb4e44792 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -12,9 +12,10 @@ //! are called directly from `dispatch()`. //! //! This is deliberately a separate file from `uninstall.rs`, not folded into -//! it: `uninstall.rs` owns only what `rocm uninstall` itself does on top of -//! removing files — undoing the installer's PATH change and deleting the -//! running executable on Windows, which cannot unlink itself. `storage.rs` +//! it: `uninstall.rs` owns what `rocm uninstall` itself does — carrying the +//! plan out (`apply_uninstall_plan`, the one step that deletes), undoing the +//! installer's PATH change and deleting the running executable on Windows, +//! which cannot unlink itself. `storage.rs` //! builds and renders a removal plan of its own (`rocm storage //! remove-downloads`) and reuses this module's plan type and its //! file-removal helpers to do it, so keeping them in `uninstall.rs` would @@ -343,9 +344,7 @@ pub(crate) fn judge_uninstall_root( &resolved_system_roots, ) { UninstallRootVerdict::Refused(why) => refuse(why), - UninstallRootVerdict::NeedsMarker - if !resolved.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file() => - { + UninstallRootVerdict::NeedsMarker if !is_root_marker(&resolved) => { refuse(ProtectedLocation::NotMarked) } UninstallRootVerdict::Allowed | UninstallRootVerdict::NeedsMarker => RootJudgment::Remove { @@ -354,6 +353,14 @@ pub(crate) fn judge_uninstall_root( } } +/// Whether `dir` carries the marker as a regular file of its own. A link named +/// like the marker is not one: anything that can plant a link there could +/// point it at any file, and ROCm CLI only ever writes a plain file. +fn is_root_marker(dir: &Path) -> bool { + fs::symlink_metadata(dir.join(rocm_core::ROCM_CLI_ROOT_MARKER)) + .is_ok_and(|meta| meta.file_type().is_file()) +} + /// Whether the real directory `path` really is the user's home or inside it, /// though spelled outside it — on Windows the temp folder is often spelled /// with the home folder's short 8.3 name (`C:\Users\RUNNER~1\...`), which by @@ -740,7 +747,10 @@ pub(crate) fn render_uninstall_plan( uninstall::render_extra_plan(&mut output, plan); if !plan.refused.is_empty() { let _ = writeln!(output); - let _ = writeln!(output, "Refused (ROCm CLI never removes these folders):"); + let _ = writeln!( + output, + "Refused (nothing is removed while any of these is listed):" + ); } for root in &plan.refused { let _ = writeln!(output, " - {}: {}", root.kind, root.describe()); @@ -2114,6 +2124,44 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + /// A link named like the marker does not mark a folder: only the plain + /// file ROCm CLI writes does. + #[test] + #[cfg(unix)] + fn a_linked_marker_does_not_mark_a_folder() { + let root = sandbox("linked-marker"); + let home = root.join("users").join("home"); + std::fs::create_dir_all(&home).unwrap(); + let data = root.join("srv").join("rocm"); + std::fs::create_dir_all(&data).unwrap(); + let elsewhere = root.join("any-file"); + std::fs::write(&elsewhere, b"").unwrap(); + std::os::unix::fs::symlink(&elsewhere, data.join(rocm_core::ROCM_CLI_ROOT_MARKER)).unwrap(); + let linked = super::build_uninstall_plan_for_home( + &data_only(data.clone(), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + std::fs::remove_file(data.join(rocm_core::ROCM_CLI_ROOT_MARKER)).unwrap(); + std::fs::write(data.join(rocm_core::ROCM_CLI_ROOT_MARKER), b"").unwrap(); + let marked = super::build_uninstall_plan_for_home( + &data_only(data, &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(linked.refused.len(), 1, "{linked:?}"); + assert_eq!( + linked.refused[0].why, + rocm_core::ProtectedLocation::NotMarked + ); + assert!(marked.refused.is_empty(), "{marked:?}"); + } + /// Check, then act, for a root that was a symbolic link at review time: /// replaced by a real folder while the prompt was open, it must not be /// removed recursively; the same goes for a file that became a folder. diff --git a/crates/rocm-core/src/config.rs b/crates/rocm-core/src/config.rs index b203cda9f2..f290c8cc8a 100644 --- a/crates/rocm-core/src/config.rs +++ b/crates/rocm-core/src/config.rs @@ -1454,16 +1454,6 @@ last_installed_runtime_id = "therock-release" Ok(()) } - /// The temp-file cleanup when the publish step fails (in - /// `atomic_write::publish_staged_file_with`), which the happy-path test above - /// cannot reach: it only ever asserts that a SUCCESSFUL save leaves nothing - /// behind, so deleting the cleanup would go unnoticed until a user with a - /// failing disk accumulated one `config.json.tmp---` per attempt. - /// - /// A directory at the destination is what makes the publish fail on both - /// supported platforms without needing permissions a root CI lane ignores — - /// the same device `write_file_atomically_cleans_up_temp_when_the_rename_fails` - /// uses in `rocm_core::atomic_write`. /// Saving the config often creates the config folder; when it does, the /// folder is marked as ROCm CLI's own, so `rocm uninstall` can later remove /// it outside the home folder. A config folder that already existed is not @@ -1493,6 +1483,16 @@ last_installed_runtime_id = "therock-release" Ok(()) } + /// The temp-file cleanup when the publish step fails (in + /// `atomic_write::publish_staged_file_with`), which the happy-path test above + /// cannot reach: it only ever asserts that a SUCCESSFUL save leaves nothing + /// behind, so deleting the cleanup would go unnoticed until a user with a + /// failing disk accumulated one `config.json.tmp---` per attempt. + /// + /// A directory at the destination is what makes the publish fail on both + /// supported platforms without needing permissions a root CI lane ignores — + /// the same device `write_file_atomically_cleans_up_temp_when_the_rename_fails` + /// uses in `rocm_core::atomic_write`. #[test] fn a_config_save_that_cannot_publish_cleans_up_its_temp_file() -> Result<()> { let (root, paths) = temp_app_paths("config-save-rename-fails"); diff --git a/crates/rocm-core/src/runtime.rs b/crates/rocm-core/src/runtime.rs index 9b61a2a5e9..861978d56d 100644 --- a/crates/rocm-core/src/runtime.rs +++ b/crates/rocm-core/src/runtime.rs @@ -827,15 +827,22 @@ pub fn runtime_protected_location_for_home( protected_location_on(path, home, RuntimePlatform::current()) } -const fn system_roots(platform: RuntimePlatform) -> &'static [&'static str] { +/// The system locations a runtime folder may not be in. On Windows these are +/// `rocm uninstall`'s own, on the system drive; on Unix the list differs from +/// [`uninstall_system_roots`] on purpose: `/opt` and `/var` are refused here +/// (a runtime prefix there is the system's), while `rocm uninstall` refuses +/// only their top level and lets a marked folder below them go. +fn system_roots(platform: RuntimePlatform) -> Vec { if platform.is_windows() { - &["C:/Windows", "C:/Program Files", "C:/Program Files (x86)"] - } else { - &[ - "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/opt", "/proc", "/root", "/sbin", - "/sys", "/usr", "/var", - ] + return uninstall_system_roots_on(platform, &windows_system_drive()); } + [ + "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/opt", "/proc", "/root", "/sbin", + "/sys", "/usr", "/var", + ] + .iter() + .map(PathBuf::from) + .collect() } /// What the user's own home folder says about a path, when it says anything. @@ -881,7 +888,6 @@ fn protected_location_on( } system_roots(platform) .iter() - .map(Path::new) .any(|root| runtime_path_is_same_or_inside_on(path, root, platform)) .then_some(ProtectedLocation::System) } @@ -982,11 +988,14 @@ fn homes_parents_on( /// What `rocm uninstall` may do with the root `path`, judged against `home`. /// -/// In order: `/` (or a drive root) is refused; the user's own home is refused, -/// as is any folder containing it, while anything inside it is allowed; the -/// [`uninstall_system_roots`] and anything inside them are refused, as are -/// `extra_system_roots` (the caller passes their resolved spellings, so -/// `/lib -> usr/lib` and `/usr/lib` are judged alike); another user's home or +/// In order: `/` (or a drive root) is refused; the [`uninstall_system_roots`] +/// and anything inside them are refused, as are `extra_system_roots` (the +/// caller passes their resolved spellings, so `/lib -> usr/lib` and `/usr/lib` +/// are judged alike) — before the home allowance, so an odd home inside a +/// system location does not open it up; the user's own home is refused, as is +/// any folder containing it, while anything inside it is allowed; off Windows, +/// a folder other programs share (anything directly under `/`, +/// `/var/{lib,cache,log,tmp}`, `/mnt/`) is refused; another user's home or /// anything inside one is refused; anything else needs the marker. pub fn uninstall_root_verdict( path: &Path, @@ -2020,19 +2029,6 @@ mod tests { assert!(accepted.is_empty(), "accepted as removable: {accepted:?}"); } - // ── Properties: the recursive-delete guard ───────────────────── - // - // `runtime_protected_location` is the runtime-folder rule for - // "may ROCm CLI `remove_dir_all` this folder?". Everything below states a - // contract it must satisfy for EVERY spelling of a path, because the whole - // point of the guard is that it is handed a path somebody (or something) - // else wrote down — a registry entry, an `--prefix` argument, a tool call - // from the local assistant. Such a path is text, and text has many - // spellings for one folder. - // - // Unix-only: the protected-root list the guard consults is the Unix one, - // and `runtime_is_windows()` is decided at compile time, so the Windows - // branch cannot be exercised from here. All pure and in-process. /// A folder that already exists when ROCm CLI asks for it — even one /// created a moment earlier by someone else — is not marked; one this call /// creates is. A marker that cannot be written is a warning, not an error. @@ -2139,6 +2135,44 @@ mod tests { } } + /// The runtime-folder rule refuses the same Windows system folders as + /// `rocm uninstall`, `ProgramData` included, on the system drive. + #[test] + fn the_runtime_rule_refuses_the_windows_system_folders_on_the_system_drive() { + let _guard = SYSTEM_DRIVE_ENV_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let drive = windows_system_drive(); + let windows = RuntimePlatform::Windows; + for folder in [ + "Windows", + "Program Files", + "Program Files (x86)", + "ProgramData", + ] { + let path = PathBuf::from(format!("{drive}/{folder}/rocm")); + assert_eq!( + protected_location_on(&path, None, windows), + Some(ProtectedLocation::System), + "{}", + path.display() + ); + } + } + + // ── Properties: the recursive-delete guard ───────────────────── + // + // `runtime_protected_location` is the runtime-folder rule for + // "may ROCm CLI `remove_dir_all` this folder?". Everything below states a + // contract it must satisfy for EVERY spelling of a path, because the whole + // point of the guard is that it is handed a path somebody (or something) + // else wrote down — a registry entry, an `--prefix` argument, a tool call + // from the local assistant. Such a path is text, and text has many + // spellings for one folder. + // + // Unix-only: the protected-root list the guard consults is the Unix one, + // and `runtime_is_windows()` is decided at compile time, so the Windows + // branch cannot be exercised from here. All pure and in-process. #[cfg(unix)] mod delete_guard_properties { use super::*; diff --git a/crates/rocm-dash-tui/src/app/slash.rs b/crates/rocm-dash-tui/src/app/slash.rs index f0ae9ecdfb..2f8a49e122 100644 --- a/crates/rocm-dash-tui/src/app/slash.rs +++ b/crates/rocm-dash-tui/src/app/slash.rs @@ -226,10 +226,33 @@ impl AppState { // SAFE default: bare `/uninstall` is a dry-run (read-only). A real // uninstall needs `/uninstall --apply` and is approval-gated (the // bin auto-adds --yes on approval). + const PASSED_THROUGH: [&str; 5] = [ + "--keep-binaries", + "--keep-config", + "--keep-data", + "--keep-cache", + "--force-dev-binaries", + ]; let flags: Vec<&str> = rest.split_whitespace().skip(1).collect(); let saw_apply = flags.contains(&"--apply"); let saw_dry_run = flags.contains(&"--dry-run"); - if saw_apply && saw_dry_run { + // A flag that is not one of these is refused, not dropped: a + // typo such as `--keep-dat` would otherwise turn an intended + // keep into a full removal request. + let unknown: Vec<&str> = flags + .iter() + .copied() + .filter(|flag| { + !PASSED_THROUGH.contains(flag) && !matches!(*flag, "--apply" | "--dry-run") + }) + .collect(); + if !unknown.is_empty() { + self.chat.push(ChatTurn::error(format!( + "unknown /uninstall flag {}: use --dry-run, --apply, {}", + unknown.join(" "), + PASSED_THROUGH.join(", ") + ))); + } else if saw_apply && saw_dry_run { self.chat.push(ChatTurn::error( "conflicting /uninstall flags: choose either --dry-run (safe) or --apply (real uninstall)" .to_string(), @@ -241,16 +264,12 @@ impl AppState { // through, in both modes: a // refused uninstall's advice is to re-run with one, and a // dashboard that dropped it could never follow that advice. - argv.extend(flags.iter().copied().filter(|flag| { - matches!( - *flag, - "--keep-binaries" - | "--keep-config" - | "--keep-data" - | "--keep-cache" - | "--force-dev-binaries" - ) - })); + for flag in flags.iter().copied().filter(|f| PASSED_THROUGH.contains(f)) { + // Each once, however often it was typed. + if !argv.contains(&flag) { + argv.push(flag); + } + } if !real { argv.push("--dry-run"); } @@ -1202,6 +1221,28 @@ mod tests { ] }) ); + // A typo is refused with the flags it takes, not dropped into a full + // removal; a repeated flag is passed once. + let before = s.chat.len(); + assert_eq!( + s.handle_slash_command("/uninstall --apply --keep-dat"), + SlashOutcome::Handled + ); + assert!(s.slash_tool.is_none(), "a typo must not raise a request"); + let turn = s.chat.last().expect("an error turn"); + assert!(s.chat.len() > before && turn.role == ChatRole::Error); + assert!(turn.content.contains("--keep-dat"), "{}", turn.content); + assert!(turn.content.contains("--keep-data"), "{}", turn.content); + assert_eq!( + s.handle_slash_command("/uninstall --keep-data --keep-data"), + SlashOutcome::Handled + ); + let req = s.slash_tool.take().expect("a dry-run request"); + assert_eq!( + req.args, + serde_json::json!({ "args": ["uninstall", "--keep-data", "--dry-run"] }) + ); + // `--force-dev-binaries` is passed on too, not silently dropped. assert_eq!( s.handle_slash_command("/uninstall --apply --force-dev-binaries"), diff --git a/docs/testing.md b/docs/testing.md index 255c9dacdb..d4875be7aa 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1792,14 +1792,16 @@ with Ctrl-D, and for a plain no, each together with the config folder being left in place. They run on the default mock lane; the helper's other callers (`rocm fix`, the SDK-overwrite prompt) share it and are covered by its unit tests in [confirm.rs](../crates/rocm-core/src/confirm.rs). -`uninstall-16` to `uninstall-21` cover the protected-location refusal, each -asserting the message together with the folders it leaves: the top of the -filesystem as the data folder (`uninstall-16`), the home folder, with the -advised `--keep-data` then succeeding (`uninstall-17`), shared caches inside the -cache folder named as deleted (`uninstall-18`), a data folder of `.` run from -home (`uninstall-19`), an unmarked folder outside home cleared by the marker -the refusal names (`uninstall-20`), and the dashboard's approved-command path -naming `setup.therock_venv` (`uninstall-21`). +`uninstall-16` to `uninstall-21` cover the protected-location refusal: the top +of the filesystem as the data folder, refused in a dry run (`uninstall-16`); the +home folder, refused with the home file and config folder left in place and the +advised `--keep-data` then succeeding (`uninstall-17`); shared caches inside the +cache folder named as deleted, then kept by `--keep-cache` and really deleted +without it (`uninstall-18`); a data folder of `.` run from home, refused with +nothing removed (`uninstall-19`); an unmarked folder outside home, refused in a +dry run until the marker the refusal names is created (`uninstall-20`); and the +dashboard's approved-command path naming `setup.therock_venv`, with the home +file and config folder left in place (`uninstall-21`). The `uninstall` command does not start the file logger, which would otherwise create the data folder's `logs` folder before the plan is built: diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 1e8e2b2f19..ec8bd08b82 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -145,11 +145,11 @@ Feature: Uninstall # The assistant's uninstall preview (the `rocm_command` tool of the chat # assistant and the dashboard, called here without a model through the hidden - # `rocm mcp-call`) renders the same plan as a dry run, but it has no flag to - # offer, so it says that removal needs approval. It is the one run here that - # cannot pass --keep-binaries: the preview takes no flags and removes nothing, - # and it is made without --allow-mutation, so a call that would remove - # something is refused. + # `rocm mcp-call`) renders the same plan as a dry run, but it has no command + # line to offer, so it says that removal needs approval. It is the one run here + # made without --keep-binaries: the preview reads the --keep-* flags but + # removes nothing, and it is made without --allow-mutation, so a call that + # would remove something is refused. @id:uninstall-assistant-preview-says-removal-needs-approval Scenario: uninstall-12 - The assistant's uninstall preview lists what it would remove, says removal needs approval, and removes nothing Given the config folder holds the user's files @@ -222,6 +222,12 @@ Feature: Uninstall When the user previews an uninstall Then the review warns that the uv and model caches will be deleted with the cache folder And the uv cache is still there after the preview + When the user uninstalls keeping the cache + Then the uninstall succeeds + And the uv cache is still there + When the user uninstalls + Then the uninstall succeeds + And the uv cache is gone # The text of `.` is not the home folder, but the folder it names is. Linux- # only like uninstall-01/-02 in what it claims: the resolution goes through @@ -257,3 +263,4 @@ Feature: Uninstall When the dashboard runs an approved uninstall Then the refusal names setup.therock_venv and advises --keep-data, not a variable the user never set And the user's files in the home folder are still there + And the config folder is still there diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index c4c96609ca..6c967c9bc3 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -747,8 +747,10 @@ async fn config_intact(world: &mut E2eWorld) { #[then("the config folder is gone")] async fn config_gone(world: &mut E2eWorld) { let config = config_dir(world); + // `symlink_metadata`, not `exists`: a folder left behind as a dangling + // link is not gone. assert!( - !config.exists(), + std::fs::symlink_metadata(&config).is_err(), "the uninstall did not remove {}:\n{}", config.display(), output(world) @@ -794,6 +796,33 @@ async fn warns_shared_caches_deleted(world: &mut E2eWorld) { ); } +#[when("the user uninstalls keeping the cache")] +async fn uninstall_keeping_cache(world: &mut E2eWorld) { + run_uninstall(world, &["--yes", "--keep-cache"]); +} + +#[then("the uv cache is still there")] +async fn uv_cache_kept(world: &mut E2eWorld) { + let blob = home(world).join(".cache").join("uv").join("blob"); + assert!( + blob.is_file(), + "--keep-cache did not keep {}:\n{}", + blob.display(), + output(world) + ); +} + +#[then("the uv cache is gone")] +async fn uv_cache_gone(world: &mut E2eWorld) { + let cache = home(world).join(".cache"); + assert!( + std::fs::symlink_metadata(&cache).is_err(), + "the review said the uv cache WILL BE DELETED, but {} is still there:\n{}", + cache.display(), + output(world) + ); +} + #[then("the uv cache is still there after the preview")] async fn uv_cache_intact(world: &mut E2eWorld) { let blob = home(world).join(".cache").join("uv").join("blob"); @@ -1158,9 +1187,9 @@ async fn dry_run_offers_no_step(world: &mut E2eWorld) { /// The assistant's uninstall preview, called without a model through the hidden /// `rocm mcp-call` entry point the dashboard and chat use for their tools. /// -/// The one run here that cannot pass `--keep-binaries`: the preview takes no -/// flags, plans every folder and the binary under test, and renders the plan. It -/// removes nothing, and it is made without `--allow-mutation`, so the tool +/// The one run here made without `--keep-binaries`: called with no flags, the +/// preview plans every folder and the binary under test, and renders the plan. +/// It removes nothing, and it is made without `--allow-mutation`, so the tool /// refuses a call that would remove something instead of running it. #[when("the assistant previews an uninstall")] async fn assistant_previews_uninstall(world: &mut E2eWorld) { @@ -1218,7 +1247,7 @@ async fn preview_says_removal_needs_approval(world: &mut E2eWorld) { text.contains("Nothing was removed. Removal needs your approval."), "the preview must say removal needs approval:\n{text}" ); - // The preview has no flag to offer, so it must not point at one. + // The preview has no command line to offer, so it must not point at one. for phrase in ["run it again", "--dry-run.", "Review uninstall"] { assert!( !text.contains(phrase), From 4ab285e5ac2d622679c24906b7fc15b17e1966a9 Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Fri, 13 Nov 2026 16:26:54 +0200 Subject: [PATCH 4/7] fix(uninstall): say "never removes" only where nothing clears it, and keep uninstall-05 inside the scenario home A refusal ended "ROCm CLI never removes such a folder" for every kind, while an unmarked folder's own advice says creating the marker makes it removable. The claim now comes from the per-kind advice only, for the kinds no marker or setting can clear (the filesystem root, a home folder or one containing it, system and shared folders, other users' homes). uninstall-17 and uninstall-20 assert it with the resulting state, and uninstall-20 now removes the folder for real once it is marked. On native Windows the harness's own config and data folders sit inside C:\Users\, outside the scenario's home, so uninstall-05 was refused as another user's home. It and uninstall-06 now keep their isolated folders inside the scenario home, as the other scenarios do. README names /mnt/wsl and /mnt/wslg, and tests now hold README's list and `rocm uninstall --help` to the real system roots. The system_roots and assistant install-prefix comments state how the runtime rule differs from uninstall's; the architecture entries cover the deletion guards and path sources; a feature comment names the test that exists. Signed-off-by: Roman Inflianskas --- README.md | 2 +- apps/rocm/src/cli.rs | 52 ++++++++- apps/rocm/src/tool_policy.rs | 4 +- apps/rocm/src/uninstall_plan.rs | 70 +++++++++++- crates/rocm-core/src/runtime.rs | 58 +++++++++- docs/architecture.md | 8 +- docs/testing.md | 10 +- tests/e2e-cucumber/features/uninstall.feature | 13 ++- .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 103 +++++++++++++----- 9 files changed, 273 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 301dc4cd08..bf693a8fe5 100644 --- a/README.md +++ b/README.md @@ -1863,7 +1863,7 @@ folder as usual. It never removes: - `/`, your home folder, or a folder that contains it; - `/usr`, `/etc`, `/boot`, `/bin`, `/sbin`, `/lib`, `/lib32`, `/lib64`, `/libx32`, `/sys`, `/proc`, `/dev`, - `/run`, `/media`, `/snap`, or anything inside them — on Windows, `Windows`, + `/run`, `/media`, `/snap`, `/mnt/wsl`, `/mnt/wslg`, or anything inside them — on Windows, `Windows`, `Program Files`, `Program Files (x86)` and `ProgramData` on the system drive, and the same folders on a drive WSL mounts at `/mnt/`; - a folder other programs share: anything directly under `/` (`/opt`, `/srv`, diff --git a/apps/rocm/src/cli.rs b/apps/rocm/src/cli.rs index 73edd26784..f018907241 100644 --- a/apps/rocm/src/cli.rs +++ b/apps/rocm/src/cli.rs @@ -720,7 +720,7 @@ rocm logs --search error timeout")] /// Windows), unless other programs share the install folder. #[command( after_help = "Never removes /, your home folder or one containing it, another user's home, a \ -system location (/usr, /etc, /lib, /run, ...; Windows, Program Files, ProgramData), or a shared \ +system location (/usr, /etc, /lib, /run, ...; Windows, Program Files, ProgramData, ...), or a shared \ folder (anything directly under /, /var/lib, /mnt/, ...). Outside your home folder it \ removes only a folder holding the .rocm-cli-root file ROCm CLI writes into folders it creates. A \ refusal stops the whole uninstall and says what clears it. See the README for the full rules.\n\n\ @@ -2524,6 +2524,56 @@ mod tests { assert!(rows.contains(&"rocm uninstall"), "{examples}"); } + /// Every system folder `rocm uninstall --help` names is one the uninstall + /// really refuses as a system location. The list is abbreviated (`...`), + /// so README carries the whole of it; rocm-core's + /// `readme_names_every_uninstall_system_root` holds README to the code. + /// Each platform's names are checked on that platform's lane. + #[test] + fn uninstall_help_names_only_folders_it_refuses() { + let mut command = cli_command(); + let help = command + .find_subcommand_mut("uninstall") + .expect("uninstall subcommand") + .render_long_help() + .to_string() + .replace('\n', " "); + let list = help + .split_once("system location (") + .and_then(|(_, rest)| rest.split_once(')')) + .map_or_else( + || panic!("no system-location list in:\n{help}"), + |(list, _)| list, + ); + let names: Vec<&str> = list + .split([',', ';']) + .map(str::trim) + .filter(|name| !name.is_empty() && *name != "...") + .collect(); + assert!( + names.contains(&"/usr") && names.contains(&"Windows"), + "{list}" + ); + for name in names { + let path = if name.starts_with('/') { + if !cfg!(unix) { + continue; + } + std::path::PathBuf::from(name) + } else { + if !cfg!(windows) { + continue; + } + std::path::PathBuf::from(format!("{}/{name}", rocm_core::windows_system_drive())) + }; + assert_eq!( + rocm_core::uninstall_root_verdict(&path, None, &[]), + rocm_core::UninstallRootVerdict::Refused(rocm_core::ProtectedLocation::System), + "--help names {name} as a system location" + ); + } + } + #[test] fn update_rejects_zero_timeout_secs() { let error = Cli::try_parse_from(["rocm", "update", "--json", "--timeout-secs", "0"]) diff --git a/apps/rocm/src/tool_policy.rs b/apps/rocm/src/tool_policy.rs index c3fafc9467..24e4a0db0d 100644 --- a/apps/rocm/src/tool_policy.rs +++ b/apps/rocm/src/tool_policy.rs @@ -962,8 +962,8 @@ fn chat_install_prefix_is_system(prefix: &Path) -> bool { } /// Why the local assistant may not install into `prefix`, if it may not: the -/// same protected-location rule every recursive delete uses, since an install -/// folder is one a later uninstall or a broken-venv rebuild may remove. +/// runtime-folder rule `rocm runtimes uninstall` applies to the same folder, +/// since an install folder is one a later uninstall or venv rebuild may remove. pub(crate) fn chat_install_prefix_protection(prefix: &Path) -> Option<&'static str> { if prefix.as_os_str().is_empty() { return Some("an empty path"); diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 9f43906d3b..7311c65e57 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -181,13 +181,18 @@ impl RefusedRoot { config.json or runtime registry inside it is not taken as proof that it is \ ROCm CLI's.", ), - rocm_core::ProtectedLocation::SharedTopLevel + // No marker or setting makes these removable, so the claim holds. + rocm_core::ProtectedLocation::FilesystemRoot + | rocm_core::ProtectedLocation::Home + | rocm_core::ProtectedLocation::ContainsHome + | rocm_core::ProtectedLocation::SharedTopLevel | rocm_core::ProtectedLocation::OtherUsersHome | rocm_core::ProtectedLocation::System => sentence.push_str( " ROCm CLI never removes this folder itself; if you are sure what in it is \ ROCm CLI's, remove those files by hand.", ), - _ => {} + // Removable once it resolves, so "never" would be false. + rocm_core::ProtectedLocation::Unresolvable => {} } sentence } @@ -259,9 +264,11 @@ impl UninstallPlan { .map(|root| format!("the {} folder {}", root.kind, root.describe())) .collect::>() .join("; "); + // No blanket "never removes" here: an unmarked folder becomes + // removable once it carries the marker, which its advice says. The + // advice adds that sentence only for the kinds it is true of. Some(format!( - "uninstall refused, nothing was removed: {reasons}, and ROCm CLI never removes \ - such a folder. {advice}" + "uninstall refused, nothing was removed: {reasons}. {advice}" )) } } @@ -1336,6 +1343,11 @@ mod tests { "{error}" ); assert!(error.contains("--keep-data"), "{error}"); + // True of `/`: the plan above holds no entry for it, whatever is set. + assert!( + error.contains("ROCm CLI never removes this folder itself"), + "{error}" + ); let rendered = super::render_uninstall_plan( &plan, &super::UninstallOptions { @@ -1742,6 +1754,53 @@ mod tests { } } + /// A refusal says ROCm CLI never removes the folder only where no marker, + /// setting or later run can make it removable: `NotMarked` clears once the + /// marker exists (`creating_the_advised_marker_clears_the_refusal`), and + /// `Unresolvable` once the folder resolves. `never` is an exhaustive + /// match, so a new kind fails to compile here until it is decided. + #[test] + fn only_a_refusal_nothing_can_clear_says_never_removes() { + use rocm_core::ProtectedLocation as Why; + const fn never(why: Why) -> bool { + match why { + Why::FilesystemRoot + | Why::Home + | Why::ContainsHome + | Why::System + | Why::OtherUsersHome + | Why::SharedTopLevel => true, + Why::NotMarked | Why::Unresolvable => false, + } + } + for why in [ + Why::FilesystemRoot, + Why::Home, + Why::ContainsHome, + Why::System, + Why::OtherUsersHome, + Why::SharedTopLevel, + Why::NotMarked, + Why::Unresolvable, + ] { + let never = never(why); + let refused = super::RefusedRoot { + kind: "data", + path: PathBuf::from("/x"), + resolved: None, + real: None, + why, + source: rocm_core::AppPathSource::Default, + }; + let plan = super::UninstallPlan { + refused: vec![refused], + ..super::UninstallPlan::default() + }; + let error = plan.refusal_error().expect("refused"); + assert_eq!(error.contains("never removes"), never, "{why:?}: {error}"); + } + } + fn sandbox(label: &str) -> PathBuf { let root = std::env::temp_dir().join(format!("rocm-{label}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); @@ -1807,6 +1866,9 @@ mod tests { marker.display() ); assert!(error.contains(&advised), "{error}"); + // The error must not also claim the folder is never removed: the rest + // of this test removes it by following the advice. + assert!(!error.contains("never removes"), "{error}"); // Follow the advice. std::fs::write(&marker, b"").unwrap(); diff --git a/crates/rocm-core/src/runtime.rs b/crates/rocm-core/src/runtime.rs index 861978d56d..f44fe1c891 100644 --- a/crates/rocm-core/src/runtime.rs +++ b/crates/rocm-core/src/runtime.rs @@ -828,10 +828,15 @@ pub fn runtime_protected_location_for_home( } /// The system locations a runtime folder may not be in. On Windows these are -/// `rocm uninstall`'s own, on the system drive; on Unix the list differs from -/// [`uninstall_system_roots`] on purpose: `/opt` and `/var` are refused here -/// (a runtime prefix there is the system's), while `rocm uninstall` refuses -/// only their top level and lets a marked folder below them go. +/// `rocm uninstall`'s own, on the system drive. On Unix the two lists differ +/// both ways. `/opt`, `/var` and `/root` are refused here (a runtime prefix +/// there is the system's), while `rocm uninstall` refuses only their top level +/// and lets a marked folder below them go. And `/lib32`, `/libx32`, `/run`, +/// `/media`, `/snap`, `/mnt/wsl` and `/mnt/wslg`, which [`uninstall_system_roots`] +/// refuses, are not refused here, so `rocm runtimes uninstall`, `rocm storage +/// remove-old-installs` and the assistant's SDK `--prefix` check accept a +/// folder inside them. Adding them would change what those accept; the two +/// lists have not been reconciled. fn system_roots(platform: RuntimePlatform) -> Vec { if platform.is_windows() { return uninstall_system_roots_on(platform, &windows_system_drive()); @@ -2160,6 +2165,51 @@ mod tests { } } + /// README's "It never removes" list names exactly the system roots + /// `rocm uninstall` refuses, on both platforms: every root in the list is + /// named there, and every system folder named there is refused as one. + /// Not `cfg(unix)`: both platforms are parameters, so this runs on every + /// lane. + #[test] + fn readme_names_every_uninstall_system_root() { + let readme = include_str!("../../../README.md"); + let section = readme + .split_once("It never removes:") + .and_then(|(_, rest)| rest.split_once("Anywhere else outside your home folder")) + .map(|(section, _)| section) + .expect("README's `rocm uninstall` section lists what it never removes"); + let bullet = section + .split("\n- ") + .find(|bullet| bullet.starts_with("`/usr`")) + .expect("the system-folder bullet"); + let named: Vec<&str> = bullet.split('`').skip(1).step_by(2).collect(); + for (platform, drive) in [ + (RuntimePlatform::Linux, "C:"), + (RuntimePlatform::Windows, "C:"), + ] { + for root in uninstall_system_roots_on(platform, drive) { + let shown = if platform.is_windows() { + root.file_name().unwrap().to_string_lossy().into_owned() + } else { + root.display().to_string() + }; + assert!(named.contains(&shown.as_str()), "README omits `{shown}`"); + } + } + for name in named.iter().filter(|name| !name.contains('<')) { + let (path, platform) = if name.starts_with('/') { + ((*name).to_owned(), RuntimePlatform::Linux) + } else { + (format!("C:/{name}"), RuntimePlatform::Windows) + }; + assert_eq!( + uninstall_root_verdict_on(Path::new(&path), None, &[], platform, "C:"), + UninstallRootVerdict::Refused(ProtectedLocation::System), + "README names `{name}` as a system folder" + ); + } + } + // ── Properties: the recursive-delete guard ───────────────────── // // `runtime_protected_location` is the runtime-folder rule for diff --git a/docs/architecture.md b/docs/architecture.md index 63d21acb40..46dc9e0565 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -107,7 +107,7 @@ The `rocm` binary: the clap command tree, a handler module for most commands, an | [`runtime_install_finalize/torch_alignment.rs`](../apps/rocm/src/runtime_install_finalize/torch_alignment.rs) | Whether an engine install realigns the runtime's torch to the engine's pin or keeps it as an intended divergence, running and reporting that, and the manifest readers it uses. | domain | | [`runtime_registry.rs`](../apps/rocm/src/runtime_registry.rs) | The installed-runtime registry: the manifest model, where manifests live, writing and loading them, selection and activation validation, and the active-runtime marker. | domain | | [`runtime_services.rs`](../apps/rocm/src/runtime_services.rs) | Reconciling running local servers with a runtime being activated or rolled back: classifying each, the report, and moving stale ones with `--restart-services`. | domain | -| [`runtime_uninstall.rs`](../apps/rocm/src/runtime_uninstall.rs) | `rocm runtimes uninstall`: planning, revalidating after the prompt, and applying the removal of a registered runtime, including clearing a Lemonade record inside its folder. | domain | +| [`runtime_uninstall.rs`](../apps/rocm/src/runtime_uninstall.rs) | `rocm runtimes uninstall`: planning, revalidating after the prompt, and applying the removal of a registered runtime, including clearing a Lemonade record inside its folder; a protected folder is refused with the reason `ProtectedLocation::describe` gives. | domain | | [`runtimes_cmd.rs`](../apps/rocm/src/runtimes_cmd.rs) | `rocm runtimes` (`runtimes`): activation and rollback with the active-runtime marker write, and the runtime list. | relocation | | [`serve_cmd.rs`](../apps/rocm/src/serve_cmd.rs) | `rocm serve` (`serve`): engine selection (`select_serve_engine`), the AIM pre-flight, and the GPU and device notes folded into the summary. | relocation | | [`serve_port.rs`](../apps/rocm/src/serve_port.rs) | The `rocm serve` port policy: turns an automatic or explicit `--port` request into one leased port before any manifest, log, key or child exists. | domain | @@ -274,7 +274,7 @@ The library every first-party app and engine crate depends on. It holds host exa | [`command_capture.rs`](../crates/rocm-core/src/command_capture.rs) | Runs the `rocm` CLI as a child process and captures what it printed (`CommandCapture`, `run_rocm_capture_with_env`, `command_capture_text`). `CommandCapture` is also what [`process/bounded.rs`](../crates/rocm-core/src/process/bounded.rs)'s `run_bounded` returns for the host probes: the lossy text and `exit_status`, the raw bytes of both streams, a typed `CommandOutcome` (not found, spawn failed, timed out, wait failed, exited with a code, killed by a signal) and the status and error text the executor saw; a capture answered without a child is built with `CommandCapture::from_text`. | domain | | [`config.rs`](../crates/rocm-core/src/config.rs) | The unified `RocmCliConfig` and its sections, including `WatcherMode`, the built-in watcher catalog and the rocm-dash dashboard sub-config with its legacy-TOML migration. | domain | | [`config_proptests.rs`](../crates/rocm-core/src/config_proptests.rs) | Property tests for the persisted `config.json` (`RocmCliConfig`) and its one-shot migration from the legacy rocm-dash `config.toml`: save and load round trips, and a save that never writes a file load rejects. Each property counts how often the generator reached the edge classes (absent optionals, empty and non-ASCII strings, non-finite floats) and fails a run that never did. Declared from [`config.rs`](../crates/rocm-core/src/config.rs). | flat | -| [`confirm.rs`](../crates/rocm-core/src/confirm.rs) | The shared `[y/N]` prompt (`print_prompt`, `read_answer`), `interactive_terminal`, and the `require_yes_or_interactive` guard for `--yes`-gated commands. | domain | +| [`confirm.rs`](../crates/rocm-core/src/confirm.rs) | The shared `[y/N]` prompt (`print_prompt`, `read_answer`), `interactive_terminal`, and the `require_yes_or_interactive` guard for `--yes`-gated commands (`require_yes_or_interactive_with` takes the terminal check as an argument). | domain | | [`crypto.rs`](../crates/rocm-core/src/crypto.rs) | Generic RSASSA-PKCS#1 v1.5 over SHA-256 sign and verify, with no external `openssl` process. | domain | | [`diagnose.rs`](../crates/rocm-core/src/diagnose.rs) | Root of `rocm diagnose`: the public result types, the score thresholds, `diagnose` itself, and the vLLM symptom classifiers that run the whole catalog. | domain | | [`diagnose/catalog.rs`](../crates/rocm-core/src/diagnose/catalog.rs) | The checker table: which check runs on which platform family and in what order, and how the family is resolved from an `Examination`. | domain | @@ -333,7 +333,7 @@ The library every first-party app and engine crate depends on. It holds host exa | [`openmpi.rs`](../crates/rocm-core/src/openmpi.rs) | OpenMPI, libatomic and libnuma detection, the `libmpi_cxx` compatibility shim, and the per-library install plans and hints vLLM's ROCm wheels need. | flat | | [`os_release.rs`](../crates/rocm-core/src/os_release.rs) | The one `/etc/os-release` parser, reading the file as a POSIX shell sourcing it would. | flat | | [`package_plan.rs`](../crates/rocm-core/src/package_plan.rs) | Distro-generic package install planning: `PackageManager` resolution, the plan types, the root and passwordless-`sudo` checks, and the `apt-get -s` safety helpers. It never executes a plan; the one process it starts is `sudo -n true`, behind `can_autoinstall`. | flat | -| [`paths.rs`](../crates/rocm-core/src/paths.rs) | `AppPaths` (config, data and cache roots and their per-engine and per-service subpaths), the managed-root override and engine plugin directories, and `AppPaths::env_vars`, the three `ROCM_CLI_*_DIR` variables that make a child process run on the same roots, with the constants that name them (`CONFIG_DIR_ENV`, `DATA_DIR_ENV`, `CACHE_DIR_ENV`, `ENGINE_ENVS_ROOT_ENV`). | domain | +| [`paths.rs`](../crates/rocm-core/src/paths.rs) | `AppPaths` (config, data and cache roots and their per-engine and per-service subpaths), the managed-root override and engine plugin directories, and `AppPaths::env_vars`, the three `ROCM_CLI_*_DIR` variables that make a child process run on the same roots, with the constants that name them (`CONFIG_DIR_ENV`, `DATA_DIR_ENV`, `CACHE_DIR_ENV`, `ENGINE_ENVS_ROOT_ENV`); `AppPaths::discover_with_sources` also reports which setting chose each root (`AppPathSource`), forwarded to child processes through `APP_PATH_SOURCES_ENV` (`ForwardedAppPathSources`) so their refusals name the right setting. | domain | | [`persisted_paths_props.rs`](../crates/rocm-core/src/persisted_paths_props.rs) | Property test that `RocmCliConfig::load` and `AppPaths::discover` agree about where the data dir is: a `config.json` that cannot be read makes discovery fail or still find the recorded managed root, never silently fall back to the default data dir. Declared from [`paths.rs`](../crates/rocm-core/src/paths.rs). | flat | | [`placeholder.rs`](../crates/rocm-core/src/placeholder.rs) | The `` placeholder rendered reports print for an empty value (`empty_as_unknown`, `trimmed_or_unknown`). | domain | | [`probe_exec.rs`](../crates/rocm-core/src/probe_exec.rs) | Subprocess and file-read helpers for the host probes: `run` under a timeout (`run`, `run_with_env` and `run_raw` are thin adapters over [`process/bounded.rs`](../crates/rocm-core/src/process/bounded.rs)'s `run_bounded`; `rc` is `127` when the program cannot be spawned, `124` on a timeout or a failure to wait and `-1` for a child killed by a signal), `which`, `read_text` and `read_host_text`. | domain | @@ -347,7 +347,7 @@ The library every first-party app and engine crate depends on. It holds host exa | [`report_rollup.rs`](../crates/rocm-core/src/report_rollup.rs) | Counts Doctor reports at every level of `Report::group_key`, keeping refused and unread reports apart. | domain | | [`report_trend.rs`](../crates/rocm-core/src/report_trend.rs) | Weekly counts of Doctor reports, and the weeks in which a known problem rose sharply. | domain | | [`rocm_install.rs`](../crates/rocm-core/src/rocm_install.rs) | Discovery of unmanaged ("legacy") ROCm installs: `LegacyRocmSummary`, the install-layout search and version ranking. | domain | -| [`runtime.rs`](../crates/rocm-core/src/runtime.rs) | The host-platform layer: `RuntimePlatform`/`RuntimeHost`, OS-specific executable and Python-environment names, default directories, path helpers and `install_root_has_payload`. | flat | +| [`runtime.rs`](../crates/rocm-core/src/runtime.rs) | The host-platform layer: `RuntimePlatform`/`RuntimeHost`, OS-specific executable and Python-environment names, default directories, path helpers and `install_root_has_payload`; and the deletion guards: `ProtectedLocation` (why a folder may not be removed), `runtime_protected_location[_for_home]` for runtime folders, `uninstall_root_verdict` and `uninstall_system_roots` for `rocm uninstall`'s config, data and cache roots, and the `ROCM_CLI_ROOT_MARKER` file that `create_marked_root`/`mark_root` write into a folder ROCm CLI created. | flat | | [`service_identity.rs`](../crates/rocm-core/src/service_identity.rs) | `ServiceId`, the validator every per-service id should pass before it reaches a path builder, and `generate_service_id` for a new launch. | domain | | [`service_record.rs`](../crates/rocm-core/src/service_record.rs) | `ManagedServiceRecord`, the on-disk manifest of a managed inference service, and the engine state-file keys that tie it to readiness probing. | domain | | [`sigpipe.rs`](../crates/rocm-core/src/sigpipe.rs) | `with_sigpipe_ignored`, which turns a write to a pipe whose reader has gone into an ordinary error instead of a signal; `rocm` runs with SIGPIPE at its default action, so the engine stdio client wraps its write to the child, and each write forwarding the child's stderr to its own, in it. Guarded regions may overlap, across threads too; the disposition in force before the first is put back when the last ends. | domain | diff --git a/docs/testing.md b/docs/testing.md index b25c381f99..26009ccbdb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1841,12 +1841,14 @@ the SDK-overwrite prompt) share it and are covered by its unit tests in [confirm.rs](../crates/rocm-core/src/confirm.rs). `uninstall-16` to `uninstall-21` cover the protected-location refusal: the top of the filesystem as the data folder, refused in a dry run (`uninstall-16`); the -home folder, refused with the home file and config folder left in place and the -advised `--keep-data` then succeeding (`uninstall-17`); shared caches inside the +home folder, refused with the home file and config folder left in place, saying +ROCm CLI never removes that folder, and the advised `--keep-data` then +succeeding (`uninstall-17`); shared caches inside the cache folder named as deleted, then kept by `--keep-cache` and really deleted without it (`uninstall-18`); a data folder of `.` run from home, refused with -nothing removed (`uninstall-19`); an unmarked folder outside home, refused in a -dry run until the marker the refusal names is created (`uninstall-20`); and the +nothing removed (`uninstall-19`); an unmarked folder outside home, refused with +it left in place and without a claim that it is never removed, then, once the +marker the refusal names is created, planned and really removed (`uninstall-20`); and the dashboard's approved-command path naming `setup.therock_venv`, with the home file and config folder left in place (`uninstall-21`). The `uninstall` command does not start the file logger, which would otherwise diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index ec8bd08b82..5280bf43d1 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -192,7 +192,7 @@ Feature: Uninstall # Linux-only: on Windows `/` names the current drive's root and renders as # `\`, so this line would read differently. The Windows drive-root refusal is - # covered only by rocm-core's `a_windows_drive_root_is_the_filesystem_root` + # covered only by rocm-core's `windows_roots_follow_the_system_drive` # unit test, not end to end. @id:uninstall-filesystem-root-refused @requires-os:linux Scenario: uninstall-16 - A data folder set to the top of the filesystem is refused @@ -208,6 +208,7 @@ Feature: Uninstall When the user uninstalls Then the uninstall is refused because the data folder "" is "your home folder" And the refusal says nothing was removed + And the refusal says ROCm CLI never removes that folder itself And the refusal advises re-running with --keep-data And the user's files in the home folder are still there And the config folder is still there @@ -242,17 +243,25 @@ Feature: Uninstall And the config folder is still there # A real folder outside the home folder is only removed when ROCm CLI marked - # it as its own. The refusal says how to mark it; doing so clears it. + # it as its own. The refusal says how to mark it, and does not claim ROCm CLI + # never removes it; marking it clears the refusal and a real run removes it. # Linux-only: on Windows the scenario root sits inside the runner's own user # folder, where a folder outside the scenario home is another user's home. @id:uninstall-unmarked-folder-refused-until-marked @requires-os:linux Scenario: uninstall-20 - A data folder outside home without ROCm CLI's marker is refused until the advised marker exists Given the data folder is a folder outside the home folder without ROCm CLI's marker + When the user uninstalls + Then the refusal says nothing was removed + And the refusal does not say ROCm CLI never removes that folder + And the data folder outside the home folder is still there When the user previews an uninstall Then the refusal advises creating the marker if the folder is ROCm CLI's When the user creates the marker the refusal named And the user previews an uninstall Then the preview plans to remove the data folder + When the user uninstalls + Then the uninstall succeeds + And the data folder outside the home folder is gone # The dashboard and the assistant run an approved `rocm uninstall` as a # child process with the folders pinned. The refusal must still name the diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index 6c967c9bc3..b53951e9ee 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -428,10 +428,24 @@ fn default_cache(world: &E2eWorld) -> PathBuf { home(world).join(".rocm").join("cache") } +/// The config folder an install isolated by `ROCM_CLI_CONFIG_DIR` and +/// `ROCM_CLI_DATA_DIR` alone uses. Inside the scenario's home but not under +/// `~/.rocm`: on Windows the scenario root is itself under +/// `C:\\Users\\`, so a folder outside the scenario home would be +/// another user's home there, and refused. +fn isolated_config(world: &E2eWorld) -> PathBuf { + home(world).join("rocm-isolated").join("config") +} + +/// The data folder of that isolated install; see [`isolated_config`]. +fn isolated_data(world: &E2eWorld) -> PathBuf { + home(world).join("rocm-isolated").join("data") +} + /// Where the cache folder belongs when only the config and data folders are -/// set: inside the scenario's data folder, the one `isolate_env` hands the CLI. +/// set: inside the isolated install's data folder. fn data_cache(world: &E2eWorld) -> PathBuf { - world.app_paths().data_dir.join("cache") + isolated_data(world).join("cache") } /// Run `rocm` with the config and data folders set but no cache folder, as an @@ -444,11 +458,15 @@ fn run_without_cache_setting(world: &mut E2eWorld, args: &[&str]) { let home = home(world); std::fs::create_dir_all(&home).expect("failed to create isolated HOME"); let home = home.display().to_string(); + let config = isolated_config(world).display().to_string(); + let data = isolated_data(world).display().to_string(); let uv = root.join("uv-cache").display().to_string(); let hf = root.join("hf-home").display().to_string(); let envs = [ ("HOME", home.as_str()), ("USERPROFILE", home.as_str()), + ("ROCM_CLI_CONFIG_DIR", config.as_str()), + ("ROCM_CLI_DATA_DIR", data.as_str()), ("UV_CACHE_DIR", uv.as_str()), ("HF_HOME", hf.as_str()), ]; @@ -471,15 +489,7 @@ async fn data_cache_holds_file(world: &mut E2eWorld) { let cache = data_cache(world); std::fs::create_dir_all(&cache).expect("failed to create the data folder's cache folder"); std::fs::write(cache.join("cached.bin"), "cached").expect("failed to write cache file"); - // The harness's config and data folders sit outside the scenario's home, - // where `rocm uninstall` removes only a folder ROCm CLI marked as its own. - // They stand for an install ROCm CLI created, so they carry its marker, - // and so does the cache folder it would have created inside the data one. - let paths = world.app_paths(); - for folder in [paths.config_dir, paths.data_dir, cache] { - std::fs::write(folder.join(".rocm-cli-root"), "created by ROCm CLI\n") - .expect("failed to mark the folder as ROCm CLI's own"); - } + std::fs::create_dir_all(isolated_config(world)).expect("failed to create the config folder"); } #[when("the user asks what ROCm CLI keeps on disk with only the config and data folders set")] @@ -533,8 +543,9 @@ async fn uninstall_skips_default_cache(world: &mut E2eWorld) { #[then("the data folder's own cache folder is gone")] async fn data_cache_gone(world: &mut E2eWorld) { let cache = data_cache(world); + // `symlink_metadata`, not `exists`: a dangling link left behind is not gone. assert!( - !cache.exists(), + std::fs::symlink_metadata(&cache).is_err(), "the uninstall left {} behind: {}", cache.display(), @@ -555,27 +566,19 @@ async fn default_cache_intact(world: &mut E2eWorld) { /// Every place the CLI keeps state when only the config and data folders are /// set: those two, the cache folder inside the data folder, and the default -/// `~/.rocm` that a stray write would land in. The harness's own cache folder -/// is left out because a runner may share it between scenarios. +/// `~/.rocm` that a stray write would land in. fn state_folders(world: &E2eWorld) -> Vec { - let paths = world.app_paths(); vec![ - paths.config_dir, - paths.data_dir.clone(), - paths.data_dir.join("cache"), + isolated_config(world), + isolated_data(world), + data_cache(world), home(world).join(".rocm"), ] } #[given("ROCm CLI has never created its folders in the user's home")] async fn no_folders_yet(world: &mut E2eWorld) { - // The harness creates the config, data and cache folders empty before each - // scenario; a machine ROCm CLI never touched has none of them. - for sub in ["config", "data", "cache"] { - let folder = root(world).join(sub); - std::fs::remove_dir(&folder) - .unwrap_or_else(|e| panic!("failed to remove the empty {}: {e}", folder.display())); - } + // A machine ROCm CLI never touched has none of the folders it would use. for folder in state_folders(world) { assert!( std::fs::symlink_metadata(&folder).is_err(), @@ -721,6 +724,33 @@ async fn refusal_says_nothing_removed(world: &mut E2eWorld) { ); } +/// The sentence a refusal adds only where nothing can make the folder +/// removable (rocm's `RefusedRoot::advice`). +const NEVER_REMOVES: &str = "ROCm CLI never removes this folder itself"; + +#[then("the refusal says ROCm CLI never removes that folder itself")] +async fn refusal_says_never_removes(world: &mut E2eWorld) { + // The scenario's later steps hold the claim to the state: the folder and + // the files in it are still there after the refusal. + assert!( + stderr(world).contains(NEVER_REMOVES), + "stderr:\n{}", + stderr(world) + ); +} + +#[then("the refusal does not say ROCm CLI never removes that folder")] +async fn refusal_does_not_say_never_removes(world: &mut E2eWorld) { + // The scenario goes on to mark the folder and remove it, which is why the + // claim would be false here. Any wording of it, not only today's sentence. + assert!( + !stderr(world).contains("never removes") && !output(world).contains("never removes"), + "an unmarked folder becomes removable once marked:\n{}\n{}", + output(world), + stderr(world) + ); +} + #[then("the user's files in the home folder are still there")] async fn home_files_intact(world: &mut E2eWorld) { let file = user_file_in_home(world); @@ -939,6 +969,29 @@ async fn preview_plans_data(world: &mut E2eWorld) { assert!(!stdout.contains("Refused"), "{stdout}"); } +#[then("the data folder outside the home folder is still there")] +async fn unmarked_data_intact(world: &mut E2eWorld) { + let file = unmarked_data(world).join("keep.txt"); + assert!( + file.is_file(), + "the refused uninstall deleted {}:\n{}\n{}", + file.display(), + output(world), + stderr(world) + ); +} + +#[then("the data folder outside the home folder is gone")] +async fn unmarked_data_gone(world: &mut E2eWorld) { + let data = unmarked_data(world); + assert!( + std::fs::symlink_metadata(&data).is_err(), + "the marked data folder {} was not removed:\n{}", + data.display(), + output(world) + ); +} + #[given("setup.therock_venv points at the user's home folder, which holds their files")] async fn venv_is_home(world: &mut E2eWorld) { let file = user_file_in_home(world); From 15b6bd8db766ec610087efbb978f041e6a198153 Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Fri, 13 Nov 2026 17:09:57 +0200 Subject: [PATCH 5/7] fix(uninstall): judge a file or link root by where its folder really is A config, data or cache setting naming a file or a link was judged by its spelling alone: with ~/x a link to /etc, ~/x/config.json passed as inside home and the uninstall unlinked /etc/config.json. A non-directory root is now judged by its resolved folder under its own name, so that one is refused as the system file it is, while a root that is itself a link is still only unlinked, never followed (uninstall-22, and unit tests for a file through a linked folder and a link pointing at a system location). A system location that exists but cannot be resolved used to drop out of the comparison silently, leaving its real place unprotected; the root is now refused as unresolvable instead. Each place that creates and marks a folder ROCm CLI owns (the tarball --prefix, the metadata cache, the vLLM cache) now has a test that a folder it creates is marked and an existing one is not; the tarball and metadata steps move into small helpers for that. Also tested: the assistant refusing the home folder as an SDK --prefix, and the dashboard's /uninstall naming an unknown flag on its own and ahead of the --apply/--dry-run conflict. Signed-off-by: Roman Inflianskas --- README.md | 6 +- apps/rocm/src/therock.rs | 42 ++- apps/rocm/src/therock/fetch.rs | 41 ++- apps/rocm/src/tool_policy.rs | 28 ++ apps/rocm/src/uninstall_plan.rs | 246 ++++++++++++++++-- crates/rocm-dash-tui/src/app/slash.rs | 23 ++ docs/testing.md | 8 +- engines/vllm/src/install.rs | 28 ++ tests/e2e-cucumber/features/uninstall.feature | 15 ++ .../e2e-cucumber/tests/e2e/uninstall_steps.rs | 43 +++ 10 files changed, 452 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index bf693a8fe5..f0fbc65878 100644 --- a/README.md +++ b/README.md @@ -1883,7 +1883,11 @@ or one some other command happened to create first is not marked, and is refused rather than removed until you create the file or keep the folder. The check looks at where a folder really is as well as how it is written, so `ROCM_CLI_DATA_DIR=.` run from your home folder, a home reached through a linked parent folder, or a system folder reached through a link is -caught too. +caught too. A setting that names a file or a link rather than a folder is +judged by where its folder really is: with `~/x` a link to `/etc`, +`~/x/config.json` is refused as `/etc/config.json`. The link itself is only +unlinked, never followed. If a system folder that exists cannot be resolved, +nothing can be judged against it, so the uninstall is refused as unresolvable. If a folder is refused (for example `ROCM_CLI_DATA_DIR=/`, or an SDK installed with `--prefix ~`), the review lists it under "Refused" with why and the diff --git a/apps/rocm/src/therock.rs b/apps/rocm/src/therock.rs index b3a930fb7b..7db4141a11 100644 --- a/apps/rocm/src/therock.rs +++ b/apps/rocm/src/therock.rs @@ -953,9 +953,7 @@ fn install_tarball_runtime( } } - fs::create_dir_all(paths.cache_dir.join("therock"))?; - rocm_core::create_marked_root(&install_root)?; - ensure_tarball_install_target_is_clean(&install_root)?; + prepare_tarball_install_root(paths, &install_root)?; if let Some(warning) = preflight_tarball_space(&artifact.url, &cache_path, &install_root)? { let _ = writeln!(output, " {warning}"); @@ -1104,6 +1102,16 @@ fn resolved_install_root( rocm_core::resolve_path_through_symlinks(&requested) } +/// The folders a tarball install writes to before it downloads: the TheRock +/// download cache, and `install_root`, marked as ROCm CLI's own when this is +/// what creates it (so `rocm uninstall` may remove it later) and refused when +/// it already holds something. +fn prepare_tarball_install_root(paths: &AppPaths, install_root: &Path) -> Result<()> { + fs::create_dir_all(paths.cache_dir.join("therock"))?; + rocm_core::create_marked_root(install_root)?; + ensure_tarball_install_target_is_clean(install_root) +} + /// Refuses to extract a tarball into a root that already holds a payload. /// /// "Holds a payload" is [`rocm_core::install_root_has_payload`]: dot-entries (the @@ -1714,6 +1722,34 @@ mod tests { ); } + /// A tarball install marks the install folder as ROCm CLI's own when it + /// creates it, so `rocm uninstall` may remove it later, and leaves an + /// existing empty folder unmarked. + #[test] + fn a_tarball_install_marks_the_install_folder_it_creates_and_not_an_existing_one() { + let base = tempfile::tempdir().expect("scratch dir"); + let paths = AppPaths { + config_dir: base.path().join("config"), + data_dir: base.path().join("data"), + cache_dir: base.path().join("cache"), + }; + let fresh = base.path().join("new-prefix"); + prepare_tarball_install_root(&paths, &fresh).expect("a new folder is prepared"); + assert!( + fresh.join(rocm_core::ROCM_CLI_ROOT_MARKER).is_file(), + "the install folder it created is not marked" + ); + assert!(paths.cache_dir.join("therock").is_dir()); + + let existing = base.path().join("existing-prefix"); + fs::create_dir_all(&existing).unwrap(); + prepare_tarball_install_root(&paths, &existing).expect("an empty folder is clean"); + assert!( + !existing.join(rocm_core::ROCM_CLI_ROOT_MARKER).exists(), + "an existing install folder was marked" + ); + } + /// The extraction guard refuses a root that holds a payload and says so, and /// it follows `rocm_core::install_root_has_payload` for what that means: a /// root that does not exist yet (the case `install_tarball_runtime` hits when diff --git a/apps/rocm/src/therock/fetch.rs b/apps/rocm/src/therock/fetch.rs index 018555d63b..3b05e471c5 100644 --- a/apps/rocm/src/therock/fetch.rs +++ b/apps/rocm/src/therock/fetch.rs @@ -416,9 +416,7 @@ pub(super) fn download_text_cached( let cache_dir = body_path .parent() .context("metadata cache path has no parent directory")?; - // The cache folder itself is ROCm CLI's own when this is what creates it. - rocm_core::create_marked_root(&paths.cache_dir)?; - fs::create_dir_all(cache_dir)?; + prepare_metadata_cache_dir(paths, cache_dir)?; let tmp_public_key = body_path.with_extension("public-key.pem"); let mut headers = Vec::new(); @@ -472,6 +470,14 @@ pub(super) fn download_text_cached( Ok(CachedHttpText { text: entry.body }) } +/// Creates `cache_dir`, the metadata folder inside the cache folder, marking +/// the cache folder itself as ROCm CLI's own when this is what creates it. +fn prepare_metadata_cache_dir(paths: &AppPaths, cache_dir: &Path) -> Result<()> { + rocm_core::create_marked_root(&paths.cache_dir)?; + fs::create_dir_all(cache_dir)?; + Ok(()) +} + fn metadata_cache_paths(paths: &AppPaths, cache_key: &str) -> (PathBuf, PathBuf) { let base = paths .cache_dir @@ -805,6 +811,35 @@ mod tests { assert_eq!(leftovers, vec![OsString::from("index.json")]); } + /// The metadata download marks the cache folder as ROCm CLI's own when it + /// creates it, so `rocm uninstall` may remove it later, and leaves a cache + /// folder that already existed unmarked. + #[test] + fn the_metadata_cache_marks_a_cache_folder_it_creates_and_not_an_existing_one() { + let (root, fresh) = test_paths("metadata-cache-marks"); + let (body, _) = metadata_cache_paths(&fresh, "key"); + prepare_metadata_cache_dir(&fresh, body.parent().unwrap()).unwrap(); + let fresh_marked = fresh + .cache_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .is_file(); + let metadata_dir_made = body.parent().unwrap().is_dir(); + + let (other_root, existing) = test_paths("metadata-cache-keeps-existing"); + fs::create_dir_all(&existing.cache_dir).unwrap(); + let (body, _) = metadata_cache_paths(&existing, "key"); + prepare_metadata_cache_dir(&existing, body.parent().unwrap()).unwrap(); + let existing_marked = existing + .cache_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .exists(); + let _ = fs::remove_dir_all(&root); + let _ = fs::remove_dir_all(&other_root); + assert!(fresh_marked, "the cache folder it created is not marked"); + assert!(metadata_dir_made); + assert!(!existing_marked, "an existing cache folder was marked"); + } + #[test] fn metadata_cache_paths_stay_under_rocm_cli_cache() { let (root, paths) = test_paths("metadata-cache-paths"); diff --git a/apps/rocm/src/tool_policy.rs b/apps/rocm/src/tool_policy.rs index 24e4a0db0d..dda338198d 100644 --- a/apps/rocm/src/tool_policy.rs +++ b/apps/rocm/src/tool_policy.rs @@ -2660,6 +2660,34 @@ mod tests { ); } + /// The assistant may not install the SDK into the home folder itself, which + /// a later uninstall or venv rebuild would remove, and the refusal says + /// why; a folder inside home is still accepted. Through the shared check + /// and through the `rocm install sdk` command a model's call goes by. + #[test] + fn the_assistant_cannot_install_into_the_home_folder_itself() { + use crate::test_support::owned_argv; + let home = rocm_core::runtime_home_dir().expect("a home directory"); + assert_eq!( + chat_install_prefix_protection(&home), + Some("your home folder") + ); + assert_eq!(chat_install_prefix_protection(&home.join("rocm")), None); + + let home_text = home.display().to_string(); + let error = validate_chat_rocm_command_safety(&owned_argv(&[ + "install", "sdk", "--format", "wheel", "--prefix", &home_text, + ])) + .expect_err("the home folder as install folder must be refused") + .to_string(); + assert!(error.contains("it is your home folder"), "{error}"); + let inside = home.join("rocm").display().to_string(); + validate_chat_rocm_command_safety(&owned_argv(&[ + "install", "sdk", "--format", "wheel", "--prefix", &inside, + ])) + .expect("a folder inside home is a valid install folder"); + } + /// The serve safety rules as the chat assistant meets them: every refusal in /// the shared table, through the safety check itself and through the two /// entry points a model's `rocm_command` call goes by. A refused call yields diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 7311c65e57..7da241ed6b 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -292,9 +292,10 @@ pub(crate) enum RootJudgment { } /// Judge the root `path` by [`rocm_core::uninstall_root_verdict`]: on its -/// spelling first, then — for a real directory, the only kind removed -/// recursively — on where it really is against where home and the system -/// locations really are. `.` run from home, `..` run from `~/proj`, home +/// spelling first, then on where it really is against where home and the +/// system locations really are — a real directory, the only kind removed +/// recursively, as a whole; a file or link by its resolved folder and its own +/// name. `.` run from home, `..` run from `~/proj`, home /// reached through a symlinked parent (`/home -> var/home`), or `/usr/lib` /// where `/lib -> usr/lib`, name a protected place without spelling it. /// A real directory outside the home folder must also carry the marker. @@ -316,9 +317,39 @@ pub(crate) fn judge_uninstall_root( real: None, }; } - // `symlink_metadata`: a symlinked root is unlinked, never walked, and a - // file is just a file. + let unresolvable = RootJudgment::Refuse { + why: ProtectedLocation::Unresolvable, + shown: None, + real: None, + }; + let resolved_home = home.map(|home| { + canonicalize(home).unwrap_or_else(|_| rocm_core::resolve_path_through_symlinks(home)) + }); + // A system location that exists but cannot be resolved would drop out of + // the comparison and leave its real location unprotected: refuse instead. + let Some(resolved_system_roots) = resolved_system_roots(canonicalize) else { + return unresolvable; + }; + // `symlink_metadata`: a non-directory root is unlinked, never walked, so + // the link itself is not followed. The folders above it are, by the OS, + // so it is judged by where its folder really is: `~/x/config.json` with + // `~/x -> /etc` is `/etc/config.json`. Only a refusal counts here; a file + // holds no marker, so anything else is unlinked as before. if !metadata.is_dir() { + let Some(real) = real_location_of_non_dir(path, canonicalize) else { + return unresolvable; + }; + if let UninstallRootVerdict::Refused(why) = rocm_core::uninstall_root_verdict( + &real, + resolved_home.as_deref(), + &resolved_system_roots, + ) { + return RootJudgment::Refuse { + why, + shown: (real != path).then(|| real.clone()), + real: Some(real), + }; + } return RootJudgment::Remove { planned: PlannedAs::non_dir(path, metadata, canonicalize), }; @@ -326,19 +357,8 @@ pub(crate) fn judge_uninstall_root( // A directory that cannot be resolved cannot be judged by where it is, and // is about to be walked recursively: refuse rather than guess. let Ok(resolved) = canonicalize(path) else { - return RootJudgment::Refuse { - why: ProtectedLocation::Unresolvable, - shown: None, - real: None, - }; + return unresolvable; }; - let resolved_home = home.map(|home| { - canonicalize(home).unwrap_or_else(|_| rocm_core::resolve_path_through_symlinks(home)) - }); - let resolved_system_roots = rocm_core::uninstall_system_roots() - .iter() - .filter_map(|root| canonicalize(root).ok()) - .collect::>(); let shown = (resolved != path).then(|| resolved.clone()); let refuse = |why| RootJudgment::Refuse { why, @@ -360,6 +380,32 @@ pub(crate) fn judge_uninstall_root( } } +/// Where each of [`rocm_core::uninstall_system_roots`] really is. One that +/// does not exist protects nothing and is left out; `None` when one exists but +/// cannot be resolved. +fn resolved_system_roots(canonicalize: Canonicalize<'_>) -> Option> { + let mut resolved = Vec::new(); + for root in rocm_core::uninstall_system_roots() { + match canonicalize(&root) { + Ok(real) => resolved.push(real), + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(_) => return None, + } + } + Some(resolved) +} + +/// A non-directory `path` with its folder resolved and its own name kept, so +/// a link root stays the link; `None` when the folder cannot be resolved. +fn real_location_of_non_dir(path: &Path, canonicalize: Canonicalize<'_>) -> Option { + let name = path.file_name()?; + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + canonicalize(parent).ok().map(|parent| parent.join(name)) +} + /// Whether `dir` carries the marker as a regular file of its own. A link named /// like the marker is not one: anything that can plant a link there could /// point it at any file, and ROCm CLI only ever writes a plain file. @@ -1549,7 +1595,9 @@ mod tests { } /// The refusal names where the folder came from, and points at that - /// setting as well as at the `--keep-` flag. + /// setting as well as at the `--keep-` flag. This pins the wording only: + /// `pointing_the_named_variable_elsewhere_clears_the_refusal` shows the + /// named variable clears it, and `uninstall-17` the named flag. #[test] fn a_refusal_names_the_setting_the_folder_came_from() { let root = std::env::temp_dir().join(format!("rocm-refuse-source-{}", std::process::id())); @@ -2054,6 +2102,168 @@ mod tests { assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::System); } + /// A file root spelled inside home but reached through a linked folder is + /// judged by where its folder really is: `~/x/conf` with `~/x` linked to a + /// system location is that location's `conf`, and the plan refuses it + /// rather than unlinking a file there. The system location is a sandbox + /// folder the injected resolver reports as `/etc`'s real place. + #[test] + #[cfg(unix)] + fn a_file_root_reached_through_a_linked_folder_is_judged_where_it_really_is() { + let root = sandbox("file-through-link"); + let home = root.join("users").join("home"); + let real_etc = root.join("real-etc"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&real_etc).unwrap(); + std::fs::write(real_etc.join("conf"), b"system").unwrap(); + std::os::unix::fs::symlink(&real_etc, home.join("x")).unwrap(); + let etc_target = real_etc.clone(); + let resolve: &dyn Fn(&Path) -> std::io::Result = &move |path: &Path| { + if path == Path::new("/etc") { + Ok(etc_target.clone()) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + let plan = super::build_uninstall_plan_with( + &data_only(home.join("x").join("conf"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + resolve, + ) + .unwrap(); + let kept = real_etc.join("conf").is_file(); + let _ = std::fs::remove_dir_all(&root); + assert!(plan.actions.is_empty(), "{plan:?}"); + assert_eq!(plan.refused.len(), 1, "{plan:?}"); + assert_eq!(plan.refused[0].why, rocm_core::ProtectedLocation::System); + assert_eq!( + plan.refused[0].resolved.as_deref(), + Some(real_etc.join("conf").as_path()) + ); + assert!(kept); + } + + /// The same layout with the link pointing at another folder in home plans + /// the file as before, and a root that is itself a link stays the link: + /// only its folder is resolved, so the plan unlinks the link and does not + /// reach the folder it points at. + #[test] + #[cfg(unix)] + fn a_file_or_link_root_whose_folder_really_is_in_home_is_planned() { + let root = sandbox("file-link-in-home"); + let home = root.join("users").join("home"); + let elsewhere = home.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + std::fs::write(elsewhere.join("conf"), b"mine").unwrap(); + std::os::unix::fs::symlink(&elsewhere, home.join("x")).unwrap(); + let file = super::build_uninstall_plan_for_home( + &data_only(home.join("x").join("conf"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let link = super::build_uninstall_plan_for_home( + &data_only(home.join("x"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert!(file.refused.is_empty(), "{file:?}"); + assert_eq!(file.actions.len(), 1, "{file:?}"); + assert!(link.refused.is_empty(), "{link:?}"); + assert_eq!(link.actions.len(), 1, "{link:?}"); + assert_eq!(link.actions[0].path, home.join("x"), "{link:?}"); + assert!( + matches!(link.actions[0].planned, super::PlannedAs::Link { .. }), + "{link:?}" + ); + } + + /// A root that is itself a link stays the link: only its folder is + /// resolved, so a link in home pointing at a system location is planned + /// as the link, to be unlinked, not refused as the place it points at. + /// The system location is a sandbox folder the injected resolver reports + /// as `/etc`'s real place. + #[test] + #[cfg(unix)] + fn a_link_root_pointing_at_a_system_location_is_planned_as_the_link() { + let root = sandbox("link-to-system"); + let home = root.join("users").join("home"); + let real_etc = root.join("real-etc"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&real_etc).unwrap(); + std::os::unix::fs::symlink(&real_etc, home.join("venv")).unwrap(); + let etc_target = real_etc.clone(); + let resolve: &dyn Fn(&Path) -> std::io::Result = &move |path: &Path| { + if path == Path::new("/etc") { + Ok(etc_target.clone()) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + let plan = super::build_uninstall_plan_with( + &data_only(home.join("venv"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + resolve, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert!(plan.refused.is_empty(), "{plan:?}"); + assert_eq!(plan.actions.len(), 1, "{plan:?}"); + assert_eq!(plan.actions[0].path, home.join("venv"), "{plan:?}"); + assert!( + matches!(plan.actions[0].planned, super::PlannedAs::Link { .. }), + "{plan:?}" + ); + } + + /// A system location that exists but cannot be resolved refuses the root + /// as unresolvable instead of dropping out of the comparison; one that + /// does not exist protects nothing and is skipped. + #[test] + fn a_system_location_that_cannot_be_resolved_refuses_the_root() { + let root = sandbox("system-root-unresolvable"); + let home = root.join("home"); + std::fs::create_dir_all(home.join("data")).unwrap(); + let system = rocm_core::uninstall_system_roots()[0].clone(); + let plan_with = |kind: std::io::ErrorKind| { + let system = system.clone(); + let resolve = move |path: &Path| { + if path == system { + Err(std::io::Error::from(kind)) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + super::build_uninstall_plan_with( + &data_only(home.join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + &resolve, + ) + .unwrap() + }; + let denied = plan_with(std::io::ErrorKind::PermissionDenied); + let missing = plan_with(std::io::ErrorKind::NotFound); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(denied.refused.len(), 1, "{denied:?}"); + assert_eq!( + denied.refused[0].why, + rocm_core::ProtectedLocation::Unresolvable + ); + assert!(denied.actions.is_empty(), "{denied:?}"); + assert!(missing.refused.is_empty(), "{missing:?}"); + assert_eq!(missing.actions.len(), 1, "{missing:?}"); + } + /// A root spelled beside home that really is inside it — Windows spells the /// temp folder with the home folder's short 8.3 name (`RUNNER~1`) — is /// judged by where it really is and planned; a real folder in another diff --git a/crates/rocm-dash-tui/src/app/slash.rs b/crates/rocm-dash-tui/src/app/slash.rs index 2f8a49e122..5a6764994e 100644 --- a/crates/rocm-dash-tui/src/app/slash.rs +++ b/crates/rocm-dash-tui/src/app/slash.rs @@ -1255,6 +1255,29 @@ mod tests { ); } + /// An unknown flag is refused on its own, with no mode flag, and it wins + /// over the `--apply`/`--dry-run` conflict: the typo is named, so the user + /// fixes it first. Neither raises a request. + #[test] + fn slash_uninstall_unknown_flag_alone_or_with_conflicting_modes_is_named() { + let mut s = st(); + for command in [ + "/uninstall --keep-dat", + "/uninstall --apply --dry-run --keep-dat", + ] { + assert_eq!(s.handle_slash_command(command), SlashOutcome::Handled); + assert!(s.slash_tool.is_none(), "{command} raised a request"); + let turn = s.chat.last().expect("an error turn"); + assert_eq!(turn.role, ChatRole::Error, "{command}"); + assert!( + turn.content + .starts_with("unknown /uninstall flag --keep-dat:"), + "{command}: {}", + turn.content + ); + } + } + #[test] fn slash_uninstall_conflicting_flags_is_guided() { let mut s = st(); diff --git a/docs/testing.md b/docs/testing.md index 26009ccbdb..adcbdd1053 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1839,7 +1839,7 @@ with Ctrl-D, and for a plain no, each together with the config folder being left in place. They run on the default mock lane; the helper's other callers (`rocm fix`, the SDK-overwrite prompt) share it and are covered by its unit tests in [confirm.rs](../crates/rocm-core/src/confirm.rs). -`uninstall-16` to `uninstall-21` cover the protected-location refusal: the top +`uninstall-16` to `uninstall-22` cover the protected-location refusal: the top of the filesystem as the data folder, refused in a dry run (`uninstall-16`); the home folder, refused with the home file and config folder left in place, saying ROCm CLI never removes that folder, and the advised `--keep-data` then @@ -1848,9 +1848,11 @@ cache folder named as deleted, then kept by `--keep-cache` and really deleted without it (`uninstall-18`); a data folder of `.` run from home, refused with nothing removed (`uninstall-19`); an unmarked folder outside home, refused with it left in place and without a claim that it is never removed, then, once the -marker the refusal names is created, planned and really removed (`uninstall-20`); and the +marker the refusal names is created, planned and really removed (`uninstall-20`); the dashboard's approved-command path naming `setup.therock_venv`, with the home -file and config folder left in place (`uninstall-21`). +file and config folder left in place (`uninstall-21`); and a data setting naming +a file through a home-folder link to `/proc`, refused as the system file it +really is with the config folder left in place (`uninstall-22`). The `uninstall` command does not start the file logger, which would otherwise create the data folder's `logs` folder before the plan is built: diff --git a/engines/vllm/src/install.rs b/engines/vllm/src/install.rs index 0baf492bc8..291165bcaf 100644 --- a/engines/vllm/src/install.rs +++ b/engines/vllm/src/install.rs @@ -1273,6 +1273,34 @@ fi contents.contains("ignore-error-codes = [403]"), "{contents}" ); + // It created the cache folder, so it marked it as ROCm CLI's own. + assert!( + paths + .cache_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .is_file() + ); + Ok(()) + } + + /// A cache folder that already existed is not claimed as ROCm CLI's own. + #[test] + fn write_vllm_index_uv_config_leaves_an_existing_cache_folder_unmarked() -> Result<()> { + let root = tempfile::tempdir()?; + let paths = AppPaths { + config_dir: root.path().join("config"), + data_dir: root.path().join("data"), + cache_dir: root.path().join("cache"), + }; + std::fs::create_dir_all(&paths.cache_dir)?; + let build = vllm_rocm_discover_build("10.0.0").expect("10.0.0 has a discover row"); + write_vllm_index_uv_config(&paths, build)?; + assert!( + !paths + .cache_dir + .join(rocm_core::ROCM_CLI_ROOT_MARKER) + .exists() + ); Ok(()) } /// The prefix boundary (`-device-gfx`, not a bare `starts_with` of diff --git a/tests/e2e-cucumber/features/uninstall.feature b/tests/e2e-cucumber/features/uninstall.feature index 5280bf43d1..a176e2d9e2 100644 --- a/tests/e2e-cucumber/features/uninstall.feature +++ b/tests/e2e-cucumber/features/uninstall.feature @@ -273,3 +273,18 @@ Feature: Uninstall Then the refusal names setup.therock_venv and advises --keep-data, not a variable the user never set And the user's files in the home folder are still there And the config folder is still there + + # A setting that names a file rather than a folder is judged by where its + # folder really is: a file spelled inside home but reached through a link to + # a system location is refused, and nothing is removed. The link points at + # `/proc`, where nothing can be unlinked even by root, so a regression could + # not damage the runner. + # Linux-only: it needs `/proc`. + @id:uninstall-file-through-linked-folder-refused @requires-os:linux + Scenario: uninstall-22 - A data setting naming a file reached through a link to a system folder is refused + Given the data folder setting names a file through a link in the home folder to /proc + When the user uninstalls + Then the refusal says that file really is in a protected system location + And the refusal says nothing was removed + And the config folder is still there + And the link in the home folder is still there diff --git a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs index b53951e9ee..2018468907 100644 --- a/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs +++ b/tests/e2e-cucumber/tests/e2e/uninstall_steps.rs @@ -992,6 +992,49 @@ async fn unmarked_data_gone(world: &mut E2eWorld) { ); } +/// The link in the scenario's home that points at `/proc`. +fn proc_link(world: &E2eWorld) -> PathBuf { + home(world).join("procfs") +} + +#[given("the data folder setting names a file through a link in the home folder to /proc")] +async fn data_is_file_through_proc_link(world: &mut E2eWorld) { + let link = proc_link(world); + std::fs::create_dir_all(home(world)).expect("failed to create HOME"); + #[cfg(unix)] + std::os::unix::fs::symlink("/proc", &link).expect("failed to link /proc"); + set_env(world, "ROCM_CLI_DATA_DIR", link.join("version")); + // A config folder the uninstall would otherwise remove, so the refusal + // stopping everything shows in what is left. + plant_config_rocm_cli_created(world); +} + +#[then("the refusal says that file really is in a protected system location")] +async fn refusal_names_real_system_file(world: &mut E2eWorld) { + let stdout = output(world); + let line = format!( + " - data: {} is a protected system location (set by ROCM_CLI_DATA_DIR; resolves to /proc/version)", + proc_link(world).join("version").display() + ); + assert!(rc(world) != 0, "a refused uninstall must fail:\n{stdout}"); + assert!( + stdout.lines().any(|l| l == line), + "expected `{line}` in the review:\n{stdout}" + ); +} + +#[then("the link in the home folder is still there")] +async fn proc_link_intact(world: &mut E2eWorld) { + let link = proc_link(world); + assert!( + std::fs::symlink_metadata(&link).is_ok_and(|meta| meta.file_type().is_symlink()), + "the refused uninstall removed {}:\n{}\n{}", + link.display(), + output(world), + stderr(world) + ); +} + #[given("setup.therock_venv points at the user's home folder, which holds their files")] async fn venv_is_home(world: &mut E2eWorld) { let file = user_file_in_home(world); From acc80d1eb46ee2d5cbf415adf6f6a378aeb16b22 Mon Sep 17 00:00:00 2001 From: Roman Inflianskas Date: Mon, 16 Nov 2026 13:57:52 +0200 Subject: [PATCH 6/7] test(uninstall): read README at run time and register rocm-core as its reader readme_names_every_uninstall_system_root embedded README.md with include_str!, which the ASCII output contract counts as data compiled into a binary, and which the pre-push hook's widening rule did not list for rocm-core. The test now reads README at run time, and CROSS_CRATE_READS names rocm-core as a README reader so the narrowed hook runs it when README changes; docs_and_skills_select_the_crates_whose_tests_read_them now expects rocm-core for README only, not for docs or skills. Also drops a redundant clone clippy flags in the new link test. Signed-off-by: Roman Inflianskas --- apps/rocm/src/uninstall_plan.rs | 3 +-- crates/rocm-core/src/runtime.rs | 7 +++++-- xtask/src/prepush.rs | 13 ++++++++++--- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 7da241ed6b..2e3512ef7f 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -2198,10 +2198,9 @@ mod tests { std::fs::create_dir_all(&home).unwrap(); std::fs::create_dir_all(&real_etc).unwrap(); std::os::unix::fs::symlink(&real_etc, home.join("venv")).unwrap(); - let etc_target = real_etc.clone(); let resolve: &dyn Fn(&Path) -> std::io::Result = &move |path: &Path| { if path == Path::new("/etc") { - Ok(etc_target.clone()) + Ok(real_etc.clone()) } else { rocm_core::canonicalize_for_compare(path) } diff --git a/crates/rocm-core/src/runtime.rs b/crates/rocm-core/src/runtime.rs index f44fe1c891..69cb18db28 100644 --- a/crates/rocm-core/src/runtime.rs +++ b/crates/rocm-core/src/runtime.rs @@ -2169,10 +2169,13 @@ mod tests { /// `rocm uninstall` refuses, on both platforms: every root in the list is /// named there, and every system folder named there is refused as one. /// Not `cfg(unix)`: both platforms are parameters, so this runs on every - /// lane. + /// lane. README is read at run time rather than embedded, so it is not + /// compiled into the test binary as data. #[test] fn readme_names_every_uninstall_system_root() { - let readme = include_str!("../../../README.md"); + let readme = + std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../README.md")) + .expect("README.md at the repo root"); let section = readme .split_once("It never removes:") .and_then(|(_, rest)| rest.split_once("Anywhere else outside your home folder")) diff --git a/xtask/src/prepush.rs b/xtask/src/prepush.rs index 9543c92115..e7c404adb3 100644 --- a/xtask/src/prepush.rs +++ b/xtask/src/prepush.rs @@ -210,12 +210,13 @@ fn package_args<'a>(packages: Option>) -> Vec Date: Tue, 17 Nov 2026 14:46:18 +0200 Subject: [PATCH 7/7] fix(uninstall): fail closed when the home folder cannot be resolved judge_uninstall_root fell back to the home folder's spelling, resolved as far as it goes, on any error canonicalizing it. A home folder that exists but cannot be resolved (permission denied on a component) could then miss the comparison with a root that really is home. Only a home folder that does not exist keeps the fallback now; any other error refuses the root as unresolvable, as a system location already does (a_home_folder_that_cannot_be_resolved_refuses_the_root). From the same review: - runtime_uninstall_of_a_runtime_in_the_home_folder_is_refused_and_removes_nothing runs a real runtime uninstall with home pointed at the runtime's folder and checks the refusal together with the folder, its files and its registry entry still being there. - uninstall_plan_refuses_the_filesystem_root asserted the absence of a heading that no longer exists; it now checks that a refused dry run on a terminal says it would be refused instead of inviting a real run. - prune_plan_leaves_a_protected_install_folder_and_says_why names the test that shows prune removes exactly what its plan lists. - The load-bearing sort of planned removals, and the different home/system precedence of the two protected-location rules, are documented. Signed-off-by: Roman Inflianskas --- apps/rocm/src/runtime_uninstall.rs | 45 +++++++++++++++++ apps/rocm/src/storage.rs | 4 ++ apps/rocm/src/uninstall_plan.rs | 81 ++++++++++++++++++++++++++++-- crates/rocm-core/src/runtime.rs | 6 +++ 4 files changed, 132 insertions(+), 4 deletions(-) diff --git a/apps/rocm/src/runtime_uninstall.rs b/apps/rocm/src/runtime_uninstall.rs index 02e9cac47c..26fc9637f5 100644 --- a/apps/rocm/src/runtime_uninstall.rs +++ b/apps/rocm/src/runtime_uninstall.rs @@ -780,6 +780,51 @@ mod tests { } } + /// The refusal above stops a real `rocm runtimes uninstall` before it + /// touches anything: a runtime whose matching in-tree manifest says its + /// folder is the home folder is refused, and the folder, its files and its + /// registry entry are all still there afterwards. Home is pointed at the + /// runtime's own sandbox folder, under the process-wide env locks. + #[test] + fn runtime_uninstall_of_a_runtime_in_the_home_folder_is_refused_and_removes_nothing() + -> Result<()> { + let (root, paths) = test_paths("runtime-uninstall-home-folder"); + let manifest = write_test_pip_runtime( + &paths, + "release-pip-gfx120x-all-7-13-0", + "therock-release:gfx120X-all", + "7.13.0", + 20, + )?; + let home = manifest.install_root.clone(); + let registry = runtime_manifest_path(&paths, &manifest.runtime_key); + let mut config = RocmCliConfig::default(); + let result = { + let _process_env = crate::test_support::PROCESS_ENV_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut env = crate::tests::ScopedTestEnv::new(); + env.set("HOME", &home.display().to_string()); + env.set("USERPROFILE", &home.display().to_string()); + uninstall_runtime(&paths, &mut config, &manifest.runtime_key) + }; + let folder_kept = home.join(".rocm-cli-runtime.json").is_file() + && manifest + .python_executable + .as_deref() + .is_some_and(|python| Path::new(python).is_file()); + let registry_kept = registry.is_file(); + let _ = fs::remove_dir_all(&root); + let err = result.expect_err("a runtime in the home folder must be refused"); + assert!( + err.to_string().ends_with("because it is your home folder"), + "{err}" + ); + assert!(folder_kept, "the home folder's contents were removed"); + assert!(registry_kept, "the registry entry was removed"); + Ok(()) + } + /// The gate above is the last thing between a registry entry and /// `fs::remove_dir_all`, and the path it is handed is text somebody else /// wrote. One folder has many spellings, so the refusal has to survive all diff --git a/apps/rocm/src/storage.rs b/apps/rocm/src/storage.rs index f810a2bc44..68c6156f9d 100644 --- a/apps/rocm/src/storage.rs +++ b/apps/rocm/src/storage.rs @@ -1656,6 +1656,10 @@ mod tests { let plan = build_prune_plan(&paths, &RocmCliConfig::default(), 1)?; let _ = std::fs::remove_dir_all(root); + // "Left in place" is held by the plan: prune removes exactly + // `plan.remove`, which `prune_removes_the_install_it_named_and_not_a_case_twin_of_it` + // shows on disk. A protected system folder cannot be staged in a + // sandbox, so this pins the plan and the line together. assert!(plan.remove.is_empty(), "{:?}", plan.remove); let expected = format!( "old: folder {} is a protected system location, so it is left in place", diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs index 2e3512ef7f..6cbcfed37a 100644 --- a/apps/rocm/src/uninstall_plan.rs +++ b/apps/rocm/src/uninstall_plan.rs @@ -322,9 +322,20 @@ pub(crate) fn judge_uninstall_root( shown: None, real: None, }; - let resolved_home = home.map(|home| { - canonicalize(home).unwrap_or_else(|_| rocm_core::resolve_path_through_symlinks(home)) - }); + // Home is resolved like everything else here, failing closed. Only a home + // folder that does not exist falls back to its spelling resolved as far as + // it goes: an existing root cannot really be a place that does not exist, + // so nothing it is compared against is lost. Any other failure would let a + // root that really is home miss the comparison: refuse instead + // (`a_home_folder_that_cannot_be_resolved_refuses_the_root`). + let resolved_home = match home.map(canonicalize) { + None => None, + Some(Ok(real)) => Some(real), + Some(Err(err)) if err.kind() == io::ErrorKind::NotFound => { + home.map(rocm_core::resolve_path_through_symlinks) + } + Some(Err(_)) => return unresolvable, + }; // A system location that exists but cannot be resolved would drop out of // the comparison and leave its real location unprotected: refuse instead. let Some(resolved_system_roots) = resolved_system_roots(canonicalize) else { @@ -609,6 +620,11 @@ pub(crate) fn build_uninstall_plan_with( )); } + // Load-bearing order: a path sorts before every path inside it, so a + // folder is removed before anything planned inside it. `apply_uninstall_plan` + // relies on that to report an entry already removed with an earlier one as + // removed (see `an_entry_removed_with_an_earlier_one_is_still_reported`), + // rather than re-checking a path that is gone. plan.actions .sort_by(|left, right| left.path.cmp(&right.path)); plan.actions.dedup_by(|left, right| left.path == right.path); @@ -1409,7 +1425,24 @@ mod tests { )), "{rendered}" ); - assert!(!rendered.contains("Choose Review uninstall"), "{rendered}"); + // On a terminal, where a dry run otherwise ends by inviting a real + // run, a refused one says what clears it instead. + let on_terminal = super::render_uninstall_plan( + &plan, + &super::UninstallOptions { + dry_run: true, + ..options + }, + super::PlanAudience::Terminal, + ); + assert!( + on_terminal.contains("This uninstall would be refused."), + "{on_terminal}" + ); + assert!( + !on_terminal.contains("To remove these items"), + "{on_terminal}" + ); let keep = super::UninstallOptions { keep_data: true, @@ -2263,6 +2296,46 @@ mod tests { assert_eq!(missing.actions.len(), 1, "{missing:?}"); } + /// A home folder that exists but cannot be resolved refuses the root as + /// unresolvable, as a system location does: otherwise a root that really + /// is home could miss the comparison. A home folder that does not exist + /// is compared by its spelling, so a root elsewhere is still planned. + #[test] + fn a_home_folder_that_cannot_be_resolved_refuses_the_root() { + let root = sandbox("home-unresolvable"); + let home = root.join("home"); + std::fs::create_dir_all(home.join("data")).unwrap(); + let plan_with = |kind: std::io::ErrorKind| { + let unresolvable = home.clone(); + let resolve = move |path: &Path| { + if path == unresolvable { + Err(std::io::Error::from(kind)) + } else { + rocm_core::canonicalize_for_compare(path) + } + }; + super::build_uninstall_plan_with( + &data_only(home.join("data"), &root), + &rocm_core::AppPathSources::default(), + &keep_binaries(), + Some(&home), + &resolve, + ) + .unwrap() + }; + let denied = plan_with(std::io::ErrorKind::PermissionDenied); + let missing = plan_with(std::io::ErrorKind::NotFound); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(denied.refused.len(), 1, "{denied:?}"); + assert_eq!( + denied.refused[0].why, + rocm_core::ProtectedLocation::Unresolvable + ); + assert!(denied.actions.is_empty(), "{denied:?}"); + assert!(missing.refused.is_empty(), "{missing:?}"); + assert_eq!(missing.actions.len(), 1, "{missing:?}"); + } + /// A root spelled beside home that really is inside it — Windows spells the /// temp folder with the home folder's short 8.3 name (`RUNNER~1`) — is /// judged by where it really is and planned; a real folder in another diff --git a/crates/rocm-core/src/runtime.rs b/crates/rocm-core/src/runtime.rs index 69cb18db28..24c9edf46b 100644 --- a/crates/rocm-core/src/runtime.rs +++ b/crates/rocm-core/src/runtime.rs @@ -837,6 +837,12 @@ pub fn runtime_protected_location_for_home( /// remove-old-installs` and the assistant's SDK `--prefix` check accept a /// folder inside them. Adding them would change what those accept; the two /// lists have not been reconciled. +/// +/// The two rules also differ in order. [`uninstall_root_verdict_on`] checks +/// the system locations before the home folder, so a home of `/usr/sbin` +/// cannot open up `/usr`; [`protected_location_on`] checks the home folder +/// first, so a runtime under `/root/.rocm` stays removable when `/root` is +/// home (`a_root_users_home_is_refused_as_a_home`). fn system_roots(platform: RuntimePlatform) -> Vec { if platform.is_windows() { return uninstall_system_roots_on(platform, &windows_system_drive());