#[cfg(target_os = "linux")]
mod linux {
pub(in crate::test_child) struct OwnedRawFd(pub(in crate::test_child) std::os::unix::io::RawFd);
impl Drop for OwnedRawFd {
fn drop(&mut self) {
unsafe {
libc::close(self.0);
}
}
}
pub(in crate::test_child) fn open_scratch_fd(dir: &std::path::Path) -> OwnedRawFd {
use std::os::unix::ffi::OsStrExt as _;
let path = std::ffi::CString::new(dir.as_os_str().as_bytes()).expect("scratch root path has no interior NUL");
let fd = unsafe { libc::open(path.as_ptr(), libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC) };
assert!(
fd >= 0,
"open scratch root as O_DIRECTORY: {}",
std::io::Error::last_os_error()
);
OwnedRawFd(fd)
}
pub(in crate::test_child) const FIXTURE_SCRATCH_FD_ENV: &str = "COSCA_FIXTURE_SCRATCH_FD";
}
#[cfg(target_os = "linux")]
pub(super) use linux::{open_scratch_fd, FIXTURE_SCRATCH_FD_ENV};
#[cfg(all(unix, not(target_os = "linux")))]
pub(super) const FIXTURE_SCRATCH_ROOT_ENV: &str = "COSCA_FIXTURE_SCRATCH_ROOT";
#[cfg(target_os = "linux")]
pub(crate) fn fixture_scratch_tempdir() -> tempfile::TempDir {
let fd: i32 = std::env::var(FIXTURE_SCRATCH_FD_ENV)
.expect("run_fixture sets the scratch fd")
.parse()
.expect("the scratch fd is a number");
tempfile::Builder::new()
.tempdir_in(format!("/proc/self/fd/{fd}"))
.expect("tempdir_in the fixture scratch root")
}
#[cfg(all(unix, not(target_os = "linux")))]
pub(crate) fn fixture_scratch_tempdir() -> tempfile::TempDir {
let root = std::env::var_os(FIXTURE_SCRATCH_ROOT_ENV).expect("run_fixture sets the scratch root");
tempfile::Builder::new()
.tempdir_in(root)
.expect("tempdir_in the fixture scratch root")
}
#[cfg(all(unix, not(target_os = "linux")))]
#[derive(Debug)]
pub(super) enum TraversalError {
Denied { path: std::path::PathBuf, errno: i32 },
Unchecked { path: std::path::PathBuf, cause: String },
}
#[cfg(all(unix, not(target_os = "linux")))]
impl std::fmt::Display for TraversalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Denied { path, errno } => write!(
f,
"{path:?} is not reachable by the identity a fixture drops to: {}",
std::io::Error::from_raw_os_error(*errno)
),
Self::Unchecked { path, cause } => write!(f, "could not check whether {path:?} is reachable: {cause}"),
}
}
}
#[cfg(all(unix, not(target_os = "linux")))]
pub(super) fn assert_dropped_identity_can_traverse_tmpdir() {
let tmpdir = std::env::temp_dir();
if let Err(e) = check_path_traversable_by(&tmpdir) {
panic!("{e}");
}
}
#[cfg(all(unix, not(target_os = "linux")))]
const CHILD_DROP_FAILED: i32 = 126;
#[cfg(all(unix, not(target_os = "linux")))]
pub(super) fn check_path_traversable_by(path: &std::path::Path) -> Result<(), TraversalError> {
use std::os::unix::ffi::OsStrExt as _;
let unchecked = |cause: String| TraversalError::Unchecked {
path: path.to_path_buf(),
cause,
};
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| unchecked("interior NUL".into()))?;
let guard = crate::child::spawn::spawn_lock();
let pid = unsafe { libc::fork() };
if pid == 0 {
unsafe {
if libc::geteuid() == 0 {
let uid = crate::test_privilege::UNPRIVILEGED;
if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(uid) != 0 || libc::setuid(uid) != 0 {
libc::_exit(CHILD_DROP_FAILED);
}
}
if libc::access(c_path.as_ptr(), libc::X_OK) == 0 {
libc::_exit(0);
}
let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(1);
libc::_exit(errno.clamp(1, CHILD_DROP_FAILED - 1));
}
}
let fork_error = (pid < 0).then(std::io::Error::last_os_error);
drop(guard);
if let Some(e) = fork_error {
return Err(unchecked(format!("fork: {e}")));
}
let mut status: libc::c_int = 0;
loop {
if unsafe { libc::waitpid(pid, &mut status, 0) } >= 0 {
break;
}
let e = std::io::Error::last_os_error();
if e.kind() != std::io::ErrorKind::Interrupted {
return Err(unchecked(format!("waitpid: {e}")));
}
}
if !libc::WIFEXITED(status) {
return Err(unchecked(format!(
"the check child did not exit (raw status {status:#x})"
)));
}
match libc::WEXITSTATUS(status) {
0 => Ok(()),
CHILD_DROP_FAILED => Err(unchecked("the check child could not drop to UNPRIVILEGED".into())),
errno => Err(TraversalError::Denied {
path: path.to_path_buf(),
errno,
}),
}
}
#[cfg(all(unix, not(target_os = "linux")))]
pub(super) fn copy_exe_to_traversable_scratch() -> (tempfile::TempDir, std::path::PathBuf) {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::Builder::new()
.tempdir_in("/tmp")
.expect("tempdir directly under /tmp for a traversable fixture-exe copy");
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755))
.expect("chmod the exe-copy scratch dir world-traversable");
let src = std::env::current_exe().expect("current_exe");
let dest = dir.path().join("fixture-exe");
std::fs::copy(&src, &dest).expect("copy the test binary into the traversable scratch dir");
std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))
.expect("chmod the exe copy world-readable+executable");
if let Err(e) = check_path_traversable_by(&dest) {
panic!("copied fixture exe: {e}");
}
(dir, dest)
}
#[cfg(all(test, unix, not(target_os = "linux")))]
#[path = "scratch_tests.rs"]
mod scratch_tests;