diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 11aab00fd4..9d1d63d179 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -260,7 +260,7 @@ Changes from `craft-media-testkit`'s `hammer`: ## temp -`TempDir::new(tag)` makes a new, empty folder `craft-testkit--` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; removal on drop is best effort, and `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix `new` asks for mode 0o700 (the umask can remove more bits), and returns an error when the folder it made is a link, is open to other users or is owned by another user. The check reads mode bits only. It does not read POSIX or NFSv4 access control lists, so an entry that grants another user access is not detected. On Windows the folder gets the inheritable access entries of the temporary directory (the user's own `%LOCALAPPDATA%\Temp` by default) and is not checked. When `TMP` or `TEMP` names a shared folder, other users may be able to open the new folder, depending on that folder's access entries. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder and returns `InvalidInput` for an empty name, `.`, `..`, or a name with `/`, `\`, `:` or NUL. The module is not built for `wasm32`. +`TempDir::new(tag)` makes a new, empty folder `craft-testkit--` in the system temporary directory and returns an error instead of panicking. Dropping it removes the folder with its contents, also when the test panics; removal on drop is best effort, and `close()` removes it and returns the error. A folder with a name that is already taken is skipped and left as it is. On Unix `new` asks for mode 0o700 (the umask can remove more bits), and returns an error when the folder it made is a link, is open to other users or is owned by another user. It returns `PermissionDenied` when the mode lacks owner read, write or search permission. The check reads mode bits only. It does not read POSIX or NFSv4 access control lists, so an entry that grants another user access is not detected. On Windows the folder gets the inheritable access entries of the temporary directory (the user's own `%LOCALAPPDATA%\Temp` by default) and is not checked. When `TMP` or `TEMP` names a shared folder, other users may be able to open the new folder, depending on that folder's access entries. `path()` returns the canonical path (`/private/var/...` on macOS, `\\?\...` on Windows). `file(name)` returns the path of `name` in the folder. On every platform, `new(tag)` and `file(name)` return `InvalidInput` for an empty tag or name, `.`, `..`, or a tag or name with `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*`, NUL or a control character U+0001 to U+001F. The module is not built for `wasm32`. ```rust let dir = craft_testkit::TempDir::new("export")?; diff --git a/crates/testkit/src/temp.rs b/crates/testkit/src/temp.rs index e675d4a145..1b86bcefb6 100644 --- a/crates/testkit/src/temp.rs +++ b/crates/testkit/src/temp.rs @@ -57,10 +57,12 @@ impl TempDir { /// /// # Errors /// - /// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL character. + /// `InvalidInput` when `tag` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`, + /// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform. /// The error from the file system when the folder cannot be made. An error when the folder that /// was made is a link or another kind of entry, is open to other users, or is owned by another - /// user; such a folder is left in place. + /// user; such a folder is left in place. On Unix, `PermissionDenied` when the mode lacks owner + /// read, write or search permission; such a folder is also left in place. pub fn new(tag: &str) -> io::Result { Self::new_in(tag, &std::env::temp_dir(), RANDOM_CHARS) } @@ -73,7 +75,7 @@ impl TempDir { builder.prefix(&prefix).rand_bytes(random); #[cfg(unix)] builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); - Self::guard(builder.tempdir_in(root)?) + Self::guard(builder.tempdir_in(std::fs::canonicalize(root)?)?) } /// Checks the folder `dir` made and returns it with its canonical path. A folder that fails the @@ -96,8 +98,8 @@ impl TempDir { /// /// # Errors /// - /// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:` or a NUL - /// character, so the path always names an entry directly inside the folder. + /// `InvalidInput` when `name` is empty, `.` or `..`, or holds `/`, `\`, `:`, `<`, `>`, `"`, + /// `|`, `?`, `*`, NUL or a control character U+0001 to U+001F, on every platform. pub fn file(&self, name: &str) -> io::Result { one_name("file name", name)?; Ok(self.path.join(name)) @@ -121,7 +123,12 @@ impl AsRef for TempDir { /// Returns `InvalidInput` unless `name` is one path component on every platform. fn one_name(what: &str, name: &str) -> io::Result<()> { - if name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '\0']) { + if name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\\', ':', '<', '>', '"', '|', '?', '*']) + || name.chars().any(|c| c <= '\u{1f}') + { return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{what} {name:?} is not a single file name"))); } Ok(()) @@ -150,7 +157,8 @@ fn verify(path: &Path) -> io::Result<()> { } /// Returns an error unless `entry` is a real folder, not a link, with no access for group or other -/// users, owned by the user `me` returns. `me` runs only after the other checks pass. +/// users, with owner read, write and search permission on Unix, owned by the user `me` returns. +/// `me` runs only after the other checks pass. fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result>) -> io::Result<()> { if entry.is_symlink || !entry.is_dir { return Err(io::Error::other(format!("{}: a link or another kind of entry is in place of the new folder", path.display()))); @@ -158,6 +166,9 @@ fn check(path: &Path, entry: Entry, me: impl FnOnce() -> io::Result> if entry.mode.is_some_and(|mode| mode & 0o077 != 0) { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is open to other users", path.display()))); } + if entry.mode.is_some_and(|mode| mode & 0o700 != 0o700) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the owner cannot use the new folder", path.display()))); + } if entry.owner != me()? { return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the new folder is owned by another user", path.display()))); } @@ -299,6 +310,10 @@ mod tests { let err = TempDir::new(tag).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{tag:?}"); } + for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') { + let tag = format!("a{c}b"); + assert_eq!(TempDir::new(&tag).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{tag:?}"); + } } #[test] @@ -309,6 +324,10 @@ mod tests { let err = dir.file(name).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{name:?}"); } + for c in ['<', '>', '"', '|', '?', '*'].into_iter().chain('\u{1}'..='\u{1f}') { + let name = format!("report{c}.txt"); + assert_eq!(dir.file(&name).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{name:?}"); + } let a = dir.file("a.txt").unwrap(); assert_eq!(a, dir.path().join("a.txt")); assert!(!a.exists(), "file does not make the file"); @@ -374,6 +393,10 @@ mod tests { let err = check(path, Entry { mode: Some(mode), ..private }, || Ok(Some(1000))).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); } + for mode in [0o40300, 0o40500, 0o40600] { + let err = check(path, Entry { mode: Some(mode), ..private }, || panic!("no probe without owner access")).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{mode:o}"); + } let err = check(path, private, || Ok(Some(1001))).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); assert!(check(path, Entry { is_symlink: true, ..private }, || panic!("no probe through a link")).is_err()); @@ -425,8 +448,13 @@ mod tests { assert_eq!(dir.path().parent(), Some(real.as_path()), "the path is canonical"); assert!(dir.path().is_dir()); let path = dir.path().to_path_buf(); + let other = root.path().join("other"); + std::fs::create_dir_all(other.join(path.file_name().unwrap())).unwrap(); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); drop(dir); - assert!(!path.exists()); + assert!(!path.exists(), "the folder that was made is removed after the link changes"); + assert!(other.join(path.file_name().unwrap()).is_dir(), "a folder with the same name under the new target stays"); assert!(real.is_dir() && link.is_symlink(), "the root and the link stay"); }