From 4d6a65e00c78aa97edad4aa21d2d03bffd8af6ff Mon Sep 17 00:00:00 2001 From: Shishir Pai <64056966+mgpai22@users.noreply.github.com> Date: Sat, 26 Sep 2026 16:54:16 -0400 Subject: [PATCH] feat(removal): refuse profile folders and flush after elevated removals --- crates/disktree-core/src/removal.rs | 71 ++++++++++++++++++++++++++++- crates/disktree-core/src/windows.rs | 57 +++++++++++++++++++++++ 2 files changed, 127 insertions(+), 1 deletion(-) diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index c41843d..b7bbc25 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -400,6 +400,15 @@ fn refuse( if home_key.is_some_and(|home| home.starts_with(&key)) { return Some("it contains the home directory".into()); } + // Elevated through another account's credentials, home is that admin's, + // and the user's own profile is just another folder; elevation opens + // every other profile too. So on Windows each directory in the profiles + // folder (`C:\Users\tobi`, `Public`, `Default`) is refused, taken from + // Windows and not from home, whose parent could be anything. What is + // inside a profile stays removable, as under one's own home. + if profiles_key().is_some_and(|profiles| is_profile(path, &key, profiles)) { + return Some("a user profile cannot be removed".into()); + } // By spelling too: the Data volume's root keeps its name as a key, while // everything under it is keyed as under `/`. if !key.starts_with(&root_key) && !path.starts_with(root) { @@ -616,6 +625,29 @@ const fn windows_mount_points() -> Vec { Vec::new() } +/// The key of the folder every user profile is in, `C:\Users` as +/// installed; asked of Windows once, since it does not move while running. +#[cfg(windows)] +fn profiles_key() -> Option<&'static Path> { + static PROFILES: std::sync::LazyLock> = + std::sync::LazyLock::new(|| { + crate::windows::user_profiles_dir().map(|dir| guard_key(&dir)) + }); + PROFILES.as_deref() +} + +#[cfg(not(windows))] +const fn profiles_key() -> Option<&'static Path> { + None +} + +/// Whether `path`, keyed `key`, is a profile: a directory directly in +/// `profiles`. A file or a link there is no profile and stays removable. +fn is_profile(path: &Path, key: &Path, profiles: &Path) -> bool { + key.parent() == Some(profiles) + && fs::symlink_metadata(path).is_ok_and(|meta| meta.is_dir()) +} + /// A mount point strictly inside the path keyed `key`, if there is one. A /// scan that stays on one filesystem never shows what is mounted there, so /// the user cannot have meant to remove it. @@ -929,6 +961,18 @@ fn run( }); } + // NTFS writes the file table's records lazily, and the elevated rescan + // of a whole drive reads that table from disk, past the cache: + // unflushed, the removed entries would still show. Only then; a folder + // is walked. Failing only lets the table lag again. + #[cfg(windows)] + if removed > 0 + && plan.root.parent().is_none() + && crate::access::administrator() == Some(true) + { + let _ = crate::windows::flush_volume(&plan.root); + } + let _ = sender.send(RemovalEvent::Done { removed, bytes, @@ -1479,7 +1523,7 @@ mod tests { assert_eq!( refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]), None, - "a sibling of home is not" + "a sibling of home is not above it" ); } @@ -2155,6 +2199,31 @@ mod tests { ); } + #[cfg(windows)] + #[test] + fn windows_profiles_are_refused() { + let temp = tempfile::tempdir().expect("tempdir"); + let profiles = temp.path(); + fs::create_dir_all(profiles.join(r"tobi\Downloads")).expect("mkdir"); + fs::write(profiles.join("notes.txt"), b"x").expect("write"); + let profile = |relative: &str| { + let path = profiles.join(relative); + is_profile(&path, &guard_key(&path), &guard_key(profiles)) + }; + assert!(profile("tobi")); + assert!(profile("TOBI"), "compared as Windows compares names"); + assert!(!profile("notes.txt"), "a file there is no profile"); + assert!(!profile(r"tobi\Downloads"), "inside a profile is not one"); + assert!(!profile("gone"), "nothing there is no profile"); + + // The rule itself, against the profiles folder Windows reports. + let public = crate::windows::user_profiles_dir() + .expect("profiles folder") + .join("Public"); + let reason = refuse(&public, &system_drive(), None, &[]); + assert!(reason.is_some_and(|reason| reason.contains("profile"))); + } + #[test] #[cfg(target_os = "macos")] fn macos_always_uses_the_system_trash() { diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs index b036bdb..53b8564 100644 --- a/crates/disktree-core/src/windows.rs +++ b/crates/disktree-core/src/windows.rs @@ -33,6 +33,7 @@ use windows_sys::Win32::Storage::FileSystem::{ FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, + FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileIdExtdDirectoryInfo, FindFirstVolumeW, FindNextVolumeW, FindVolumeClose, GetDiskFreeSpaceExW, GetFileInformationByHandleEx, GetVolumeInformationW, GetVolumePathNameW, @@ -672,6 +673,24 @@ pub fn run_elevated(program: &Path, args: &[OsString]) -> io::Result<()> { } } +/// Write out what the file system holds only in memory for the volume +/// holding `path`, its file table included. Flushing a volume takes write +/// access, so an administrator. Only a volume mounted as a drive letter: +/// for one mounted in a folder, `\\.\X:` would name the drive around it. +pub fn flush_volume(path: &Path) -> io::Result<()> { + let root = volume_root(path).ok_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "no volume holds the path") + })?; + let letter = drive_letter(&root) + .ok_or_else(|| io::Error::from(io::ErrorKind::Unsupported))?; + OpenOptions::new() + .read(true) + .write(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) + .open(format!(r"\\.\{letter}:"))? + .sync_all() +} + /// `C` when `canonical` is the root of drive `C:`; `None` for anything /// else, a folder or a volume mounted in one. pub fn drive_letter(canonical: &Path) -> Option { @@ -688,6 +707,44 @@ pub fn drive_letter(canonical: &Path) -> Option { .then_some(char::from(letter)) } +/// The folder that holds every user's profile, `C:\Users` as installed, +/// from Windows itself: it can be moved, so no path is assumed. `None` +/// when Windows does not say. +pub fn user_profiles_dir() -> Option { + use windows_sys::Win32::System::Com::CoTaskMemFree; + use windows_sys::Win32::UI::Shell::{ + FOLDERID_UserProfiles, SHGetKnownFolderPath, + }; + let mut raw: *mut u16 = std::ptr::null_mut(); + // SAFETY: the id outlives the call, a null token means this user, and + // `raw` receives a string the shell allocates, freed below either way. + let result = unsafe { + SHGetKnownFolderPath( + &FOLDERID_UserProfiles, + 0, + std::ptr::null_mut(), + &raw mut raw, + ) + }; + let path = (result >= 0 && !raw.is_null()).then(|| { + // SAFETY: on success `raw` is a NUL-terminated string, read up to + // and not past its NUL. + unsafe { + let mut len = 0; + while *raw.add(len) != 0 { + len += 1; + } + PathBuf::from(OsString::from_wide(std::slice::from_raw_parts( + raw, len, + ))) + } + }); + // SAFETY: `raw` came from the shell's allocator, or is null, which + // the call accepts. + unsafe { CoTaskMemFree(raw.cast()) }; + path +} + /// `arg` quoted so a program's C runtime splits it back out whole: inside /// quotes, backslashes are literal except before a quote, where they must /// be doubled, so `C:\` becomes `"C:\\"` and not `"C:\"`.