From 95aa6c098a1e72d4ef8797bb255bef858ea3e62c Mon Sep 17 00:00:00 2001 From: Pierre Warnier Date: Sun, 8 Nov 2026 08:24:43 +0100 Subject: [PATCH 1/5] userdel: keep a mail spool the user does not own With -r, a mail spool that the user does not own is now kept, as upstream does: "SPOOL not owned by LOGIN, not removing" on stderr, the home still removed, exit 12. -f removes it. A spool that is a symlink is judged by the file it points to, and only the link is ever removed. The spool is looked up once through a descriptor on /var/mail, and the unlink goes through that same descriptor. Fixes #400 --- CHANGELOG.md | 5 ++ docs/man/userdel.8.md | 8 +- src/uu/userdel/src/userdel.rs | 85 ++++++++++++++++---- tests/by-util/test_userdel.rs | 141 ++++++++++++++++++++++++++++++++++ 4 files changed, 221 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e5cd625..f5c5d771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 not a usage error. `newusers` refuses to create a group over 32 characters, as upstream does (#391) +- `userdel -r` keeps a mail spool that the user does not own, or a symlink to a + file they do not own, says `SPOOL not owned by LOGIN, not removing` and exits 12 + after removing the home, as upstream does; `-f` removes it. It unlinked the + spool whoever owned it (#400) + - `userdel -r` says `LOGIN mail spool (PATH) not found` and `LOGIN home directory (PATH) not found` on standard error when either is missing, mail spool first, as upstream does, with exit 0. It said nothing (#392) diff --git a/docs/man/userdel.8.md b/docs/man/userdel.8.md index 7f495ab0..f0a2a34f 100644 --- a/docs/man/userdel.8.md +++ b/docs/man/userdel.8.md @@ -20,7 +20,8 @@ is also removed from membership lists in /etc/group and /etc/gshadow. **-f**, **--force** : With **-r**, remove the home directory even if it is not owned by the user or - is shared with another account. A user that does not exist is still exit + is shared with another account, and the mail spool even if it is not owned by + the user. A user that does not exist is still exit status 6. **-P**, **--prefix** *PREFIX_DIR* @@ -37,6 +38,11 @@ is also removed from membership lists in /etc/group and /etc/gshadow. (PATH) not found* and *LOGIN home directory (PATH) not found* are printed on standard error, in that order, and the exit status is unchanged. + A mail spool the user does not own is kept unless **-f** is given: *SPOOL not + owned by LOGIN, not removing* is printed on standard error, the home is still + removed, and the exit status is 12. A spool that is a symbolic link is judged + by the file it points to; the link is what is removed, never that file. + **-R**, **--root** *CHROOT_DIR* : Apply changes in the *CHROOT_DIR* directory. diff --git a/src/uu/userdel/src/userdel.rs b/src/uu/userdel/src/userdel.rs index eca8a4f2..758e9dbf 100644 --- a/src/uu/userdel/src/userdel.rs +++ b/src/uu/userdel/src/userdel.rs @@ -286,7 +286,8 @@ pub fn uu_app() -> Command { /// Remove the mail spool and the home of the account being deleted, for `-r`. /// /// Either one missing is said on stderr and is not a failure, spool first, as -/// upstream does. +/// upstream does. A spool the user does not own is kept unless `force`; the +/// home is still removed, and the exit status is then `CANT_REMOVE_HOME`. fn remove_spool_and_home( root: &SysRoot, login: &str, @@ -294,29 +295,79 @@ fn remove_spool_and_home( uid: u32, force: bool, shared_by_other: bool, -) -> Result<(), UserdelError> { +) -> UResult<()> { let mail = root.resolve(&format!("/var/mail/{login}")); - // `exists()` follows a symlink on purpose, here and for the home below: - // Ubuntu 26.04's `userdel -r` reports a dangling link as not found, exit - // 0, and leaves it in place. - if mail.exists() { - let _ = std::fs::remove_file(&mail); - } else { - uucore::show_error!("{login} mail spool ({}) not found", mail.display()); - } + let spool_kept = match remove_mail_spool(&mail, uid, force) { + Spool::Removed => false, + Spool::Missing => { + uucore::show_error!("{login} mail spool ({}) not found", mail.display()); + false + } + Spool::NotOwned => { + uucore::show_error!("{} not owned by {login}, not removing", mail.display()); + true + } + }; if home.is_empty() { // Nothing to remove; upstream names the empty path all the same. uucore::show_error!("{login} home directory () not found"); - return Ok(()); - } - let home = root.resolve(home); - if home.exists() { - safe_remove_home(&home, uid, force, shared_by_other) } else { - uucore::show_error!("{login} home directory ({}) not found", home.display()); - Ok(()) + let home = root.resolve(home); + // `exists()` follows a symlink on purpose: Ubuntu 26.04's `userdel -r` + // reports a dangling link as not found, exit 0, and leaves it in place. + if home.exists() { + safe_remove_home(&home, uid, force, shared_by_other)?; + } else { + uucore::show_error!("{login} home directory ({}) not found", home.display()); + } + } + + if spool_kept { + // Already said above, in its place before anything about the home. + return Err(shadow_core::cli::AlreadyPrinted(exit_codes::CANT_REMOVE_HOME).into()); + } + Ok(()) +} + +/// What `-r` did with the mail spool. +enum Spool { + Removed, + Missing, + NotOwned, +} + +/// Remove the mail spool at `mail` unless it belongs to someone other than +/// `uid` and `force` is not given. +/// +/// Ownership is that of the file the entry leads to: Ubuntu 26.04's `userdel +/// -r` keeps a symlink to another user's file, removes a symlink to the +/// user's own, and reports a dangling one as not found and leaves it. The +/// entry is looked up once through a descriptor on its directory, and the +/// unlink goes through that same descriptor, so the directory cannot be +/// swapped for another between the ownership check and the removal. +fn remove_mail_spool(mail: &Path, uid: u32, force: bool) -> Spool { + use rustix::fs::{AtFlags, Mode, OFlags}; + + let (Some(parent), Some(name)) = (mail.parent(), mail.file_name()) else { + return Spool::Missing; + }; + let Ok(dir) = rustix::fs::open( + parent, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) else { + return Spool::Missing; + }; + let Ok(target) = rustix::fs::statat(&dir, name, AtFlags::empty()) else { + return Spool::Missing; + }; + if !force && target.st_uid != uid { + return Spool::NotOwned; } + // A failed unlink has never been reported here; that is not this check's to change. + let _ = rustix::fs::unlinkat(&dir, name, AtFlags::empty()); + Spool::Removed } // --------------------------------------------------------------------------- diff --git a/tests/by-util/test_userdel.rs b/tests/by-util/test_userdel.rs index 22f04e7e..ca975a25 100644 --- a/tests/by-util/test_userdel.rs +++ b/tests/by-util/test_userdel.rs @@ -738,3 +738,144 @@ fn test_remove_leaves_a_dangling_home_link() { assert!(meta.file_type().is_symlink()); assert!(!read_passwd(&dir).contains("testuser:")); } + +/// What a spool test starts from: a home the user owns, so that the home's +/// fate shows whether `-r` carried on past the spool. +struct SpoolCase { + dir: tempfile::TempDir, + home: std::path::PathBuf, + spool: std::path::PathBuf, + target: std::path::PathBuf, +} + +/// `kind` is `"file"` for a regular spool, or `"link"` for a spool that is a +/// symlink to a file outside /var/mail; that file, or the spool itself, is +/// owned by `owner`. +fn spool_case(kind: &str, owner: u32) -> SpoolCase { + let dir = setup_root_dir(); + let root = dir.path().to_path_buf(); + let home = root.join("home/testuser"); + std::fs::create_dir_all(&home).expect("home"); + std::os::unix::fs::chown(&home, Some(1000), Some(1000)).expect("chown home"); + std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); + let spool = root.join("var/mail/testuser"); + let target = root.join("srv-mailbox"); + if kind == "link" { + std::fs::write(&target, "mail").expect("link target"); + std::os::unix::fs::chown(&target, Some(owner), Some(owner)).expect("chown target"); + std::os::unix::fs::symlink(&target, &spool).expect("spool link"); + } else { + std::fs::write(&spool, "mail").expect("spool"); + std::os::unix::fs::chown(&spool, Some(owner), Some(owner)).expect("chown spool"); + } + SpoolCase { + dir, + home, + spool, + target, + } +} + +fn run_spool_case(case: &SpoolCase, flags: &[&str]) -> crate::common::Output { + let prefix = case.dir.path().to_str().expect("non-UTF-8 temp path"); + let mut command_line = vec!["-P", prefix]; + command_line.extend_from_slice(flags); + command_line.push("testuser"); + crate::common::run("userdel", &command_line) +} + +/// A spool that is not the user's is kept, said on stderr, exit 12; the +/// account and the home go all the same. Ubuntu 26.04's `userdel -r` does so. +#[test] +fn test_remove_keeps_a_mail_spool_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case("file", 0); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(12); + assert!(out.stdout.is_empty(), "stdout: {:?}", out.stdout); + assert_eq!( + messages(&out), + [format!( + "{} not owned by testuser, not removing", + case.spool.display() + )] + ); + assert!(case.spool.exists(), "the spool should have been kept"); + assert!(!case.home.exists(), "the home should have been removed"); + assert!(!read_passwd(&case.dir).contains("testuser:")); +} + +/// `-f` removes a spool that is not the user's, without a word. +#[test] +fn test_remove_force_removes_a_mail_spool_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case("file", 0); + let out = run_spool_case(&case, &["-r", "-f"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(!case.spool.exists(), "the spool should have been removed"); + assert!(!case.home.exists(), "the home should have been removed"); +} + +/// A spool that is a symlink to someone else's file is judged by that file: +/// the link is kept, and so is the file, exit 12. +#[test] +fn test_remove_keeps_a_spool_link_to_a_file_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case("link", 0); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(12); + assert_eq!( + messages(&out), + [format!( + "{} not owned by testuser, not removing", + case.spool.display() + )] + ); + let meta = std::fs::symlink_metadata(&case.spool).expect("the link should be kept"); + assert!(meta.file_type().is_symlink()); + assert!(case.target.exists(), "the link target should be untouched"); + assert!(!case.home.exists(), "the home should have been removed"); + assert!(!read_passwd(&case.dir).contains("testuser:")); +} + +/// `-f` removes the link to someone else's file, never the file itself. +#[test] +fn test_remove_force_removes_a_spool_link_but_not_its_target() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case("link", 0); + let out = run_spool_case(&case, &["-r", "-f"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(std::fs::symlink_metadata(&case.spool).is_err()); + assert!(case.target.exists(), "the link target should be untouched"); +} + +/// A symlink to the user's own file is removed even though the link itself is +/// root's, and the file it points at stays, exit 0. +#[test] +fn test_remove_removes_a_spool_link_to_the_users_own_file() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case("link", 1000); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(std::fs::symlink_metadata(&case.spool).is_err()); + assert!(case.target.exists(), "the link target should be untouched"); + assert!(!case.home.exists(), "the home should have been removed"); +} From 53dfd7e431379d2cc54bf56df34e15c2177677e6 Mon Sep 17 00:00:00 2001 From: Pierre Warnier Date: Sat, 5 Dec 2026 09:56:53 +0100 Subject: [PATCH 2/5] tests: share the /dev/log listener, one test at a time usermod's audit test had it to itself. A second test that listens would find the socket taken by the first and skip without a word, so the listener moves to the common helpers and takes a lock that keeps the next test waiting until the socket is gone. --- tests/by-util/test_usermod.rs | 78 +---------------------------- tests/common/mod.rs | 94 +++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 77 deletions(-) diff --git a/tests/by-util/test_usermod.rs b/tests/by-util/test_usermod.rs index a8bf6670..6a726e60 100644 --- a/tests/by-util/test_usermod.rs +++ b/tests/by-util/test_usermod.rs @@ -1354,82 +1354,6 @@ fn test_rechown_home_that_cannot_be_walked() { } } -/// Listens on `/dev/log` for the life of a test, and removes it afterwards. -/// -/// Sending to a full datagram socket blocks, and every test in this process -/// that logs sends to this one while it exists, this test's own `usermod` -/// included. So a thread keeps it drained the whole time. -struct SyslogListener { - lines: std::sync::Arc>>, - stop: std::sync::Arc, - reader: Option>, -} - -impl SyslogListener { - const PATH: &'static str = "/dev/log"; - - /// `None` where a real syslog daemon already owns the socket: taking it - /// over would lose that daemon's log, and its messages cannot be read here. - fn bind() -> Option { - use std::sync::atomic::Ordering; - - if std::fs::symlink_metadata(Self::PATH).is_ok() { - return None; - } - let socket = std::os::unix::net::UnixDatagram::bind(Self::PATH).expect("bind /dev/log"); - socket - .set_read_timeout(Some(std::time::Duration::from_millis(50))) - .expect("set timeout"); - let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let reader = { - let lines = std::sync::Arc::clone(&lines); - let stop = std::sync::Arc::clone(&stop); - std::thread::spawn(move || { - let mut buf = [0u8; 2048]; - while !stop.load(Ordering::Relaxed) { - if let Ok(n) = socket.recv(&mut buf) { - lines - .lock() - .expect("lines lock") - .push(String::from_utf8_lossy(&buf[..n]).into_owned()); - } - } - }) - }; - Some(Self { - lines, - stop, - reader: Some(reader), - }) - } - - /// The first line about `login`. Tests run in parallel in this process and - /// log too, so lines about other accounts are expected here. - fn line_about(&self, login: &str) -> String { - let needle = format!("acct=\"{login}\""); - for _ in 0..1000 { - let lines = self.lines.lock().expect("lines lock"); - if let Some(line) = lines.iter().find(|line| line.contains(&needle)) { - return line.clone(); - } - drop(lines); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - panic!("no syslog line about {login}"); - } -} - -impl Drop for SyslogListener { - fn drop(&mut self) { - self.stop.store(true, std::sync::atomic::Ordering::Relaxed); - if let Some(reader) = self.reader.take() { - let _ = reader.join(); - } - let _ = std::fs::remove_file(Self::PATH); - } -} - /// The account files are written either way, but a home that could not be /// re-owned means the change did not complete, and exit 12 says so: the audit /// trail must not record the same run as a success. @@ -1438,7 +1362,7 @@ fn test_audit_records_a_failed_home_rechown_as_failed() { if crate::common::skip_unless_root() { return; } - let Some(listener) = SyslogListener::bind() else { + let Some(listener) = crate::common::SyslogListener::bind() else { return; }; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4df7601b..773334a9 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -137,3 +137,97 @@ pub fn run_cmd(cmd: &mut std::process::Command) -> Output { stderr: String::from_utf8_lossy(&out.stderr).into_owned(), } } + +/// Listens on `/dev/log` for the life of a test, and removes it afterwards. +/// +/// Sending to a full datagram socket blocks, and every test in this process +/// that logs sends to this one while it exists, the test's own tool included. +/// So a thread keeps it drained the whole time. +/// +/// There is one `/dev/log`, so tests that listen take turns: a second one +/// waits for the first to drop its listener, where it would otherwise find the +/// socket taken and skip. +pub struct SyslogListener { + lines: std::sync::Arc>>, + stop: std::sync::Arc, + reader: Option>, + // Fields drop after `drop` has run, so the next test waits for the socket to go. + _turn: std::sync::MutexGuard<'static, ()>, +} + +impl SyslogListener { + const PATH: &'static str = "/dev/log"; + + /// `None` where a real syslog daemon already owns the socket: taking it + /// over would lose that daemon's log, and its messages cannot be read here. + #[must_use] + pub fn bind() -> Option { + use std::sync::atomic::Ordering; + + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + // A test that panicked while listening still removed the socket. + let turn = TURN + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if std::fs::symlink_metadata(Self::PATH).is_ok() { + return None; + } + let socket = std::os::unix::net::UnixDatagram::bind(Self::PATH).expect("bind /dev/log"); + socket + .set_read_timeout(Some(std::time::Duration::from_millis(50))) + .expect("set timeout"); + let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let reader = { + let lines = std::sync::Arc::clone(&lines); + let stop = std::sync::Arc::clone(&stop); + std::thread::spawn(move || { + let mut buf = [0u8; 2048]; + while !stop.load(Ordering::Relaxed) { + if let Ok(n) = socket.recv(&mut buf) { + lines + .lock() + .expect("lines lock") + .push(String::from_utf8_lossy(&buf[..n]).into_owned()); + } + } + }) + }; + Some(Self { + lines, + stop, + reader: Some(reader), + _turn: turn, + }) + } + + /// The first line about `login`. Tests run in parallel in this process and + /// log too, so lines about other accounts are expected here. + /// + /// # Panics + /// + /// Panics if no such line arrives within ten seconds. + #[must_use] + pub fn line_about(&self, login: &str) -> String { + let needle = format!("acct=\"{login}\""); + for _ in 0..1000 { + let lines = self.lines.lock().expect("lines lock"); + if let Some(line) = lines.iter().find(|line| line.contains(&needle)) { + return line.clone(); + } + drop(lines); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + panic!("no syslog line about {login}"); + } +} + +impl Drop for SyslogListener { + fn drop(&mut self) { + self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + if let Some(reader) = self.reader.take() { + let _ = reader.join(); + } + let _ = std::fs::remove_file(Self::PATH); + } +} From 0bacf3b27405a5b8568b824fa8cb12ae45ae1399 Mon Sep 17 00:00:00 2001 From: Pierre Warnier Date: Sat, 5 Dec 2026 09:57:04 +0100 Subject: [PATCH 3/5] userdel: exit 12 for a kept spool or home only after the audit record The account is already removed when -r gets to the spool and the home, so returning there skipped the SELinux login mapping, the nscd invalidation and the audit record, all of which concern the account. What is kept is now said where it was, and exit 12 is returned once those have run. Ubuntu 26.04's userdel logs the deletion in this case as well. --- src/uu/userdel/src/userdel.rs | 40 ++++++++++++++++++++-------------- tests/by-util/test_userdel.rs | 41 +++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 16 deletions(-) diff --git a/src/uu/userdel/src/userdel.rs b/src/uu/userdel/src/userdel.rs index 758e9dbf..d23f52c5 100644 --- a/src/uu/userdel/src/userdel.rs +++ b/src/uu/userdel/src/userdel.rs @@ -16,6 +16,7 @@ use clap::{Arg, ArgAction, Command}; use uucore::error::{UError, UResult}; use shadow_core::audit; +use shadow_core::cli::AlreadyPrinted; use shadow_core::error::ShadowError; use shadow_core::group::GroupEntry; use shadow_core::gshadow::GshadowEntry; @@ -201,8 +202,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { // Restore signals before potentially long-running home removal. drop(signals); - // 7. Optionally remove the mail spool and home directory. - if remove_home { + // 7. Optionally remove the mail spool and home directory. The account is + // already gone, so a spool or home that was kept is exit 12 only after + // the steps below have run. + let removal = if remove_home { remove_spool_and_home( &root, login, @@ -210,8 +213,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { saved_uid, force, home_shared_by_other, - )?; - } + ) + } else { + Ok(()) + }; if selinux_user { shadow_core::selinux::remove_login(login) @@ -223,7 +228,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { audit::log_user_event("DEL_USER", login, saved_uid, true); - Ok(()) + removal.map_err(Into::into) } #[must_use] @@ -287,7 +292,8 @@ pub fn uu_app() -> Command { /// /// Either one missing is said on stderr and is not a failure, spool first, as /// upstream does. A spool the user does not own is kept unless `force`; the -/// home is still removed, and the exit status is then `CANT_REMOVE_HOME`. +/// home is still removed. Whatever is kept is said here, in that order, and +/// the error only carries `CANT_REMOVE_HOME` for the caller to return last. fn remove_spool_and_home( root: &SysRoot, login: &str, @@ -295,19 +301,19 @@ fn remove_spool_and_home( uid: u32, force: bool, shared_by_other: bool, -) -> UResult<()> { +) -> Result<(), AlreadyPrinted> { + let mut kept = false; let mail = root.resolve(&format!("/var/mail/{login}")); - let spool_kept = match remove_mail_spool(&mail, uid, force) { - Spool::Removed => false, + match remove_mail_spool(&mail, uid, force) { + Spool::Removed => {} Spool::Missing => { uucore::show_error!("{login} mail spool ({}) not found", mail.display()); - false } Spool::NotOwned => { uucore::show_error!("{} not owned by {login}, not removing", mail.display()); - true + kept = true; } - }; + } if home.is_empty() { // Nothing to remove; upstream names the empty path all the same. @@ -317,15 +323,17 @@ fn remove_spool_and_home( // `exists()` follows a symlink on purpose: Ubuntu 26.04's `userdel -r` // reports a dangling link as not found, exit 0, and leaves it in place. if home.exists() { - safe_remove_home(&home, uid, force, shared_by_other)?; + if let Err(e) = safe_remove_home(&home, uid, force, shared_by_other) { + uucore::show_error!("{e}"); + kept = true; + } } else { uucore::show_error!("{login} home directory ({}) not found", home.display()); } } - if spool_kept { - // Already said above, in its place before anything about the home. - return Err(shadow_core::cli::AlreadyPrinted(exit_codes::CANT_REMOVE_HOME).into()); + if kept { + return Err(AlreadyPrinted(exit_codes::CANT_REMOVE_HOME)); } Ok(()) } diff --git a/tests/by-util/test_userdel.rs b/tests/by-util/test_userdel.rs index ca975a25..10000572 100644 --- a/tests/by-util/test_userdel.rs +++ b/tests/by-util/test_userdel.rs @@ -879,3 +879,44 @@ fn test_remove_removes_a_spool_link_to_the_users_own_file() { assert!(case.target.exists(), "the link target should be untouched"); assert!(!case.home.exists(), "the home should have been removed"); } + +/// The account is gone before the spool is looked at, so keeping the spool +/// must not skip what follows the removal: the audit record, the last of those +/// steps, is still written, and exit 12 comes after it. +#[test] +fn test_remove_keeping_the_spool_still_records_the_deletion() { + if crate::common::skip_unless_root() { + return; + } + let Some(listener) = crate::common::SyslogListener::bind() else { + return; + }; + + // A login of its own: other tests running alongside log about `testuser`. + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let root = dir.path(); + std::fs::create_dir_all(root.join("etc")).expect("etc"); + std::fs::write( + root.join("etc/passwd"), + "root:x:0:0:root:/root:/bin/bash\nspoolaudit:x:1000:1000::/home/spoolaudit:/bin/sh\n", + ) + .expect("passwd"); + std::fs::write(root.join("etc/group"), "root:x:0:\n").expect("group"); + let home = root.join("home/spoolaudit"); + std::fs::create_dir_all(&home).expect("home"); + std::os::unix::fs::chown(&home, Some(1000), Some(1000)).expect("chown home"); + std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); + let spool = root.join("var/mail/spoolaudit"); + std::fs::write(&spool, "mail").expect("spool"); + + let prefix = root.to_str().expect("non-UTF-8 temp path"); + let out = crate::common::run("userdel", &["-P", prefix, "-r", "spoolaudit"]); + out.assert_code(12); + assert!(spool.exists(), "the spool should have been kept"); + assert!(!home.exists(), "the home should have been removed"); + let passwd = std::fs::read_to_string(root.join("etc/passwd")).expect("read passwd"); + assert!(!passwd.contains("spoolaudit:"), "{passwd}"); + let line = listener.line_about("spoolaudit"); + assert!(line.contains("op=DEL_USER"), "{line}"); + assert!(line.contains("res=success"), "{line}"); +} From 990be8012c5385334fce2ffe0276cc3aea44e3f1 Mon Sep 17 00:00:00 2001 From: Pierre Warnier Date: Sat, 5 Dec 2026 09:57:08 +0100 Subject: [PATCH 4/5] userdel: shorten the mail spool comments --- src/uu/userdel/src/userdel.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/uu/userdel/src/userdel.rs b/src/uu/userdel/src/userdel.rs index d23f52c5..78b8dd62 100644 --- a/src/uu/userdel/src/userdel.rs +++ b/src/uu/userdel/src/userdel.rs @@ -348,12 +348,9 @@ enum Spool { /// Remove the mail spool at `mail` unless it belongs to someone other than /// `uid` and `force` is not given. /// -/// Ownership is that of the file the entry leads to: Ubuntu 26.04's `userdel -/// -r` keeps a symlink to another user's file, removes a symlink to the -/// user's own, and reports a dangling one as not found and leaves it. The -/// entry is looked up once through a descriptor on its directory, and the -/// unlink goes through that same descriptor, so the directory cannot be -/// swapped for another between the ownership check and the removal. +/// Ownership is that of the file a symlink leads to; only the link is removed. +/// The check and the unlink go through one descriptor on the directory, so it +/// cannot be swapped in between. fn remove_mail_spool(mail: &Path, uid: u32, force: bool) -> Spool { use rustix::fs::{AtFlags, Mode, OFlags}; @@ -373,7 +370,7 @@ fn remove_mail_spool(mail: &Path, uid: u32, force: bool) -> Spool { if !force && target.st_uid != uid { return Spool::NotOwned; } - // A failed unlink has never been reported here; that is not this check's to change. + // Ignored as it always was here; upstream warns and exits 12, a separate fix. let _ = rustix::fs::unlinkat(&dir, name, AtFlags::empty()); Spool::Removed } From 0befa85048ac8c0269dd2eef080bbc9915c54e77 Mon Sep 17 00:00:00 2001 From: Pierre Warnier Date: Sat, 5 Dec 2026 09:57:08 +0100 Subject: [PATCH 5/5] userdel: take a bool for a spool test's link case --- tests/by-util/test_userdel.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/tests/by-util/test_userdel.rs b/tests/by-util/test_userdel.rs index 10000572..30f99c83 100644 --- a/tests/by-util/test_userdel.rs +++ b/tests/by-util/test_userdel.rs @@ -748,10 +748,9 @@ struct SpoolCase { target: std::path::PathBuf, } -/// `kind` is `"file"` for a regular spool, or `"link"` for a spool that is a -/// symlink to a file outside /var/mail; that file, or the spool itself, is -/// owned by `owner`. -fn spool_case(kind: &str, owner: u32) -> SpoolCase { +/// The spool is a regular file, or with `link` a symlink to a file outside +/// /var/mail; that file, or the spool itself, is owned by `owner`. +fn spool_case(link: bool, owner: u32) -> SpoolCase { let dir = setup_root_dir(); let root = dir.path().to_path_buf(); let home = root.join("home/testuser"); @@ -760,7 +759,7 @@ fn spool_case(kind: &str, owner: u32) -> SpoolCase { std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); let spool = root.join("var/mail/testuser"); let target = root.join("srv-mailbox"); - if kind == "link" { + if link { std::fs::write(&target, "mail").expect("link target"); std::os::unix::fs::chown(&target, Some(owner), Some(owner)).expect("chown target"); std::os::unix::fs::symlink(&target, &spool).expect("spool link"); @@ -792,7 +791,7 @@ fn test_remove_keeps_a_mail_spool_the_user_does_not_own() { return; } - let case = spool_case("file", 0); + let case = spool_case(false, 0); let out = run_spool_case(&case, &["-r"]); out.assert_code(12); assert!(out.stdout.is_empty(), "stdout: {:?}", out.stdout); @@ -815,7 +814,7 @@ fn test_remove_force_removes_a_mail_spool_the_user_does_not_own() { return; } - let case = spool_case("file", 0); + let case = spool_case(false, 0); let out = run_spool_case(&case, &["-r", "-f"]); out.assert_code(0); assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); @@ -831,7 +830,7 @@ fn test_remove_keeps_a_spool_link_to_a_file_the_user_does_not_own() { return; } - let case = spool_case("link", 0); + let case = spool_case(true, 0); let out = run_spool_case(&case, &["-r"]); out.assert_code(12); assert_eq!( @@ -855,7 +854,7 @@ fn test_remove_force_removes_a_spool_link_but_not_its_target() { return; } - let case = spool_case("link", 0); + let case = spool_case(true, 0); let out = run_spool_case(&case, &["-r", "-f"]); out.assert_code(0); assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); @@ -871,7 +870,7 @@ fn test_remove_removes_a_spool_link_to_the_users_own_file() { return; } - let case = spool_case("link", 1000); + let case = spool_case(true, 1000); let out = run_spool_case(&case, &["-r"]); out.assert_code(0); assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr);