use std::os::fd::OwnedFd;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use rustix::io::Errno;
use rustix::process::Pid;
use super::open_tests::LiveNonLeaderTid;
use crate::error::Error;
use crate::identity::{
proc_view_with, FakeKernel, HostKernel, Kernel, ProcDir, ProcOpenFailure, ProcView, ReadFailure,
UNREADABLE_STATUS_REASON,
};
use crate::test_child::fixture_path;
use crate::test_child::namespaces as ns;
use crate::test_groups::{namespaces, Group};
#[skuld::test]
fn namespaces_a_status_mounted_over_below_proc_keeps_live_foreign_kills_working(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_status_mounted_over));
}
#[skuld::test]
fn fixture_status_mounted_over() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let mut child = crate::test_child::blocker();
let id = crate::identity::ticks_id(child.id());
let own_id = crate::identity::ticks_id(std::process::id());
let scratch = tempfile::tempdir().expect("tempdir");
let status = scratch.path().join("status");
std::fs::write(&status, "Name:\tcosca\nState:\tR (running)\n").expect("write the fake status");
ns::bind_over(&status, &PathBuf::from(format!("/proc/{}/status", std::process::id())));
let process = crate::os_process::open(id)
.expect("a live foreign open must not depend on the /proc view")
.expect("the live child opens");
crate::os_process::kill(&*process).expect("a live foreign kill must not depend on the /proc view");
let status = child.wait().expect("reap the killed child");
assert!(!status.success(), "the child must have been killed, got {status:?}");
let own = super::open_verified_error_with(&HostKernel, own_id);
assert!(matches!(own, Ok(Some(_))), "got {own:?}");
match proc_view_with(&HostKernel) {
ProcView::Unassessable(why) => {
assert!(why.reason.contains(UNREADABLE_STATUS_REASON), "{why}");
assert_eq!(
why.source.as_ref().and_then(|e| e.raw_os_error()),
Some(libc::EXDEV),
"{why}"
);
}
other => panic!("a status mounted over below /proc must not be read, got {other:?}"),
}
}
#[skuld::test]
fn namespaces_an_outer_procfs_is_diverged_and_unassessable(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_pid_ns_outer));
}
#[skuld::test]
fn fixture_pid_ns_outer() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_pid_ns_inner));
}
#[skuld::test]
fn fixture_pid_ns_inner() {
if !ns::is_child_in_new_pid_ns() {
return;
}
assert_eq!(
std::process::id(),
1,
"the fixture must be pid 1 of its own pid namespace"
);
let view = proc_view_with(&HostKernel);
assert!(matches!(view, ProcView::Diverged), "got {view:?}");
let stat = std::fs::read("/proc/self/stat").expect("read own stat");
let ticks = crate::identity::stat_parse::parse_starttime_jiffies(&stat).expect("own starttime parses");
let own = crate::identity::ProcessId::from_parts_for_test(1, crate::identity::Key::Ticks(ticks));
match super::open_verified_error_with(&HostKernel, own) {
Err(Error::Unassessable { detail, .. }) => {
assert!(detail.contains("outer pid namespace"), "{detail}");
assert!(
!detail.contains("numbers the target 1 "),
"the outer procfs must number this process differently from its own pid 1: {detail}"
);
}
other => panic!("the success path under an outer procfs must be Unassessable, got {other:?}"),
}
}
fn fake_stat(pid: u32) -> String {
let zeros = ["0"; 18].join(" ");
format!("{pid} (fake) S {zeros} 999999999999 0 0\n")
}
fn overmount_proc_with_a_foreign_stat(pid: u32) {
ns::mount_tmpfs(std::path::Path::new("/proc"));
let dir = PathBuf::from(format!("/proc/{pid}"));
std::fs::create_dir(&dir).expect("mkdir the fake pid dir");
std::fs::write(dir.join("stat"), fake_stat(pid)).expect("write the fake stat");
}
fn overmount_stat_with_a_foreign_file(pid: u32) {
let scratch = tempfile::tempdir().expect("tempdir");
let file = scratch.path().join("stat");
std::fs::write(&file, fake_stat(pid)).expect("write the fake stat");
ns::bind_over(&file, &PathBuf::from(format!("/proc/{pid}/stat")));
std::mem::forget(scratch);
}
fn recording_hook(mount: impl FnOnce() + Send + 'static) -> (Arc<AtomicBool>, impl FnOnce() + Send + 'static) {
let fired = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&fired);
(fired, move || {
mount();
flag.store(true, Ordering::SeqCst);
})
}
struct PauseKernel<'a> {
inner: &'a dyn Kernel,
pid: u32,
pause: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}
impl<'a> PauseKernel<'a> {
fn new(inner: &'a dyn Kernel, pid: u32, pause: impl FnOnce() + Send + 'static) -> Self {
PauseKernel {
inner,
pid,
pause: Mutex::new(Some(Box::new(pause))),
}
}
}
impl Kernel for PauseKernel<'_> {
fn pidfd_open(&self, target: Pid, flags: rustix::process::PidfdFlags) -> Result<OwnedFd, Errno> {
self.inner.pidfd_open(target, flags)
}
fn pidfs_ino(&self, fd: std::os::fd::BorrowedFd<'_>) -> Result<Option<u64>, Errno> {
self.inner.pidfs_ino(fd)
}
fn open_proc(&self) -> Result<ProcDir, ProcOpenFailure> {
self.inner.open_proc()
}
fn read(&self, dir: &ProcDir, path: &str) -> Result<Vec<u8>, ReadFailure> {
if path == format!("{}/stat", self.pid) {
let pause = self.pause.lock().expect("no panic holds the pause").take();
if let Some(pause) = pause {
pause();
}
}
self.inner.read(dir, path)
}
fn read_link(&self, dir: &ProcDir, path: &str) -> Result<Vec<u8>, ReadFailure> {
self.inner.read_link(dir, path)
}
fn pids(&self, dir: &ProcDir) -> Result<Vec<u32>, ReadFailure> {
self.inner.pids(dir)
}
fn tids(&self, dir: &ProcDir, pid: u32) -> Result<Vec<u32>, ReadFailure> {
self.inner.tids(dir, pid)
}
fn signal_probe(&self, target: Pid) -> Result<(), Errno> {
self.inner.signal_probe(target)
}
fn peek(&self, pidfd: std::os::fd::BorrowedFd<'_>) -> Result<Option<crate::identity::Record>, Errno> {
self.inner.peek(pidfd)
}
fn consume(&self, pidfd: std::os::fd::BorrowedFd<'_>) -> Result<Option<crate::identity::Record>, Errno> {
self.inner.consume(pidfd)
}
}
fn assert_by_path_stat_is_fake(pid: u32) {
let by_path = std::fs::read_to_string(format!("/proc/{pid}/stat")).expect("read /proc/{pid}/stat by path");
assert!(
by_path.contains("(fake)"),
"the overmount must be visible by path, else the fixture proves nothing: {by_path:?}"
);
}
fn assert_unassessable_existence(result: Result<Option<rustix::fd::OwnedFd>, Error>) {
match result {
Err(Error::Unassessable { detail, .. }) => assert!(detail.contains("existence query"), "{detail}"),
other => panic!("a stat that cannot be read through the checked dirfd must be Unassessable, got {other:?}"),
}
}
#[skuld::test]
fn namespaces_the_success_path_reads_through_the_checked_proc_dirfd(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_overmount_success));
}
#[skuld::test]
fn fixture_overmount_success() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let pid = std::process::id();
let (fired, hook) = recording_hook(move || overmount_proc_with_a_foreign_stat(pid));
let result = super::open_verified_error_with(
&PauseKernel::new(&HostKernel, pid, hook),
crate::identity::ticks_id(std::process::id()),
);
assert!(
fired.load(Ordering::SeqCst),
"the pause before the stat read must have run"
);
assert_by_path_stat_is_fake(pid);
assert!(matches!(result, Ok(Some(_))), "got {result:?}");
}
#[skuld::test]
fn namespaces_the_einval_arm_reads_through_the_checked_proc_dirfd(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_overmount_einval));
}
#[skuld::test]
fn fixture_overmount_einval() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let worker = LiveNonLeaderTid::spawn();
let tid = worker.id.pid();
let (fired, hook) = recording_hook(move || overmount_proc_with_a_foreign_stat(tid));
let refused = FakeKernel::over(&HostKernel).on_pidfd_open(tid, Err(Errno::NOENT));
let result = super::open_verified_error_with(&PauseKernel::new(&refused, tid, hook), worker.id);
assert!(
fired.load(Ordering::SeqCst),
"the pause before the stat read must have run"
);
assert_by_path_stat_is_fake(tid);
match result {
Err(Error::NotThreadGroupLeader { pid, .. }) => assert_eq!(pid, tid),
other => panic!("a live non-leader tid must stay NotThreadGroupLeader, got {other:?}"),
}
}
#[skuld::test]
fn namespaces_a_stat_mounted_over_below_proc_is_not_read_on_the_success_path(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_stat_overmount_success));
}
#[skuld::test]
fn fixture_stat_overmount_success() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let pid = std::process::id();
let (fired, hook) = recording_hook(move || overmount_stat_with_a_foreign_file(pid));
let result = super::open_verified_error_with(
&PauseKernel::new(&HostKernel, pid, hook),
crate::identity::ticks_id(std::process::id()),
);
assert!(
fired.load(Ordering::SeqCst),
"the pause before the stat read must have run"
);
assert_by_path_stat_is_fake(pid);
assert_unassessable_existence(result);
}
#[skuld::test]
fn namespaces_a_stat_mounted_over_below_proc_is_not_read_on_the_einval_arm(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_stat_overmount_einval));
}
#[skuld::test]
fn fixture_stat_overmount_einval() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let worker = LiveNonLeaderTid::spawn();
let tid = worker.id.pid();
let (fired, hook) = recording_hook(move || overmount_stat_with_a_foreign_file(tid));
let refused = FakeKernel::over(&HostKernel).on_pidfd_open(tid, Err(Errno::NOENT));
let result = super::open_verified_error_with(&PauseKernel::new(&refused, tid, hook), worker.id);
assert!(
fired.load(Ordering::SeqCst),
"the pause before the stat read must have run"
);
assert_by_path_stat_is_fake(tid);
assert_unassessable_existence(result);
}
#[skuld::test]
fn namespaces_a_tmpfs_at_proc_is_not_procfs(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_tmpfs_at_proc));
}
#[skuld::test]
fn fixture_tmpfs_at_proc() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
let id = crate::identity::ticks_id(std::process::id());
ns::mount_tmpfs(std::path::Path::new("/proc"));
let opened = ProcDir::open();
assert!(
matches!(&opened, Err(ProcOpenFailure::NotProcfs { .. })),
"got {opened:?}"
);
match proc_view_with(&HostKernel) {
ProcView::Unassessable(why) => assert!(why.reason.contains("not procfs"), "{why}"),
other => panic!("a tmpfs at /proc must be Unassessable, got {other:?}"),
}
match super::open_verified_error_with(&HostKernel, id) {
Err(Error::Unassessable { detail, .. }) => assert!(detail.contains("not procfs"), "{detail}"),
other => panic!("a tmpfs at /proc must be Unassessable, got {other:?}"),
}
}
#[skuld::test]
fn namespaces_a_procfs_subtree_bound_over_proc_is_not_the_procfs_root(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_subtree_at_proc));
}
#[skuld::test]
fn fixture_subtree_at_proc() {
if !ns::is_child() {
return;
}
ns::enter_private_mount_ns();
ns::bind_over(std::path::Path::new("/proc/sys"), std::path::Path::new("/proc"));
let opened = ProcDir::open();
assert!(
matches!(&opened, Err(ProcOpenFailure::NotRoot { .. })),
"got {opened:?}"
);
}