diff --git a/native/.cargo/mutants.toml b/native/.cargo/mutants.toml index 91d40041..6aea6231 100644 --- a/native/.cargo/mutants.toml +++ b/native/.cargo/mutants.toml @@ -31,6 +31,9 @@ exclude_re = [ "guest-agent/src/net\\.rs:.*GuestNet::(from_proc|configure)", # Equivalent: the VM range tag and a NetId never share bits with a normalised /64. "replace \\| with \\^ in NodePrefix::(vm_range|guest)$", + # Equivalent: the operands never share a bit (no OpenFlags carries O_EXCL without O_CREAT, + # nor O_DIRECTORY or O_CLOEXEC; the RESOLVE_* flags are distinct bits). + "hyperrs-fs/src/(dir|file)\\.rs:.*replace \\| with \\^ in SafeFile<.*>::(openat|open_at|open_raw)$", # Equivalent: the dst-nat chain runs after conntrack and before routing at -100 or 100. "suidhelper/src/net/mod\\.rs:\\d+:\\d+: delete -$", ] diff --git a/native/hyperrs-firecracker/tests/chroot_remove_names.rs b/native/hyperrs-firecracker/tests/chroot_remove_names.rs new file mode 100644 index 00000000..a769a7b0 --- /dev/null +++ b/native/hyperrs-firecracker/tests/chroot_remove_names.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: MIT +//! Teardown contract of [`JailLayout::remove`]: it removes the per-VM chroot whatever the jailed +//! Firecracker left in it, and is idempotent. +//! +//! Laws: +//! - the jail root is owned by the jailed uid, so Firecracker can create any legal file name in +//! it; `remove` must still delete the whole `/firecracker/` tree for every such name +//! (whitespace and non-UTF-8 bytes included), or a VM's jail leaks past teardown; +//! - removing an already-removed jail is `Ok`, and sibling jails are never touched; +//! - `remove` succeeds on a tree deeper than the soft fd limit, which a jail process can build +//! holding one fd at a time, and never follows a link planted in the jail out of the tree. + +use assert_fs::TempDir; +use hyperrs_firecracker::jailer::chroot::JailLayout; +use hyperrs_firecracker::VmId; +use hyperrs_fs::path::{IsAbsolute, SafePathBuf, StrictComponents}; +use nix::fcntl::{openat, OFlag}; +use nix::sys::stat::{mkdirat, Mode}; +use nix::unistd::mkfifo; +use std::ffi::OsStr; +use std::fs; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::symlink; +use std::os::unix::net::UnixListener; +use std::path::Path; + +type Strict = SafePathBuf; + +fn base(tmp: &TempDir) -> Strict { + fs::canonicalize(tmp.path()).unwrap().try_into().unwrap() +} + +#[test] +fn remove_deletes_the_jail_whatever_names_the_guest_side_left_in_it() { + let names: [&[u8]; 9] = [ + b"firecracker.log", + b" ", + b"-rf", + &[b'n'; 255], + b"\xff\xfe", + b"two words", + b"line\nbreak", + b"tab\there", + b"trailing ", + ]; + let leaked: Vec = names + .iter() + .filter_map(|raw| { + let tmp = TempDir::new().unwrap(); + let base = base(&tmp); + let id: VmId = "vm-a".parse().unwrap(); + let sibling: VmId = "vm-b".parse().unwrap(); + let jail = JailLayout::new(&base, &id); + let other = JailLayout::new(&base, &sibling); + jail.create_root().unwrap(); + other.create_root().unwrap(); + fs::write(jail.root().as_path().join(OsStr::from_bytes(raw)), b"x").unwrap(); + + let got = jail.remove(); + let gone = !jail.chroot_dir().as_path().exists(); + assert!(other.root().as_path().is_dir()); + (got.is_err() || !gone).then(|| format!("{:?}: {got:?}", String::from_utf8_lossy(raw))) + }) + .collect(); + assert!( + leaked.is_empty(), + "jail leaked past teardown for {leaked:#?}" + ); +} + +#[test] +fn remove_is_idempotent_and_spares_siblings() { + let tmp = TempDir::new().unwrap(); + let base = base(&tmp); + let id: VmId = "vm-a".parse().unwrap(); + let sibling: VmId = "vm-b".parse().unwrap(); + let jail = JailLayout::new(&base, &id); + let other = JailLayout::new(&base, &sibling); + jail.create_root().unwrap(); + other.create_root().unwrap(); + fs::write(other.root().as_path().join("keep"), b"keep").unwrap(); + + jail.remove().unwrap(); + jail.remove().unwrap(); + + assert!(!jail.chroot_dir().as_path().exists()); + assert_eq!( + fs::read(other.root().as_path().join("keep")).unwrap(), + b"keep" + ); +} + +struct NofileLimit(nix::libc::rlimit); + +impl NofileLimit { + fn lower_to(soft: u64) -> Self { + let mut old = nix::libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + // SAFETY: getrlimit/setrlimit only read/write the rlimit structs passed in. + unsafe { + assert_eq!(nix::libc::getrlimit(nix::libc::RLIMIT_NOFILE, &mut old), 0); + let new = nix::libc::rlimit { + rlim_cur: soft.min(old.rlim_max), + rlim_max: old.rlim_max, + }; + assert_eq!(nix::libc::setrlimit(nix::libc::RLIMIT_NOFILE, &new), 0); + } + Self(old) + } +} + +impl Drop for NofileLimit { + fn drop(&mut self) { + // SAFETY: restores the struct getrlimit returned. + unsafe { nix::libc::setrlimit(nix::libc::RLIMIT_NOFILE, &self.0) }; + } +} + +/// Builds `depth` nested directories below `top` holding only one fd at a time, which is how a +/// jail process can nest past any per-process fd limit. +fn nest(top: &Path, depth: usize) { + let mut cur: OwnedFd = fs::File::open(top).unwrap().into(); + for _ in 0..depth { + mkdirat(Some(cur.as_raw_fd()), "d", Mode::from_bits_truncate(0o755)).unwrap(); + let next = openat( + Some(cur.as_raw_fd()), + "d", + OFlag::O_RDONLY | OFlag::O_DIRECTORY, + Mode::empty(), + ) + .unwrap(); + // SAFETY: openat just returned this fd and nothing else owns it. + cur = unsafe { OwnedFd::from_raw_fd(next) }; + } +} + +#[test] +fn remove_clears_a_tree_deeper_than_the_default_fd_limit() { + let tmp = TempDir::new().unwrap(); + let base = base(&tmp); + let id: VmId = "vm-a".parse().unwrap(); + let jail = JailLayout::new(&base, &id); + jail.create_root().unwrap(); + nest(jail.root().as_path(), 1500); + + let got = { + let _limit = NofileLimit::lower_to(1024); + jail.remove() + }; + + assert!(got.is_ok(), "teardown failed on a 1500-deep tree: {got:?}"); + assert!(!jail.chroot_dir().as_path().exists()); +} + +#[test] +fn remove_never_follows_links_planted_in_the_jail() { + let tmp = TempDir::new().unwrap(); + let base = base(&tmp); + let id: VmId = "vm-a".parse().unwrap(); + let jail = JailLayout::new(&base, &id); + jail.create_root().unwrap(); + let root = jail.root().as_path().to_path_buf(); + let outside = tmp.path().join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join("keep.txt"), b"keep").unwrap(); + let outside_file = tmp.path().join("outside-file"); + fs::write(&outside_file, b"keep").unwrap(); + + symlink(&outside, root.join("to-dir")).unwrap(); + symlink(&outside_file, root.join("to-file")).unwrap(); + fs::create_dir(root.join("nested")).unwrap(); + symlink(tmp.path(), root.join("nested/up")).unwrap(); + fs::hard_link(&outside_file, root.join("hard")).unwrap(); + mkfifo(&root.join("fifo"), Mode::from_bits_truncate(0o600)).unwrap(); + let _sock = UnixListener::bind(root.join("sock")).unwrap(); + + jail.remove().unwrap(); + + assert!(!jail.chroot_dir().as_path().exists()); + assert_eq!(fs::read(outside.join("keep.txt")).unwrap(), b"keep"); + assert_eq!(fs::read(&outside_file).unwrap(), b"keep"); +} diff --git a/native/hyperrs-fs/src/dir.rs b/native/hyperrs-fs/src/dir.rs index 3a4aedfe..3291f622 100644 --- a/native/hyperrs-fs/src/dir.rs +++ b/native/hyperrs-fs/src/dir.rs @@ -6,7 +6,7 @@ use super::file::{ Any, DeviceType, FileType, IsDirectory, OpenFlags, Owner, Ownership, SafeFile, ValidationError, Writability, }; -use super::path::{StrictComponent, StrictComponentBuf}; +use super::path::{ComponentWithWhitespace, ComponentWithWhitespaceBuf, StrictComponent}; use nix::dir::{Dir, Type}; use nix::errno::Errno; use nix::fcntl::{openat2, AtFlags, OFlag, OpenHow, ResolveFlag}; @@ -28,6 +28,8 @@ pub enum DirError { Sys(#[from] Errno), #[error(transparent)] Io(#[from] io::Error), + #[error("directory moved while it was being removed")] + Moved, #[error("existing device node is {found}, expected {expected}")] DeviceMismatch { expected: DeviceNumber, @@ -41,29 +43,41 @@ impl DirError { match self { DirError::Open(ValidationError::Open(errno) | ValidationError::Fstat(errno)) | DirError::Sys(errno) => Some(*errno), - DirError::Open(_) | DirError::Io(_) | DirError::DeviceMismatch { .. } => None, + DirError::Open(_) + | DirError::Io(_) + | DirError::Moved + | DirError::DeviceMismatch { .. } => None, } } } +type FileId = (libc::dev_t, libc::ino_t); + +struct Ancestor { + id: FileId, + name: ComponentWithWhitespaceBuf, + subdirs: Vec, +} + /// See [`SafeFile`]. pub type SafeDir = SafeFile; impl SafeFile { - /// Open `name` relative to this directory and verify it as a [`SafeFile`]. + /// Open `name` relative to this directory and verify it as a [`SafeFile`]. As with + /// [`SafeFile::open`], `flags` apply only after the checks pass. pub fn openat( &self, name: impl AsRef, flags: OpenFlags, mode: Mode, ) -> Result, ValidationError> { - let how = OpenHow::new() - .flags(OFlag::from(flags) | T::OPEN_FLAGS | OFlag::O_CLOEXEC) - .mode(mode) - .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS | ResolveFlag::RESOLVE_BENEATH); - let raw = openat2(self.as_raw_fd(), name.as_ref(), how).map_err(ValidationError::Open)?; - // SAFETY: openat2 just handed us this fd; nobody else owns it. - SafeFile::try_from(unsafe { OwnedFd::from_raw_fd(raw) }) + SafeFile::open_at( + self.as_raw_fd(), + name.as_ref(), + flags, + mode, + ResolveFlag::RESOLVE_NO_SYMLINKS | ResolveFlag::RESOLVE_BENEATH, + ) } /// Create file `name` in this directory, failing if it exists. @@ -154,7 +168,7 @@ impl SafeFile { /// /// Note that this must remain private as this function is a footgun. It's very dangerous and /// risky to use this function as it causes an array of TOCTOU bugs. - fn statat(&self, name: &StrictComponent) -> nix::Result { + fn statat(&self, name: &ComponentWithWhitespace) -> nix::Result { let how = OpenHow::new() .flags(OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC) .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS | ResolveFlag::RESOLVE_BENEATH); @@ -183,22 +197,77 @@ impl SafeFile { } /// Recursively, without following symlinks, remove child `name` and everything under it. + /// Holds a bounded number of fds whatever the depth. Fails with [`DirError::Moved`] if a + /// directory is moved out of the tree mid-walk. pub fn rmdirat_recursive(&self, name: &StrictComponent) -> Result<(), DirError> { - let child: SafeDir = self.openat(name, OpenFlags::RDONLY, Mode::empty())?; - let entries = child.entries()?.collect::>>()?; - for (entry, ty) in entries { - match ty { - Type::Directory => child.rmdirat_recursive(&entry)?, - _ => child.unlinkat(&entry)?, + // Walk with no fd held per level, so depth is bounded by memory rather than + // RLIMIT_NOFILE; climbing through `..` is confined by matching the recorded parent inode. + let mut dir: SafeDir = self.openat(name, OpenFlags::RDONLY, Mode::empty())?; + let mut subdirs = dir.unlink_non_dirs()?; + let mut ancestors: Vec = Vec::new(); + loop { + if let Some(sub) = subdirs.pop() { + let child: SafeDir = dir.openat(&sub, OpenFlags::RDONLY, Mode::empty())?; + ancestors.push(Ancestor { + id: dir.id()?, + name: sub, + subdirs: std::mem::replace(&mut subdirs, child.unlink_non_dirs()?), + }); + dir = child; + } else if let Some(ancestor) = ancestors.pop() { + let parent = dir.parent()?; + if parent.id()? != ancestor.id { + return Err(DirError::Moved); + } + unlinkat( + Some(parent.as_raw_fd()), + ancestor.name.as_path(), + UnlinkatFlags::RemoveDir, + )?; + dir = parent; + subdirs = ancestor.subdirs; + } else { + break; } } + drop(dir); Ok(self.rmdirat(name)?) } + fn unlink_non_dirs(&self) -> Result, DirError> { + let mut subdirs = Vec::new(); + for entry in self.entries()? { + match entry? { + (name, Type::Directory) => subdirs.push(name), + (name, _) => unlinkat( + Some(self.as_raw_fd()), + name.as_path(), + UnlinkatFlags::NoRemoveDir, + )?, + } + } + Ok(subdirs) + } + + fn parent(&self) -> Result { + SafeFile::open_at( + self.as_raw_fd(), + Path::new(".."), + OpenFlags::RDONLY, + Mode::empty(), + ResolveFlag::RESOLVE_NO_SYMLINKS, + ) + } + + fn id(&self) -> nix::Result { + fstat(self.as_raw_fd()).map(|stat| (stat.st_dev, stat.st_ino)) + } + /// Get an iterator through all the entries in this directory. pub fn entries( &self, - ) -> Result> + '_, DirError> { + ) -> Result> + '_, DirError> + { let fresh: SafeDir = self.openat(Path::new("."), OpenFlags::RDONLY, Mode::empty())?; Ok(Dir::from(OwnedFd::from(fresh))? @@ -214,7 +283,7 @@ impl SafeFile { return None; } - let name: &StrictComponent = match OsStr::from_bytes(bytes).try_into() { + let name: &ComponentWithWhitespace = match OsStr::from_bytes(bytes).try_into() { Ok(name) => name, Err(_) => return Some(Err(Errno::EINVAL)), }; @@ -378,4 +447,17 @@ mod tests { ]); assert_eq!(got, want); } + + #[rstest] + fn id_names_one_directory_however_it_is_reached(tmp: TempDir) { + tmp.child("a/child").create_dir_all().unwrap(); + tmp.child("b").create_dir_all().unwrap(); + let root = open(tmp.path()); + let a: SafeDir = root.openat("a", OpenFlags::RDONLY, Mode::empty()).unwrap(); + let b: SafeDir = root.openat("b", OpenFlags::RDONLY, Mode::empty()).unwrap(); + let child: SafeDir = a.openat("child", OpenFlags::RDONLY, Mode::empty()).unwrap(); + + assert_eq!(child.parent().unwrap().id().unwrap(), a.id().unwrap()); + assert_ne!(a.id().unwrap(), b.id().unwrap()); + } } diff --git a/native/hyperrs-fs/src/file.rs b/native/hyperrs-fs/src/file.rs index 4eed6f89..60ded6cb 100644 --- a/native/hyperrs-fs/src/file.rs +++ b/native/hyperrs-fs/src/file.rs @@ -4,6 +4,7 @@ use super::dev::DeviceNumber; use super::path::{IsAbsolute, SafePath, StrictComponents}; use derive_more::{BitOr, Into}; +use nix::errno::Errno; use nix::fcntl::{open, openat2, AtFlags, OFlag, OpenHow, ResolveFlag}; use nix::libc::AT_FDCWD; use nix::sys::stat::{fchmodat, fstat, FchmodatFlags, FileStat, Mode, SFlag}; @@ -11,7 +12,7 @@ use nix::unistd::{dup, fchownat, getgid, getuid, Gid, Uid}; use std::io; use std::marker::PhantomData; use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use thiserror::Error as ThisError; const SECTOR_BYTES: u64 = 512; @@ -61,6 +62,9 @@ pub struct OwnerOnlyWritable; /// What's the type of the file? pub trait FileType { const OPEN_FLAGS: OFlag = OFlag::empty(); + /// Whether an open may create the file. When false, `CREATE_NEW` is refused and `CREATE` + /// only opens an existing file. + const CREATABLE: bool = false; fn check(stat: &FileStat) -> Result<(), ValidationError>; } @@ -76,6 +80,8 @@ pub trait Writability { } impl FileType for Any { + const CREATABLE: bool = true; + fn check(_: &FileStat) -> Result<(), ValidationError> { Ok(()) } @@ -94,6 +100,8 @@ impl Writability for Any { } impl FileType for IsRegularFile { + const CREATABLE: bool = true; + fn check(stat: &FileStat) -> Result<(), ValidationError> { if stat.st_mode & SFlag::S_IFMT.bits() == SFlag::S_IFREG.bits() { Ok(()) @@ -269,19 +277,67 @@ where R: Ownership, O: Writability, { - /// Open `path` and verify it against the type traits. + /// Open `path` and verify it against the type traits. `flags` apply only after the checks + /// pass, so a refused open never blocks on a FIFO, truncates, or creates. pub fn open( path: &SafePath, flags: OpenFlags, + ) -> Result { + Self::open_at( + AT_FDCWD, + path.as_ref(), + flags, + Mode::empty(), + ResolveFlag::RESOLVE_NO_SYMLINKS, + ) + } + + // Validate through an O_PATH probe before applying `flags`, so a refused open never blocks on a + // FIFO, truncates, or creates. + pub(crate) fn open_at( + dir: RawFd, + path: &Path, + flags: OpenFlags, + mode: Mode, + resolve: ResolveFlag, + ) -> Result { + let flags = flags.0; + let create_new = OFlag::O_CREAT | OFlag::O_EXCL; + if flags.contains(OFlag::O_PATH) || (flags.contains(create_new) && T::CREATABLE) { + return Self::open_raw(dir, path, flags, mode, resolve); + } + if flags.contains(create_new) { + return Err(ValidationError::WrongFileType); + } + let create = flags.contains(OFlag::O_CREAT) && T::CREATABLE; + let flags = flags - OFlag::O_CREAT; + loop { + match Self::open_raw(dir, path, OFlag::O_PATH, Mode::empty(), resolve) { + Ok(probe) => return probe.reopen(OpenFlags(flags)), + Err(ValidationError::Open(Errno::ENOENT)) if create => {} + Err(refused) => return Err(refused), + } + match Self::open_raw(dir, path, flags | create_new, mode, resolve) { + Err(ValidationError::Open(Errno::EEXIST)) => {} + created => return created, + } + } + } + + fn open_raw( + dir: RawFd, + path: &Path, + flags: OFlag, + mode: Mode, + resolve: ResolveFlag, ) -> Result { let how = OpenHow::new() - .flags(flags.0 | T::OPEN_FLAGS | OFlag::O_CLOEXEC) - .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS); - let raw = openat2(AT_FDCWD, path.as_ref(), how).map_err(ValidationError::Open)?; + .flags(flags | T::OPEN_FLAGS | OFlag::O_CLOEXEC) + .mode(mode) + .resolve(resolve); + let raw = openat2(dir, path, how).map_err(ValidationError::Open)?; // SAFETY: `openat2` just handed us this fd; nobody else owns it. - let owned = unsafe { OwnedFd::from_raw_fd(raw) }; - - Self::try_from(owned) + Self::try_from(unsafe { OwnedFd::from_raw_fd(raw) }) } pub fn reopen(&self, flags: OpenFlags) -> Result { @@ -351,11 +407,12 @@ mod tests { RootOwner, SafeFile, ValidationError, }; use crate::dir::SafeDir; - use crate::path::{IsAbsolute, SafePathBuf, StrictComponents}; + use crate::path::{IsAbsolute, SafePathBuf, StrictComponent, StrictComponents}; use assert_fs::fixture::ChildPath; use assert_fs::prelude::*; use assert_fs::TempDir; use nix::errno::Errno; + use nix::fcntl::{fcntl, FcntlArg, FdFlag}; use nix::sys::stat::Mode; use pretty_assertions::assert_eq; use rstest::{fixture, rstest}; @@ -363,6 +420,7 @@ mod tests { use std::fs; use std::io::{Read, Write}; use std::os::unix::fs::PermissionsExt; + use std::os::unix::io::AsRawFd; use std::path::Path; type Strict = SafePathBuf; @@ -486,4 +544,35 @@ mod tests { "{path} with {flags:?}" ); } + + type Opened = Result, ValidationError>; + + #[rstest] + #[case::path_probe(|dir: &SafeDir| -> Opened { + dir.openat(Path::new("plain"), OpenFlags::PATH, Mode::empty()) + })] + #[case::reopened(|dir: &SafeDir| -> Opened { + dir.openat(Path::new("plain"), OpenFlags::RDONLY, Mode::empty()) + })] + #[case::created_new(|dir: &SafeDir| -> Opened { + dir.mkfileat(StrictComponent::from_static("new"), Mode::from_bits_truncate(0o600)) + })] + #[case::created(|dir: &SafeDir| -> Opened { + dir.openat( + Path::new("new"), + OpenFlags::WRONLY | OpenFlags::CREATE, + Mode::from_bits_truncate(0o600), + ) + })] + fn every_open_is_close_on_exec( + plain: (TempDir, ChildPath), + #[case] open: fn(&SafeDir) -> Opened, + ) { + let (tmp, _) = plain; + let dir = SafeDir::open(&safe(tmp.path()), OpenFlags::RDONLY).unwrap(); + let file = open(&dir).unwrap(); + let fd_flags = + FdFlag::from_bits_truncate(fcntl(file.as_raw_fd(), FcntlArg::F_GETFD).unwrap()); + assert!(fd_flags.contains(FdFlag::FD_CLOEXEC), "{fd_flags:?}"); + } } diff --git a/native/hyperrs-fs/src/path.rs b/native/hyperrs-fs/src/path.rs index 9da96a1e..e81cd296 100644 --- a/native/hyperrs-fs/src/path.rs +++ b/native/hyperrs-fs/src/path.rs @@ -54,33 +54,24 @@ impl StrictComponent { #[ref_cast_custom] const fn new_unchecked(bytes: &[u8]) -> &Self; - const fn check(bytes: &[u8]) -> Result<(), ComponentError> { - match bytes { - [] => return Err(ComponentError::Empty), - b"." => return Err(ComponentError::CurrentDir), - b".." => return Err(ComponentError::ParentDir), - _ => {} - } - if bytes.len() > NAME_MAX { - return Err(ComponentError::TooLong(bytes.len())); - } + const fn from_bytes(bytes: &[u8]) -> Result<&Self, ComponentError> { + let name = match ComponentWithWhitespace::from_bytes(bytes) { + Ok(name) => name, + Err(e) => return Err(e), + }; let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'/' => return Err(ComponentError::Separator), - 0 => return Err(ComponentError::Nul), - b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r' => { - return Err(ComponentError::Whitespace) - } - _ => i += 1, + while i < name.0.len() { + if matches!(name.0[i], b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r') { + return Err(ComponentError::Whitespace); } + i += 1; } - Ok(()) + Ok(Self::new_unchecked(&name.0)) } pub const fn from_static(name: &'static str) -> &'static Self { - match Self::check(name.as_bytes()) { - Ok(()) => Self::new_unchecked(name.as_bytes()), + match Self::from_bytes(name.as_bytes()) { + Ok(name) => name, Err(_) => panic!("not a strict path component"), } } @@ -97,8 +88,7 @@ impl StrictComponent { impl<'a> TryFrom<&'a OsStr> for &'a StrictComponent { type Error = ComponentError; fn try_from(name: &'a OsStr) -> Result { - StrictComponent::check(name.as_bytes())?; - Ok(StrictComponent::new_unchecked(name.as_bytes())) + StrictComponent::from_bytes(name.as_bytes()) } } @@ -147,6 +137,89 @@ impl AsRef for StrictComponentBuf { } } +/// Like [`StrictComponent`], but whitespace is allowed. +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, RefCastCustom, derive_more::Debug)] +#[debug("{:?}", self.as_os_str())] +#[repr(transparent)] +pub struct ComponentWithWhitespace([u8]); + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Debug)] +#[debug("{:?}", self.as_os_str())] +pub struct ComponentWithWhitespaceBuf(Box<[u8]>); + +impl ComponentWithWhitespace { + #[ref_cast_custom] + const fn new_unchecked(bytes: &[u8]) -> &Self; + + const fn from_bytes(bytes: &[u8]) -> Result<&Self, ComponentError> { + match bytes { + [] => return Err(ComponentError::Empty), + b"." => return Err(ComponentError::CurrentDir), + b".." => return Err(ComponentError::ParentDir), + _ => {} + } + if bytes.len() > NAME_MAX { + return Err(ComponentError::TooLong(bytes.len())); + } + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'/' => return Err(ComponentError::Separator), + 0 => return Err(ComponentError::Nul), + _ => i += 1, + } + } + Ok(Self::new_unchecked(bytes)) + } + + pub fn as_os_str(&self) -> &OsStr { + OsStr::from_bytes(&self.0) + } + + pub fn as_path(&self) -> &Path { + Path::new(self.as_os_str()) + } +} + +impl<'a> TryFrom<&'a OsStr> for &'a ComponentWithWhitespace { + type Error = ComponentError; + fn try_from(name: &'a OsStr) -> Result { + ComponentWithWhitespace::from_bytes(name.as_bytes()) + } +} + +impl AsRef for ComponentWithWhitespace { + fn as_ref(&self) -> &Path { + self.as_path() + } +} + +impl ToOwned for ComponentWithWhitespace { + type Owned = ComponentWithWhitespaceBuf; + fn to_owned(&self) -> ComponentWithWhitespaceBuf { + ComponentWithWhitespaceBuf(self.0.into()) + } +} + +impl Deref for ComponentWithWhitespaceBuf { + type Target = ComponentWithWhitespace; + fn deref(&self) -> &ComponentWithWhitespace { + ComponentWithWhitespace::new_unchecked(&self.0) + } +} + +impl Borrow for ComponentWithWhitespaceBuf { + fn borrow(&self) -> &ComponentWithWhitespace { + self + } +} + +impl AsRef for ComponentWithWhitespaceBuf { + fn as_ref(&self) -> &Path { + self.as_path() + } +} + #[derive(Debug, ThisError)] pub enum RelativeError { #[error("path is not under the required base directory")] @@ -205,7 +278,7 @@ const fn check_strict_components(raw: &[u8]) -> Result<(), ComponentError> { end += 1; } let (segment, tail) = rest.split_at(end); - if let Err(e) = StrictComponent::check(segment) { + if let Err(e) = StrictComponent::from_bytes(segment) { return Err(e); } match tail { @@ -381,13 +454,14 @@ where #[cfg(test)] mod tests { use super::{ - ComponentError, IsAbsolute, RelativeError, SafePath, SafePathBuf, StrictComponent, - StrictComponents, ValidationError, + ComponentError, ComponentWithWhitespace, IsAbsolute, RelativeError, SafePath, SafePathBuf, + StrictComponent, StrictComponents, ValidationError, }; use pretty_assertions::assert_eq; use proptest::prelude::*; use rstest::rstest; use std::assert_matches; + use std::ffi::OsStr; use std::path::{Path, PathBuf}; use test_strategy::proptest; @@ -475,6 +549,25 @@ mod tests { ); } + #[proptest] + fn rejects_a_nul_byte_anywhere_in_any_component_kind( + #[strategy(safe_component())] head: String, + #[strategy(safe_component())] tail: String, + #[strategy(0usize..3)] at: usize, + ) { + let bad = match at { + 0 => format!("\0{head}"), + 1 => format!("{head}\0{tail}"), + _ => format!("{head}\0"), + }; + let bad = OsStr::new(&bad); + assert_matches!(<&StrictComponent>::try_from(bad), Err(ComponentError::Nul)); + assert_matches!( + <&ComponentWithWhitespace>::try_from(bad), + Err(ComponentError::Nul) + ); + } + #[proptest] fn rejects_relative_paths(#[strategy(components(1..6))] parts: Vec) { let rel: PathBuf = parts.iter().collect(); diff --git a/native/hyperrs-fs/tests/dir_confinement.proptest-regressions b/native/hyperrs-fs/tests/dir_confinement.proptest-regressions new file mode 100644 index 00000000..063726f1 --- /dev/null +++ b/native/hyperrs-fs/tests/dir_confinement.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc cb517a93f9b9b43a5b0c16e00ed4a9f6594a61befc18e55a9f09e5c404588253 # shrinks to children = [Dir([File, File])], names = [[97], [97], [116, 119, 111, 32, 119, 111, 114, 100, 115], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97], [97]] diff --git a/native/hyperrs-fs/tests/dir_confinement.rs b/native/hyperrs-fs/tests/dir_confinement.rs new file mode 100644 index 00000000..a8ea9d18 --- /dev/null +++ b/native/hyperrs-fs/tests/dir_confinement.rs @@ -0,0 +1,367 @@ +// SPDX-License-Identifier: MIT +//! Confinement contract of [`SafeDir`]: fd-anchored operations never act through a planted link +//! and never reach outside the anchor. +//! +//! Laws under test: +//! - **`openat` is lexical-beneath.** For any relative name built from real dirs, `.` and `..`, +//! the open succeeds iff the walk never climbs above the anchor (oracle: running depth never +//! negative); a climb is always `EXDEV`, never a successful open of something outside. +//! - **Planted names are refused, never followed.** `mkfileat` over any existing entry (file, +//! dir, symlink to a file outside, dangling symlink to a path outside) is `EEXIST` and creates or +//! writes nothing outside; `ensure_dir` over a symlink-to-dir or a file is an error and creates +//! nothing in the link's target; `make_device` over a planted non-device or symlink is refused +//! without chowning/chmodding the planted file or the link's target. +//! - **`entries` is the directory listing.** For any set of names the kernel accepts (any bytes +//! but `/` and NUL, whitespace and non-UTF-8 included), it reports exactly those names. +//! - **`rmdirat_recursive` removes the whole tree and only the tree.** For any tree of dirs, files +//! and symlinks pointing outside, the tree is gone afterwards and everything outside is intact, +//! whatever bytes the entry names hold (spaces, newlines and non-UTF-8 bytes are legal names a +//! tree can contain); a target that is itself a symlink is refused and nothing is removed. + +use assert_fs::TempDir; +use hyperrs_fs::dev::{DeviceNode, DeviceNumber}; +use hyperrs_fs::dir::SafeDir; +use hyperrs_fs::file::{Any, IsBlockDevice, IsDirectory, OpenFlags, Owner, ValidationError}; +use hyperrs_fs::path::{IsAbsolute, SafePathBuf, StrictComponent, StrictComponents}; +use nix::errno::Errno; +use nix::sys::stat::Mode; +use proptest::prelude::*; +use std::assert_matches; +use std::collections::BTreeSet; +use std::ffi::{OsStr, OsString}; +use std::fs; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +type Strict = SafePathBuf; + +fn open(p: &Path) -> SafeDir { + let strict: Strict = p.to_path_buf().try_into().expect("strict tmp path"); + SafeDir::open(&strict, OpenFlags::RDONLY).unwrap() +} + +fn name(s: &str) -> &StrictComponent { + s.try_into().unwrap() +} + +fn mode_of(p: &Path) -> u32 { + fs::symlink_metadata(p).unwrap().mode() & 0o7777 +} + +struct World { + _tmp: TempDir, + anchor: PathBuf, + outside_file: PathBuf, + outside_dir: PathBuf, + outside_absent: PathBuf, +} + +impl World { + fn new() -> Self { + let tmp = TempDir::new().unwrap(); + let anchor = tmp.path().join("anchor"); + fs::create_dir(&anchor).unwrap(); + let outside_file = tmp.path().join("outside-file"); + fs::write(&outside_file, b"outside").unwrap(); + fs::set_permissions(&outside_file, fs::Permissions::from_mode(0o640)).unwrap(); + let outside_dir = tmp.path().join("outside-dir"); + fs::create_dir(&outside_dir).unwrap(); + fs::write(outside_dir.join("keep"), b"keep").unwrap(); + Self { + outside_absent: tmp.path().join("outside-absent"), + _tmp: tmp, + anchor, + outside_file, + outside_dir, + } + } + + fn assert_outside_intact(&self) { + assert_eq!(fs::read(&self.outside_file).unwrap(), b"outside"); + assert_eq!(mode_of(&self.outside_file), 0o640); + let listing: Vec<_> = fs::read_dir(&self.outside_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(listing, [OsString::from("keep")]); + assert_eq!(fs::read(self.outside_dir.join("keep")).unwrap(), b"keep"); + assert!(fs::symlink_metadata(&self.outside_absent).is_err()); + } + + fn plant(&self, how: Plant, at: &Path) { + match how { + Plant::File => fs::write(at, b"planted").unwrap(), + Plant::Dir => fs::create_dir(at).unwrap(), + Plant::LinkToFile => symlink(&self.outside_file, at).unwrap(), + Plant::LinkToDir => symlink(&self.outside_dir, at).unwrap(), + Plant::Dangling => symlink(&self.outside_absent, at).unwrap(), + } + } +} + +#[derive(Debug, Clone, Copy)] +enum Plant { + File, + Dir, + LinkToFile, + LinkToDir, + Dangling, +} + +const PLANTS: [Plant; 5] = [ + Plant::File, + Plant::Dir, + Plant::LinkToFile, + Plant::LinkToDir, + Plant::Dangling, +]; + +#[test] +fn mkfileat_refuses_every_planted_name_and_writes_nothing_outside() { + for plant in PLANTS { + let w = World::new(); + w.plant(plant, &w.anchor.join("victim")); + assert_matches!( + open(&w.anchor).mkfileat(name("victim"), Mode::from_bits_truncate(0o644)), + Err(ValidationError::Open(Errno::EEXIST)), + "{plant:?}" + ); + w.assert_outside_intact(); + } +} + +#[test] +fn ensure_dir_never_resolves_a_planted_link_or_file() { + for plant in [ + Plant::File, + Plant::LinkToDir, + Plant::LinkToFile, + Plant::Dangling, + ] { + let w = World::new(); + let at = w.anchor.join("victim"); + w.plant(plant, &at); + let got = open(&w.anchor) + .ensure_dir(name("victim"), Mode::from_bits_truncate(0o700)) + .and_then(|dir| dir.ensure_dir(name("child"), Mode::from_bits_truncate(0o700))); + assert!(got.is_err(), "{plant:?}"); + assert!(!fs::symlink_metadata(&at).unwrap().is_dir(), "{plant:?}"); + w.assert_outside_intact(); + } +} + +#[test] +fn make_device_never_adopts_a_planted_non_device() { + let me = Owner::caller(); + for plant in [Plant::File, Plant::Dir, Plant::LinkToFile, Plant::Dangling] { + let w = World::new(); + let at = w.anchor.join("rootfs"); + w.plant(plant, &at); + let before = fs::symlink_metadata(&at).unwrap(); + let node = DeviceNode::::new( + DeviceNumber::new(7, 0), + Mode::from_bits_truncate(0o666), + ); + let got = open(&w.anchor).make_device(name("rootfs"), node, me); + assert!(got.is_err(), "{plant:?}"); + let after = fs::symlink_metadata(&at).unwrap(); + assert_eq!(after.mode(), before.mode(), "{plant:?}"); + assert_eq!(after.file_type(), before.file_type(), "{plant:?}"); + w.assert_outside_intact(); + } +} + +#[derive(Debug, Clone, Copy, PartialEq)] +enum Step { + Into(&'static str), + Dot, + Up, +} + +fn step() -> impl Strategy { + prop_oneof![ + 3 => prop::sample::select(vec!["a", "b"]).prop_map(Step::Into), + 1 => Just(Step::Dot), + 2 => Just(Step::Up), + ] +} + +fn stays_beneath(steps: &[Step]) -> bool { + let mut depth = 0i32; + for s in steps { + match s { + Step::Into(_) => depth += 1, + Step::Dot => {} + Step::Up => depth -= 1, + } + if depth < 0 { + return false; + } + } + true +} + +fn build_nested(root: &Path, depth: usize) { + if depth == 0 { + return; + } + for d in ["a", "b"] { + let child = root.join(d); + fs::create_dir(&child).unwrap(); + build_nested(&child, depth - 1); + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn openat_succeeds_iff_the_walk_stays_beneath_the_anchor( + steps in prop::collection::vec(step(), 1..7), + ) { + let tmp = TempDir::new().unwrap(); + let outer = tmp.path().join("a"); + fs::create_dir(&outer).unwrap(); + let anchor = outer.join("a"); + fs::create_dir(&anchor).unwrap(); + build_nested(&anchor, 6); + + let rel: PathBuf = steps + .iter() + .map(|s| match s { + Step::Into(d) => *d, + Step::Dot => ".", + Step::Up => "..", + }) + .collect(); + let got = open(&anchor).openat::(&rel, OpenFlags::PATH, Mode::empty()); + if stays_beneath(&steps) { + prop_assert!(got.is_ok(), "{rel:?}: {got:?}"); + } else { + prop_assert!(matches!(got, Err(ValidationError::Open(Errno::EXDEV))), "{rel:?}: {got:?}"); + } + } + + #[test] + fn entries_lists_exactly_the_created_names( + names in prop::collection::btree_set(prop::collection::vec(1u8..=255, 1..12), 0..12), + ) { + let names: BTreeSet = names + .into_iter() + .filter(|n| !n.contains(&b'/') && n != b"." && n != b"..") + .map(|n| OsStr::from_bytes(&n).to_os_string()) + .collect(); + let tmp = TempDir::new().unwrap(); + for (i, n) in names.iter().enumerate() { + let p = tmp.path().join(n); + if i % 2 == 0 { fs::write(p, b"").unwrap() } else { fs::create_dir(p).unwrap() } + } + let got: BTreeSet = open(tmp.path()) + .entries() + .unwrap() + .map(|e| e.map(|(n, _)| n.as_os_str().to_os_string())) + .collect::>() + .unwrap(); + prop_assert_eq!(got, names); + } +} + +#[derive(Debug, Clone)] +enum Node { + File, + Link(Plant), + Dir(Vec), +} + +fn node() -> impl Strategy { + let leaf = prop_oneof![ + 2 => Just(Node::File), + 1 => prop::sample::select(vec![Plant::LinkToFile, Plant::LinkToDir, Plant::Dangling]).prop_map(Node::Link), + ]; + leaf.prop_recursive(4, 24, 4, |inner| { + prop::collection::vec(inner, 0..4).prop_map(Node::Dir) + }) +} + +fn entry_name() -> impl Strategy> { + prop_oneof![ + 4 => "[a-z]{1,6}".prop_map(String::into_bytes), + 1 => Just(vec![0xff, 0xfe, b'x']), + 1 => Just(b".hidden".to_vec()), + ] +} + +fn materialize(w: &World, node: &Node, at: &Path, names: &mut impl Iterator>) { + match node { + Node::File => fs::write(at, b"x").unwrap(), + Node::Link(plant) => w.plant(*plant, at), + Node::Dir(children) => { + fs::create_dir(at).unwrap(); + for (i, child) in children.iter().enumerate() { + let mut raw = names.next().unwrap(); + raw.extend(format!("{i}").bytes()); + materialize(w, child, &at.join(OsStr::from_bytes(&raw)), names); + } + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn rmdirat_recursive_removes_the_tree_and_only_the_tree( + children in prop::collection::vec(node(), 0..4), + names in prop::collection::vec(entry_name(), 64), + ) { + let w = World::new(); + let tree = w.anchor.join("tree"); + materialize(&w, &Node::Dir(children.clone()), &tree, &mut names.into_iter().cycle()); + + let got = open(&w.anchor).rmdirat_recursive(name("tree")); + prop_assert!(got.is_ok(), "{children:?}: {got:?}"); + prop_assert!(fs::symlink_metadata(&tree).is_err()); + w.assert_outside_intact(); + } +} + +#[test] +fn rmdirat_recursive_removes_trees_holding_any_legal_entry_name() { + let names: [&[u8]; 5] = [ + b"two words", + b"line\nbreak", + b"tab\there", + b"trailing ", + b"\xff\xfe", + ]; + let failures: Vec = names + .iter() + .filter_map(|raw| { + let tmp = TempDir::new().unwrap(); + let tree = tmp.path().join("tree"); + fs::create_dir(&tree).unwrap(); + fs::write(tree.join(OsStr::from_bytes(raw)), b"x").unwrap(); + let got = open(tmp.path()).rmdirat_recursive(name("tree")); + (got.is_err() || tree.exists()) + .then(|| format!("{:?}: {got:?}", String::from_utf8_lossy(raw))) + }) + .collect(); + assert!(failures.is_empty(), "tree not removed for {failures:#?}"); +} + +#[test] +fn rmdirat_recursive_refuses_a_symlinked_target_and_removes_nothing() { + let w = World::new(); + let link = w.anchor.join("tree"); + symlink(&w.outside_dir, &link).unwrap(); + assert_matches!( + open(&w.anchor).rmdirat_recursive(name("tree")), + Err(e) if e.errno() == Some(Errno::ELOOP) + ); + assert!(fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink()); + w.assert_outside_intact(); +} diff --git a/native/hyperrs-fs/tests/file_open_refusal.proptest-regressions b/native/hyperrs-fs/tests/file_open_refusal.proptest-regressions new file mode 100644 index 00000000..9464094c --- /dev/null +++ b/native/hyperrs-fs/tests/file_open_refusal.proptest-regressions @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 5d0d7decb710113a2a7389ccbe70ec078b4dbb7c8e6c991ccfec5754b1e0ecd4 # shrinks to bytes = [127, 80, 212, 163, 3, 160, 24, 6, 113, 15, 8, 123, 170, 100, 167, 249, 74, 69, 213, 128, 126, 86, 98, 89, 115, 34, 184, 242, 20, 87, 176, 86, 197, 46, 76, 247, 118, 152, 202, 194, 202, 77, 72, 240, 183, 129, 217, 144, 228, 111, 241, 248, 200, 25, 114, 60, 232, 150, 166, 184, 252, 224, 252, 1, 59, 19, 188, 254, 168, 114, 213, 76, 157, 235, 139, 53, 45, 123, 3, 248, 94, 112, 63, 247, 78, 94, 175, 52, 91, 232, 138, 124, 156, 146, 42, 249, 208, 217, 167, 29, 126, 240, 171, 66, 56, 220, 103, 131, 26, 89, 36, 197, 3, 194, 31, 68, 210, 61, 129, 10, 253, 238, 196, 145, 230, 231, 118, 109, 191, 227, 219, 181, 250, 9, 72, 56, 120, 241, 11, 114, 223, 21, 178, 244, 154, 248, 84, 146, 159, 65, 21, 122, 112, 12, 210, 216, 141, 228, 219, 237, 82, 82, 149, 124, 139, 74, 200, 108, 205, 111, 196, 211, 23, 204, 138, 35, 143, 87, 130, 46, 243, 4, 177, 29, 95, 31, 115, 128, 92, 55, 59, 163, 167, 130, 197, 198, 170, 98, 127, 136, 169, 152, 245, 203, 28, 100, 250, 75, 172, 158, 189, 229, 17, 100, 88, 26, 57, 226, 81, 129, 68, 191, 83, 132, 0, 13, 199, 191, 177, 26, 135, 197, 108, 251, 129, 68, 202, 118, 128, 144, 226, 216, 189, 20, 33, 245, 98, 10, 80, 96, 146, 31, 224, 100, 123, 231, 113, 217, 17, 208, 39, 248, 17, 189, 140, 168, 237, 141, 235, 101, 219, 104, 171, 18, 95, 99, 32, 142, 93, 46, 5, 212, 10, 140, 30, 126, 22, 136, 36, 57, 178, 244, 181, 22, 23, 32, 201, 196, 69, 157, 137, 37, 224, 218, 235, 66, 20, 212, 42, 51, 103, 174, 216, 94, 169, 61, 13, 70, 52, 71, 94, 8, 45, 218, 80, 96, 45, 97, 189, 127, 13, 213, 92, 95, 32, 193, 194, 170, 166, 91, 110, 72, 108, 66, 133, 48, 83, 93, 124, 166, 192, 43, 227, 0, 121, 184, 216, 181, 229, 141, 62, 41, 157, 10, 49, 39, 142, 125, 153, 48, 246, 127, 61, 238, 228, 62, 25, 170, 77, 88, 142, 203, 73, 111, 135, 235, 184, 122, 142, 220, 255, 113, 123, 229, 239, 129, 163, 113, 25, 223, 247, 8, 90, 110, 103, 125, 30, 95, 48, 168, 124, 158, 97, 59, 249, 245, 91, 30, 19, 211, 16, 225, 74, 197, 134, 204, 132, 0, 252, 167, 223, 115, 210, 74, 130, 183, 48, 16, 101, 100, 219, 203, 225, 134, 145, 209, 215, 58, 212, 223, 134, 74, 3, 150, 120, 9, 114, 13, 157, 75, 127, 5, 155, 163, 106, 130, 246, 47, 222, 92, 194, 173, 83, 160, 194, 32, 172, 168, 48, 160, 249, 88, 26, 84, 193, 15, 56, 253, 117, 115, 108, 21, 177, 209, 187, 163, 40, 183, 220, 65, 215, 120, 101, 206, 161, 168, 69, 141, 94, 17, 196, 115, 81, 176, 66, 66, 104, 208, 206, 239, 78, 12, 233, 208, 208, 253, 85, 10, 115, 68, 179, 80, 35, 70, 188, 38, 177, 34, 206, 161, 214, 128, 138, 153, 186, 46, 189, 42, 171, 235, 252, 136, 192, 167, 22, 123, 12, 16, 200, 240, 134, 112, 160, 140, 80, 98, 217, 183, 15, 101, 174, 221, 249, 111, 17, 46, 126, 48, 154, 42, 165, 165, 80, 31, 251, 194, 5, 52, 159, 122, 100, 71, 9, 190, 101, 140, 83, 17, 218, 26, 233, 29, 126, 96, 132, 47, 85, 28, 134, 118, 150, 65, 65, 6, 103, 30, 171, 10, 75, 250, 161, 174, 9, 91, 178, 243, 128, 220, 226, 118, 195, 90, 248, 245, 131, 29, 29, 92, 48, 47, 100, 10, 93, 9, 10, 152, 136, 149, 20, 34, 167, 187, 126, 60, 151, 186, 87, 49, 179, 76, 71, 62, 101, 161, 219, 92, 58, 61, 171, 230, 215, 148, 134, 22, 73, 23, 4, 53, 164, 35, 223, 171, 130, 198, 225, 38, 34, 150, 175, 202, 220, 177, 144, 136, 222, 3, 141, 54, 95, 108, 10, 41, 84, 229, 128, 163, 243, 130, 47, 223, 218, 210, 40, 169, 149, 155, 142, 252, 5, 154, 71, 253, 45, 237, 155, 178, 254, 57, 5, 205, 41, 144, 77, 46, 187, 1, 139, 146, 43, 143, 65, 197, 124, 97, 4, 160, 220, 36, 183, 114, 240, 105, 11, 237, 233, 217, 214, 188, 108, 47, 224, 223, 49, 238, 141, 18, 61, 118, 246, 90, 230, 27, 228, 63, 13, 106, 220, 194, 182, 154, 118, 149, 233, 15, 27, 80, 243, 20, 201, 21, 55, 143, 126, 176, 204, 86, 251, 252, 112, 13, 218, 246, 183, 18, 113, 59, 90, 165, 99, 11, 197, 79, 62, 58, 152, 192, 152, 9, 156, 127, 231, 99, 5, 212, 202, 78, 215, 247, 201, 98, 4, 145, 156, 23, 252, 150, 106, 230, 76, 186, 53, 54, 130, 197, 63, 174, 118, 64, 212, 159, 143, 125, 157, 63, 144, 196, 75, 97, 198, 62, 211, 74, 52, 162, 62, 242, 81, 93, 183, 81, 120, 240, 12, 11, 229, 153, 96, 186, 164, 224, 45, 233, 238, 81, 108, 134, 121, 211, 238, 249, 54, 210, 54, 204, 186, 206, 44, 86, 79, 153, 31, 173, 211, 94, 170, 25, 51, 99, 222, 97, 170, 111, 55, 37, 206, 161, 129, 179, 199, 215, 236, 27, 125, 36, 105, 129, 180, 91, 230, 181, 133, 52, 225, 70, 205, 28, 128, 10, 93, 84, 11, 55, 186, 113, 226, 203, 240, 49, 142, 20, 202, 10, 99, 246, 8, 20, 90, 137, 210, 152, 73, 7, 192, 154, 205, 52, 170, 72, 246, 222, 249, 244, 209, 91, 188, 57, 88, 205, 242, 141, 62, 236, 9, 98, 90, 67, 8, 105, 245, 108, 244, 153, 11, 16, 194, 106, 166, 209, 134, 62, 67, 61, 196, 241, 165, 19, 34, 173, 37, 41, 18, 139, 255, 129, 51, 152, 240, 194, 30, 176, 228, 242, 235, 194, 40, 133, 206, 175, 194, 36, 6, 237, 92, 77, 4, 225, 57, 208, 6, 166, 50, 101, 217, 63, 29, 95, 252, 240, 251, 94, 221, 94, 30, 6, 120, 131, 103, 226, 134, 213, 183, 214, 66, 19, 135, 129, 221, 137, 208, 215, 215, 122, 69, 87, 118, 14, 182, 68, 210, 232, 92, 212, 164, 116, 183, 90, 76, 206, 199, 33, 115, 19, 21, 95, 250, 120, 120, 112, 131, 118, 180, 8, 21, 50, 197, 110, 177, 139, 135, 255, 59, 173, 61, 234, 151, 152, 171, 74, 112, 36, 162, 74, 65, 198, 218, 105, 235, 122, 1, 62, 91, 148, 94, 197, 200, 202, 84, 68, 101, 140, 192, 221, 82, 199, 98, 104, 18, 104, 183, 205, 152, 176, 57, 155, 203, 208, 7, 59, 46, 161, 107, 151, 9, 249, 212, 210, 47, 103, 98, 186, 17, 210, 161, 60, 107, 15, 141, 61, 182, 27, 175, 127, 116, 194, 233, 197, 160, 95, 239, 134, 255, 149, 21, 175, 151, 150, 159, 210, 183, 254, 95, 75, 91, 38, 99, 125, 235, 31, 110, 181, 30, 89, 132, 244, 75, 74, 245, 215, 241, 56, 39, 100, 177, 207, 22, 242, 42, 203, 224, 153, 165, 163, 179, 180, 42, 218, 190, 92, 121, 160, 167, 165, 166, 234, 16, 138, 98, 48, 22, 241, 0, 230, 190, 74, 245, 173, 80, 241, 12, 166, 117, 151, 158, 29, 125, 9, 225, 81, 228, 225, 207, 15, 19, 240, 113, 0, 168, 109, 91, 84, 246, 78, 82, 36, 95, 83, 8, 55, 70, 149, 117, 76, 59, 118, 239, 237, 70, 36, 205, 100, 107, 22, 165, 126, 56, 109, 26, 120, 228, 177, 27, 0, 55, 163, 229, 146, 28, 226, 120, 244, 110, 241, 144, 144, 37, 180, 138, 203, 196, 39, 212, 62, 191, 67, 166, 107, 192, 178, 76, 58, 75, 27, 58, 72, 76, 51, 131, 89, 223, 171, 157, 19, 133, 176, 253, 247, 183, 88, 8, 241, 67, 31, 209, 239, 45, 204, 50, 47, 8, 71, 230, 13, 39, 58, 239, 21, 2, 191, 217, 56, 216, 106, 183, 12, 29, 206, 247, 118, 32, 74, 205, 48, 53, 207, 223, 7, 98, 130, 254, 64, 142, 208, 239, 235, 202, 20, 235, 99, 118, 22, 53, 217, 100, 86, 110, 112, 44, 104, 251, 74, 91, 219, 245, 13, 233, 133, 96, 251, 32, 253, 254, 231, 51, 74, 87, 55, 182, 163, 195, 244, 211, 170, 75, 98, 179, 61, 11, 243, 90, 137, 3, 18, 52, 190, 108, 197, 197, 26, 215, 224, 65, 240, 49, 190, 239, 52, 20, 220, 214, 8, 40, 45, 88, 242, 196, 50, 115, 179, 250, 243, 152, 73, 77, 240, 152, 183, 220, 136, 52, 158, 206, 5, 128, 132, 33, 57, 50, 139, 163, 55, 53, 217, 82, 132, 171, 0, 14, 87, 59, 47, 96, 47, 187, 144, 226, 215, 208, 81, 151, 33, 92, 240, 171, 95, 145, 89, 2, 119, 23, 232, 18, 252, 193, 121, 140, 38, 217, 47, 123, 209, 252, 47, 116, 157, 121, 53, 233, 127, 55, 98, 55, 38, 15, 162, 180, 20, 45, 252, 80, 135, 105, 251, 119, 96, 125, 235, 157, 2, 156, 71, 152, 173, 70, 107, 71, 112, 126, 197, 212, 129, 17, 116, 40, 187, 0, 230, 148, 6, 67, 42, 234, 241, 12, 10, 18, 208, 167, 63, 18, 97, 108, 50, 27, 253, 232, 216, 146, 111, 10, 109, 207, 134, 235, 69, 253, 94, 218, 136, 44, 199, 182, 41, 19, 241, 18, 201, 222, 195, 78, 32, 31, 206, 126, 69, 65, 67, 76, 80, 25, 164, 48, 24, 214, 173, 110, 244, 218, 70, 86, 58, 165, 2, 41, 193, 72, 198, 61, 251, 220, 100, 117, 78, 113, 80, 80, 184, 66, 105, 2, 111, 33, 86, 137, 255, 51, 255, 219, 133, 244, 178, 202, 182, 8, 112, 37, 163, 129, 251, 117, 177, 15, 213, 120, 156, 159, 221, 178, 114, 153, 24, 103, 204, 222, 219, 23, 9, 228, 56, 232, 54, 69, 110, 126, 83, 232, 193, 129, 158, 203, 69, 173, 252, 189, 173, 2, 77, 80, 20, 209, 123, 245, 2, 151, 62, 139, 176, 193, 185, 94, 245, 8, 87, 38, 133, 156, 177, 233, 206, 95, 124, 206, 189, 25, 222, 167, 140, 227, 122, 182, 40, 252, 223, 157, 133, 9, 21, 162, 171, 77, 9, 33, 101, 111, 98, 137, 72, 124, 64, 71, 190, 141, 216, 9, 111, 184, 152, 136, 107, 56, 219, 64, 100, 223, 128, 79, 168, 108, 46, 158, 191, 239, 93, 231, 208, 46, 194, 210, 96, 251, 187, 51, 181, 228, 136, 186, 58, 162, 17, 176, 165, 28, 213, 50, 196, 56, 94, 28, 73, 57, 216, 42, 121, 95, 89, 112, 204, 232, 17, 233, 173, 197, 91, 77, 234, 195, 203, 187, 237, 59, 60, 86, 168, 211, 68, 203, 169, 181, 146, 133, 108, 221, 84, 74, 28, 129, 191, 52, 81, 62, 222, 142, 153, 181, 228, 154, 254, 45, 104, 10, 253, 156, 102, 2, 78, 141, 165, 37, 99, 129, 28, 141, 111, 47, 185, 119, 60, 55, 185, 142, 113, 54, 176, 189, 93, 136, 133, 217, 3, 105, 245, 97, 68, 117, 225, 100, 143, 214, 166, 126, 38, 189, 210, 145, 87, 40, 45, 226, 190, 119, 106, 38, 240, 96, 201, 58, 218, 54, 39, 125, 243, 44, 121, 100, 35, 3, 20, 253, 157, 133, 28, 112, 42, 59, 77, 27, 204, 182, 161, 96, 113, 229, 148, 125, 249, 77, 201, 123, 232, 46, 104, 33, 183, 157, 98, 99, 36, 49, 200, 220, 156, 72, 148, 106, 248, 25, 56, 143, 1, 84, 106, 133, 13, 94, 35, 241, 147, 97, 20, 73, 159, 136, 199, 101, 17, 154, 88, 36, 29, 14, 68, 244, 168, 142, 65, 25, 187, 221, 28, 196, 201, 126, 151, 143, 19, 225, 15, 152, 138, 93, 124, 148, 205, 53, 143, 127, 68, 225, 45, 168, 210, 141, 80, 163, 141, 14, 163, 152, 137, 148, 12, 250, 254, 120, 80, 185, 184, 249, 119, 139, 15, 89, 166, 224, 224, 253, 230, 226, 107, 184, 24, 166, 124, 193, 140, 171, 180, 93, 88, 63, 114, 102, 233, 2, 71, 34, 80, 121, 126, 155, 159, 152, 195, 251, 229, 143, 202, 29, 252, 26, 126, 61, 80, 164, 205, 98, 109, 197, 126, 251, 128, 95, 29, 4, 49, 202, 76, 33, 48, 46, 46, 10, 51, 203, 36, 250, 207, 14, 231, 222, 220, 88, 77, 127, 89, 209, 20, 57, 75, 76, 64, 189, 167, 191, 67, 173, 208, 6, 69, 174, 111, 137, 19, 136, 4, 52, 67, 228, 140, 18, 49, 117, 3, 252, 246, 150, 200, 168, 159, 138, 164, 186, 45, 220, 160, 213, 159, 67, 5, 140, 118, 196, 151, 136, 142, 58, 2, 20, 68, 64, 216, 67, 134, 209, 85, 206, 40, 15, 188, 165, 99, 25, 244, 174, 166, 74, 119, 78, 198, 103, 81, 34, 96, 59, 253, 64, 198, 77, 11, 24, 244, 161, 208, 155, 27, 194, 99, 106, 57, 189, 61, 188, 100, 19, 192, 182, 73, 72, 249, 20, 218, 211, 251, 70, 33, 87, 69, 233, 168, 232, 205, 135, 237, 137, 70, 60, 157, 240, 214, 21, 141, 43, 249, 136, 16, 183, 28, 242, 30, 2, 4, 138, 207, 164, 118, 58, 134, 232, 187, 249, 22, 98, 247, 98, 235, 86, 72, 15, 214, 183, 155, 149, 51, 214, 160, 28, 74, 43, 33, 213, 98, 21, 85, 105, 174, 35, 90, 116, 247, 226, 86, 23, 68, 66, 224, 70, 92, 227, 190, 148, 255, 91, 162, 108, 227, 181, 122, 56, 88, 175, 157, 37, 240, 61, 157, 27, 20, 177, 253, 114, 204, 59, 134, 56, 198, 61, 144, 126, 207, 180, 212, 58, 178, 19, 6, 183, 6, 190, 199, 46, 62, 175, 242, 160, 55, 3, 118, 242, 109, 227, 143, 83, 233, 203, 212, 32, 184, 98, 139, 42, 32, 119, 12, 229, 60, 3, 152, 94, 118, 161, 181, 26, 198, 75, 220, 133, 160, 205, 52, 170, 155, 187, 80, 113, 187, 239, 232, 36, 41, 180, 56, 83, 143, 97, 38, 237, 108, 31, 76, 194, 252, 245, 94, 14, 77, 195, 197, 218, 94, 69, 29, 172, 105, 175, 92, 29, 172, 222, 224, 115, 156, 198, 219, 188, 33, 118, 15, 144, 193, 3, 153, 80, 46, 125, 91, 66, 113, 176, 228, 76, 107, 172, 152, 124, 112, 149, 62, 50, 4, 12, 80, 228, 5, 178, 70, 145, 143, 139, 60, 223, 30, 158, 131, 146, 84, 242, 41, 209, 24, 66, 127, 245, 88, 216, 116, 135, 65, 160, 220, 159, 104, 223, 27, 220, 114, 196, 254, 162, 150, 52, 37, 89, 232, 239, 168, 128, 227, 41, 95, 108, 76, 134, 15, 248, 182, 58, 22, 4, 254, 94, 13, 166, 64, 178, 228, 2, 250, 13, 32, 81, 22, 103, 114, 211, 139, 57, 144, 54, 140, 160, 38, 28, 40, 25, 35, 116, 208, 237, 91, 89, 114, 183, 95, 101, 14, 250, 27, 75, 238, 22, 172, 148, 174, 49, 245, 102, 199, 224, 182, 147, 69, 202, 107, 223, 174, 95, 192, 253, 7, 198, 58, 116, 166, 89, 163, 43, 150, 204, 236, 3, 50, 121, 159, 123, 193, 147, 205, 231, 254, 215, 143, 247, 35, 247, 4, 62, 36, 193, 189, 195, 222, 187, 90, 72, 210, 113, 69, 202, 53, 106, 157, 94, 145, 170, 159, 239, 71, 215, 76, 246, 107, 107, 185, 253, 124, 126, 227, 27, 178, 251, 41, 190, 104, 60, 84, 5, 254, 151, 240, 253, 43, 43, 121, 74, 244, 53, 191, 69, 185, 61, 56, 208, 3, 42, 30, 101, 142, 15, 57, 166, 139, 75, 20, 74, 138, 136, 221, 17, 158, 122, 167, 43, 32, 151, 229, 153, 193, 251, 254, 7, 74, 17, 70, 5, 40, 203, 28, 212, 210, 200, 223, 60, 112, 102, 157, 8, 20, 116, 123, 56, 96, 224, 241, 136, 20, 213, 206, 16, 239, 244, 39, 30, 166, 29, 82, 103, 35, 130, 216, 238, 215, 190, 96, 0, 140, 230, 192, 128, 110, 63, 39, 81, 226, 98, 51, 48, 99, 150, 49, 113, 197, 198, 221, 37, 130, 23, 158, 74, 92, 118, 158, 77, 117, 215, 19, 90, 73, 7, 133, 93, 125, 68, 113, 72, 56, 123, 156, 204, 10, 234, 184, 189, 166, 4, 203, 0, 161, 119, 100, 187, 73, 138, 111, 236, 133, 153, 214, 97, 36, 234, 2, 4, 155, 1, 149, 47, 8, 64, 218, 180, 164, 14, 183, 137, 223, 42, 35, 143, 151, 254, 68, 153, 211, 160, 152, 26, 45, 181, 255, 112, 123], why = WrongTypeAsChar diff --git a/native/hyperrs-fs/tests/file_open_refusal.rs b/native/hyperrs-fs/tests/file_open_refusal.rs new file mode 100644 index 00000000..c7784a9d --- /dev/null +++ b/native/hyperrs-fs/tests/file_open_refusal.rs @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: MIT +//! Refusal contract of [`SafeFile::open`] and [`SafeDir::openat`]: a refused open is free of side +//! effects. +//! +//! The helper runs as root and opens caller-named paths, so validating a file only *after* the +//! open syscall is only safe if that open itself can neither hang nor change anything. Laws under +//! test: +//! - **A type mismatch never blocks.** Opening a FIFO as a regular file, block device or char +//! device returns [`ValidationError::WrongFileType`] promptly for every access mode, instead of +//! parking the (root, lock-holding) helper until some peer opens the other end. +//! - **A type mismatch is invisible to a peer.** A writer blocked on a FIFO is never released by a +//! refused open: no reader ever appears on the pipe. +//! - **A refused open never truncates.** For any file contents and any refusal reason (wrong type, +//! group/other-writable), an open with `O_TRUNC` that is refused leaves the bytes intact. +//! - **A refused open never creates.** An `O_CREAT` open refused for its type leaves no new entry. + +use assert_fs::prelude::*; +use assert_fs::TempDir; +use hyperrs_fs::dir::SafeDir; +use hyperrs_fs::file::{ + Any, IsBlockDevice, IsCharDevice, IsRegularFile, OpenFlags, OwnerOnlyWritable, SafeFile, + ValidationError, +}; +use hyperrs_fs::path::{IsAbsolute, SafePathBuf, StrictComponents}; +use nix::fcntl::{open, OFlag}; +use nix::sys::stat::Mode; +use nix::unistd::mkfifo; +use proptest::prelude::*; +use std::assert_matches; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +type Strict = SafePathBuf; + +const PROMPT: Duration = Duration::from_secs(3); + +fn strict(p: &Path) -> Strict { + p.to_path_buf() + .try_into() + .expect("strict-absolute temp path") +} + +fn fifo(tmp: &TempDir) -> PathBuf { + let p = tmp.child("pipe").path().to_path_buf(); + mkfifo(&p, Mode::from_bits_truncate(0o600)).unwrap(); + p +} + +/// Unblock any opener parked on `fifo` so a hung worker thread can finish. +fn release(fifo: &Path) { + let _ = open(fifo, OFlag::O_RDWR | OFlag::O_NONBLOCK, Mode::empty()); +} + +#[derive(Debug, Clone, Copy)] +enum Want { + Regular, + Block, + Char, +} + +fn open_as(want: Want, p: &Strict, flags: OpenFlags) -> Result<(), ValidationError> { + match want { + Want::Regular => SafeFile::::open(p, flags).map(drop), + Want::Block => SafeFile::::open(p, flags).map(drop), + Want::Char => SafeFile::::open(p, flags).map(drop), + } +} + +#[test] +fn a_fifo_opened_as_any_non_fifo_type_is_refused_promptly_for_every_access_mode() { + let mut hung = Vec::new(); + for want in [Want::Regular, Want::Block, Want::Char] { + for (label, flags) in [ + ("RDONLY", OpenFlags::RDONLY), + ("WRONLY", OpenFlags::WRONLY), + ("RDWR", OpenFlags::RDWR), + ] { + let tmp = TempDir::new().unwrap(); + let pipe = fifo(&tmp); + let target = strict(&pipe); + let (tx, rx) = mpsc::channel(); + let worker = thread::spawn(move || tx.send(open_as(want, &target, flags)).unwrap()); + + match rx.recv_timeout(PROMPT) { + Ok(got) => { + assert_matches!(got, Err(ValidationError::WrongFileType), "{want:?} {label}") + } + Err(_) => { + hung.push(format!("{want:?}/{label}")); + release(&pipe); + } + } + worker.join().unwrap(); + } + } + assert!(hung.is_empty(), "refusal blocked on a FIFO for: {hung:?}"); +} + +#[test] +fn a_refused_fifo_open_never_releases_a_blocked_peer_writer() { + let tmp = TempDir::new().unwrap(); + let pipe = fifo(&tmp); + let peer_path = pipe.clone(); + let (tx, rx) = mpsc::channel(); + let peer = thread::spawn(move || { + let opened = open(&peer_path, OFlag::O_WRONLY, Mode::empty()).is_ok(); + tx.send(opened).unwrap(); + }); + thread::sleep(Duration::from_millis(100)); + + let target = strict(&pipe); + let opener = thread::spawn(move || { + let _ = SafeFile::::open(&target, OpenFlags::RDONLY); + }); + + let released = rx.recv_timeout(Duration::from_millis(500)).is_ok(); + release(&pipe); + peer.join().unwrap(); + opener.join().unwrap(); + assert!( + !released, + "a SafeFile open that must be refused acted as the FIFO's reader" + ); +} + +#[derive(Debug, Clone, Copy)] +enum Refusal { + WrongTypeAsBlock, + WrongTypeAsChar, + GroupWritable, + OtherWritable, +} + +fn refusal() -> impl Strategy { + prop_oneof![ + Just(Refusal::WrongTypeAsBlock), + Just(Refusal::WrongTypeAsChar), + Just(Refusal::GroupWritable), + Just(Refusal::OtherWritable), + ] +} + +fn refused_trunc_open(why: Refusal, p: &Strict) -> Result<(), ValidationError> { + let flags = OpenFlags::WRONLY | OpenFlags::TRUNC; + match why { + Refusal::WrongTypeAsBlock => SafeFile::::open(p, flags).map(drop), + Refusal::WrongTypeAsChar => SafeFile::::open(p, flags).map(drop), + Refusal::GroupWritable | Refusal::OtherWritable => { + SafeFile::::open(p, flags).map(drop) + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + #[test] + fn a_refused_truncating_open_leaves_the_file_bytes_intact( + bytes in prop::collection::vec(any::(), 1..4096), + why in refusal(), + ) { + let tmp = TempDir::new().unwrap(); + let f = tmp.child("victim"); + f.write_binary(&bytes).unwrap(); + let mode = match why { + Refusal::GroupWritable => 0o620, + Refusal::OtherWritable => 0o602, + _ => 0o600, + }; + fs::set_permissions(f.path(), fs::Permissions::from_mode(mode)).unwrap(); + + let got = refused_trunc_open(why, &strict(f.path())); + + prop_assert!(got.is_err(), "{why:?} was accepted"); + prop_assert_eq!(fs::read(f.path()).unwrap(), bytes, "{:?} truncated the file", why); + } +} + +#[test] +fn a_create_refused_for_its_type_leaves_no_new_entry() { + let tmp = TempDir::new().unwrap(); + let dir = SafeDir::open(&strict(tmp.path()), OpenFlags::RDONLY).unwrap(); + + let via_open = SafeFile::::open( + &strict(&tmp.path().join("by-open")), + OpenFlags::WRONLY | OpenFlags::CREATE, + ); + let via_openat = dir.openat::( + Path::new("by-openat"), + OpenFlags::WRONLY | OpenFlags::CREATE_NEW, + Mode::from_bits_truncate(0o600), + ); + + assert_matches!(via_open, Err(_)); + assert_matches!(via_openat, Err(ValidationError::WrongFileType)); + let left: Vec<_> = fs::read_dir(tmp.path()) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert!(left.is_empty(), "refused creates left entries: {left:?}"); +} diff --git a/native/hyperrs-fs/tests/lock_exclusion_properties.rs b/native/hyperrs-fs/tests/lock_exclusion_properties.rs new file mode 100644 index 00000000..359cd6a8 --- /dev/null +++ b/native/hyperrs-fs/tests/lock_exclusion_properties.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MIT +//! Contract of [`FileLock`], the per-VM lock the suidhelper uses to serialize `vm_launch` against +//! `vm_teardown` (#135). +//! +//! Laws under test: +//! - **Mutual exclusion survives removal.** However many contenders race, and whichever holders +//! `remove()` the lock file on their way out (as `vm_teardown` does), at most one contender is +//! ever inside the critical section, and every contender eventually gets in. A waiter that +//! flocked an inode which was unlinked under it must not count as a holder. +//! - **Never follows a planted name.** A symlink at the lock name is refused, and the open never +//! creates the symlink's target. +//! - **The timeout bounds the call.** A lock name occupied by something that is not a lock file +//! ends in an error within the timeout, never a hang. + +use assert_fs::TempDir; +use hyperrs_fs::dir::SafeDir; +use hyperrs_fs::file::{OpenFlags, SafeFile}; +use hyperrs_fs::lock::{FileLock, LockError}; +use hyperrs_fs::path::{IsAbsolute, SafePathBuf, StrictComponent, StrictComponents}; +use nix::sys::stat::Mode; +use nix::unistd::mkfifo; +use proptest::prelude::*; +use std::assert_matches; +use std::os::unix::fs::symlink; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +const NAME_STR: &str = "vm-lock"; +const NAME: &StrictComponent = StrictComponent::from_static(NAME_STR); +const WAIT: Duration = Duration::from_secs(20); + +fn open(path: &Path) -> SafeDir { + let path: SafePathBuf = path.to_path_buf().try_into().unwrap(); + SafeFile::open(&path, OpenFlags::RDONLY).unwrap() +} + +#[derive(Debug, Clone)] +struct Contender { + rounds: Vec<(bool, u8)>, +} + +fn contender() -> impl Strategy { + prop::collection::vec((any::(), 0u8..8), 1..5).prop_map(|rounds| Contender { rounds }) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(24))] + + #[test] + fn at_most_one_holder_even_when_holders_remove_the_file( + contenders in prop::collection::vec(contender(), 2..7), + ) { + let tmp = TempDir::new().unwrap(); + let inside = AtomicUsize::new(0); + let peak = AtomicUsize::new(0); + let entered = AtomicUsize::new(0); + let failures = AtomicUsize::new(0); + let expected: usize = contenders.iter().map(|c| c.rounds.len()).sum(); + + thread::scope(|scope| { + for contender in &contenders { + let (inside, peak, entered, failures) = (&inside, &peak, &entered, &failures); + let base = tmp.path().to_path_buf(); + scope.spawn(move || { + let dir = open(&base); + for &(remove, hold_ms) in &contender.rounds { + let lock = match FileLock::acquire(&dir, NAME, WAIT) { + Ok(lock) => lock, + Err(_) => { + failures.fetch_add(1, Ordering::SeqCst); + continue; + } + }; + let now = inside.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(now, Ordering::SeqCst); + entered.fetch_add(1, Ordering::SeqCst); + thread::sleep(Duration::from_millis(u64::from(hold_ms) * 3)); + inside.fetch_sub(1, Ordering::SeqCst); + if remove { + lock.remove().unwrap(); + } else { + drop(lock); + } + } + }); + } + }); + + prop_assert_eq!(peak.load(Ordering::SeqCst), 1, "two contenders held the lock at once"); + prop_assert_eq!(failures.load(Ordering::SeqCst), 0); + prop_assert_eq!(entered.load(Ordering::SeqCst), expected); + } +} + +#[test] +fn a_symlink_at_the_lock_name_is_refused_and_its_target_never_created() { + let tmp = TempDir::new().unwrap(); + let target: PathBuf = tmp.path().join("victim"); + symlink(&target, tmp.path().join(NAME_STR)).unwrap(); + let dir = open(tmp.path()); + + let got = FileLock::acquire(&dir, NAME, Duration::from_millis(200)); + + assert_matches!(got.err(), Some(LockError::Open(_))); + assert!( + !target.exists(), + "acquire must not create through a symlink" + ); +} + +#[test] +fn a_directory_at_the_lock_name_is_refused_not_locked() { + let tmp = TempDir::new().unwrap(); + std::fs::create_dir(tmp.path().join(NAME_STR)).unwrap(); + let dir = open(tmp.path()); + + assert_matches!( + FileLock::acquire(&dir, NAME, Duration::from_millis(200)).err(), + Some(LockError::Open(_)) + ); +} + +#[test] +fn a_fifo_at_the_lock_name_errors_within_the_timeout_instead_of_hanging() { + let tmp = TempDir::new().unwrap(); + mkfifo(&tmp.path().join(NAME_STR), Mode::from_bits_truncate(0o600)).unwrap(); + let base = tmp.path().to_path_buf(); + let (sent, received) = mpsc::channel(); + thread::spawn(move || { + let dir = open(&base); + let _ = sent.send(FileLock::acquire(&dir, NAME, Duration::from_millis(200)).map(drop)); + }); + + let got = received.recv_timeout(Duration::from_secs(5)); + + assert_matches!(got, Ok(Err(_)), "acquire must not block past its timeout"); +}