use std::io;
use std::os::fd::AsFd;
use crate::test_child::fixture_path;
use crate::test_child::namespaces as ns;
use crate::test_groups::{namespaces, Group};
use super::{
classify_ns_links, classify_status, collect_pids, parse_fdinfo_pid, pidfd_pid_in, proc_view_with, PidfdTarget,
ProcDir, ProcView, Verdict, ViewUnreadable, UNREADABLE_STATUS_REASON,
};
use crate::identity::{FakeKernel, HostKernel};
fn ns_pid(exists: io::Result<bool>) -> impl FnOnce() -> io::Result<bool> {
move || exists
}
fn unreachable_ns_pid() -> io::Result<bool> {
panic!("self/ns/pid must be consulted only when NSpid is absent")
}
#[skuld::test]
fn proc_view_matches_how_proc_numbers_our_own_init() {
let dir = ProcDir::open().expect("/proc opens");
let init = rustix::process::pidfd_open(
rustix::process::Pid::from_raw(1).expect("1 is nonzero"),
rustix::process::PidfdFlags::empty(),
)
.expect("pidfd_open(1)");
let numbered = pidfd_pid_in(&HostKernel, &dir, init.as_fd()).expect("read pid 1's pidfd fdinfo");
let view = proc_view_with(&HostKernel);
assert_eq!(
matches!(view, ProcView::Same(_)),
numbered == PidfdTarget::Pid(1),
"got {view:?}, while /proc numbers this namespace's init {numbered:?}"
);
}
#[skuld::test]
fn one_nspid_entry_is_same() {
let verdict = classify_status("Name:\tcosca\nNSpid:\t1234\nState:\tR\n", unreachable_ns_pid);
assert!(matches!(verdict, Verdict::Same), "got {verdict:?}");
}
#[skuld::test]
fn several_nspid_entries_are_diverged() {
let verdict = classify_status("NSpid:\t99\t5\t1\n", unreachable_ns_pid);
assert!(matches!(verdict, Verdict::Diverged), "got {verdict:?}");
}
#[skuld::test]
fn an_empty_nspid_line_is_unassessable() {
let verdict = classify_status("NSpid:\t\n", unreachable_ns_pid);
assert!(matches!(verdict, Verdict::Unassessable(_)), "got {verdict:?}");
}
#[skuld::test]
fn no_nspid_and_no_ns_pid_is_same() {
let verdict = classify_status("Name:\tcosca\nState:\tR\n", ns_pid(Ok(false)));
assert!(matches!(verdict, Verdict::Same), "got {verdict:?}");
}
#[skuld::test]
fn no_nspid_but_ns_pid_exists_needs_the_cross_check() {
let verdict = classify_status("Name:\tcosca\n", ns_pid(Ok(true)));
assert!(matches!(verdict, Verdict::NoNspid), "got {verdict:?}");
}
#[skuld::test]
fn no_nspid_and_an_unreadable_ns_pid_is_unassessable_with_the_cause() {
let Verdict::Unassessable(why) = classify_status(
"Name:\tcosca\n",
ns_pid(Err(io::Error::from_raw_os_error(libc::EACCES))),
) else {
panic!("expected Unassessable");
};
assert!(why.source.is_some(), "the OS error must be carried: {why}");
assert!(why.to_string().contains("could not be checked"), "{why}");
}
#[skuld::test]
fn fdinfo_pid_is_parsed() {
assert_eq!(
parse_fdinfo_pid("pos:\t0\nflags:\t02000000\nPid:\t4321\nNSpid:\t4321\n"),
Some(PidfdTarget::Pid(4321))
);
assert_eq!(parse_fdinfo_pid("Pid:\t0\n"), Some(PidfdTarget::Pid(0)));
assert_eq!(parse_fdinfo_pid("pos:\t0\n"), None);
assert_eq!(parse_fdinfo_pid("Pid:\tx\n"), None);
}
#[skuld::test]
fn fdinfo_pid_minus_one_is_reaped() {
assert_eq!(parse_fdinfo_pid("Pid:\t-1\n"), Some(PidfdTarget::Reaped));
}
#[skuld::test]
fn fdinfo_pid_other_negatives_are_unparseable() {
assert_eq!(parse_fdinfo_pid("Pid:\t-2\n"), None);
assert_eq!(parse_fdinfo_pid("Pid:\t-4294967296\n"), None);
}
#[skuld::test]
fn fdinfo_pid_beyond_u32_is_unparseable() {
assert_eq!(parse_fdinfo_pid("Pid:\t4294967296\n"), None);
assert_eq!(parse_fdinfo_pid("Pid:\t4294967295\n"), Some(PidfdTarget::Pid(u32::MAX)));
}
#[skuld::test]
fn fdinfo_pid_with_an_empty_value_is_unparseable() {
assert_eq!(parse_fdinfo_pid("Pid:\n"), None);
assert_eq!(parse_fdinfo_pid("Pid:\t\n"), None);
}
#[skuld::test]
fn fdinfo_pid_ignores_similarly_prefixed_keys() {
assert_eq!(parse_fdinfo_pid("NSpid:\t9\nPidx:\t8\nxPid:\t7\n"), None);
assert_eq!(
parse_fdinfo_pid("NSpid:\t9\nPidx:\t8\nPid:\t3\n"),
Some(PidfdTarget::Pid(3))
);
}
#[skuld::test]
fn proc_view_with_is_unassessable_for_a_status_that_is_not_utf8() {
let kernel = FakeKernel::over(&HostKernel).on_read("self/status", Ok(&[0xff]));
match proc_view_with(&kernel) {
ProcView::Unassessable(why) => assert!(why.reason.contains(UNREADABLE_STATUS_REASON), "{why}"),
other => panic!("got {other:?}"),
}
}
#[skuld::test]
fn the_proc_dir_reads_a_file_beneath_it() {
let status = ProcDir::open()
.expect("/proc opens")
.read_to_string("thread-self/status")
.expect("read");
assert!(status.contains("Name:"), "{status}");
}
#[skuld::test]
fn the_proc_dir_refuses_a_path_that_climbs_out_of_it() {
let dir = ProcDir::open().expect("/proc opens");
let err = dir.read("../etc/passwd").expect_err("must not leave /proc");
assert_eq!(err.raw_os_error(), Some(libc::EXDEV), "{err}");
}
#[skuld::test]
fn the_proc_dir_refuses_an_absolute_path() {
let dir = ProcDir::open().expect("/proc opens");
let err = dir.read("/etc/passwd").expect_err("must not leave /proc");
assert_eq!(err.raw_os_error(), Some(libc::EXDEV), "{err}");
}
#[skuld::test]
fn the_proc_dir_refuses_a_magic_link() {
let dir = ProcDir::open().expect("/proc opens");
let err = dir.read("self/exe").expect_err("a magic link must not be followed");
assert_eq!(err.raw_os_error(), Some(libc::ELOOP), "{err}");
}
const NO_NSPID: &str = "Name:\tcosca\nState:\tR (running)\n";
fn link(target: &str) -> io::Result<Vec<u8>> {
Ok(target.as_bytes().to_vec())
}
#[skuld::test]
fn a_procfs_whose_pid_1_shares_this_threads_namespace_is_same() {
let verdict = classify_ns_links(link("pid:[4026531836]"), || link("pid:[4026531836]"));
assert!(matches!(verdict, Verdict::Same), "got {verdict:?}");
}
#[skuld::test]
fn a_procfs_whose_pid_1_is_in_another_namespace_is_diverged() {
let verdict = classify_ns_links(link("pid:[4026532831]"), || link("pid:[4026532830]"));
assert!(matches!(verdict, Verdict::Diverged), "got {verdict:?}");
}
#[skuld::test]
fn an_unreadable_pid_1_link_is_unassessable_with_the_cause() {
let Verdict::Unassessable(why) = classify_ns_links(link("pid:[4026531836]"), || {
Err(io::Error::from_raw_os_error(libc::EACCES))
}) else {
panic!("expected Unassessable");
};
assert!(why.reason.contains("1/ns/pid"), "{why}");
assert_eq!(why.source.and_then(|e| e.raw_os_error()), Some(libc::EACCES));
}
#[skuld::test]
fn an_unreadable_own_link_is_unassessable_without_reading_pid_1() {
let Verdict::Unassessable(why) = classify_ns_links(Err(io::Error::from_raw_os_error(libc::ENOENT)), || {
panic!("pid 1's link must not be read once the own link failed")
}) else {
panic!("expected Unassessable");
};
assert!(why.reason.contains("thread-self/ns/pid"), "{why}");
}
#[skuld::test]
fn a_link_that_names_no_pid_namespace_is_unassessable() {
for (own, init) in [("", ""), ("net:[1]", "net:[1]"), ("pid:[1]", "pid:[1")] {
let verdict = classify_ns_links(link(own), || link(init));
assert!(
matches!(verdict, Verdict::Unassessable(_)),
"{own:?} {init:?}: got {verdict:?}"
);
}
}
#[skuld::test]
fn this_threads_own_namespace_link_reads_through_the_proc_dir() {
let dir = ProcDir::open().expect("/proc opens");
let own = dir.read_link("thread-self/ns/pid").expect("read own link");
assert!(own.starts_with(b"pid:["), "{:?}", String::from_utf8_lossy(&own));
}
#[skuld::test]
fn the_fdinfo_of_a_reaped_targets_pidfd_is_reaped() {
let (mut child, pidfd) = spawn_exited_child_with_pidfd();
child.wait().expect("reap the child");
let dir = ProcDir::open().expect("/proc opens");
let got = pidfd_pid_in(&HostKernel, &dir, pidfd.as_fd());
assert!(matches!(got, Ok(PidfdTarget::Reaped)), "got {got:?}");
}
#[skuld::test]
fn the_fdinfo_of_an_unreaped_targets_pidfd_names_its_pid() {
let (mut child, pidfd) = spawn_exited_child_with_pidfd();
let dir = ProcDir::open().expect("/proc opens");
let got = pidfd_pid_in(&HostKernel, &dir, pidfd.as_fd());
let pid = child.id();
child.wait().expect("reap the child");
assert!(
matches!(got, Ok(PidfdTarget::Pid(p)) if p == pid),
"got {got:?}, pid {pid}"
);
}
#[skuld::test]
fn pidfd_pid_in_reads_thread_self_fdinfo_and_names_a_missing_pid_line() {
use std::os::fd::AsRawFd as _;
let (mut child, pidfd) = spawn_exited_child_with_pidfd();
let dir = ProcDir::open().expect("/proc opens");
let path = format!("thread-self/fdinfo/{}", pidfd.as_raw_fd());
let stated_pid = child.id() + 1;
let stated = FakeKernel::over(&HostKernel).on_read(&path, Ok(format!("Pid:\t{stated_pid}\n").as_bytes()));
let got = pidfd_pid_in(&stated, &dir, pidfd.as_fd());
let no_pid = FakeKernel::over(&HostKernel).on_read(&path, Ok(b"pos:\t0\n"));
let err = pidfd_pid_in(&no_pid, &dir, pidfd.as_fd()).expect_err("no Pid line");
child.wait().expect("reap the child");
assert!(matches!(got, Ok(PidfdTarget::Pid(p)) if p == stated_pid), "got {got:?}");
assert!(err.reason.contains("no parseable Pid line"), "{err}");
}
fn spawn_exited_child_with_pidfd() -> (std::process::Child, rustix::fd::OwnedFd) {
let child = crate::test_spawn::spawn(&mut std::process::Command::new("true")).expect("spawn true");
let pid = rustix::process::Pid::from_raw(child.id() as i32).expect("child pid is nonzero");
let pidfd = rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open");
(child, pidfd)
}
#[skuld::test]
fn namespaces_the_fdinfo_is_read_through_the_calling_threads_fd_table(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_fdinfo_after_unshare_files));
}
#[skuld::test]
fn fixture_fdinfo_after_unshare_files() {
if !ns::is_child() {
return;
}
let dir = ProcDir::open().expect("/proc opens");
let own = rustix::process::Pid::from_raw(std::process::id() as i32).expect("own pid");
let got = std::thread::scope(|s| {
s.spawn(|| {
unsafe { rustix::thread::unshare_unsafe(rustix::thread::UnshareFlags::FILES) }.expect("unshare(FILES)");
let pidfd = rustix::process::pidfd_open(own, rustix::process::PidfdFlags::empty()).expect("pidfd_open");
pidfd_pid_in(&HostKernel, &dir, pidfd.as_fd())
})
.join()
.expect("thread")
});
assert!(
matches!(got, Ok(PidfdTarget::Pid(p)) if p == std::process::id()),
"got {got:?}"
);
}
#[skuld::test]
fn namespaces_no_nspid_under_an_outer_procfs_numbering_this_thread_alike_is_diverged(
#[fixture(namespaces)] _group: &Group,
) {
ns::run(fixture_path!(fixture_coinciding_tid_driver));
}
#[skuld::test]
fn fixture_coinciding_tid_driver() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_coinciding_tid_outer_init));
}
#[skuld::test]
fn fixture_coinciding_tid_outer_init() {
if !ns::is_child_in_new_pid_ns() {
return;
}
ns::enter_private_mount_ns();
ns::mount_proc(std::path::Path::new("/proc"));
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_coinciding_tid_inner));
}
#[skuld::test]
fn fixture_coinciding_tid_inner() {
if !ns::is_child_in_new_pid_ns() {
return;
}
let last_in_proc = std::thread::spawn(ns::tid_in_proc).join().expect("probe thread");
ns::set_last_pid(last_in_proc);
let view = std::thread::spawn(|| {
let tid = rustix::thread::gettid().as_raw_nonzero().get() as u32;
assert_eq!(
ns::tid_in_proc(),
tid,
"precondition: /proc must number this thread as gettid() does"
);
proc_view_with(&FakeKernel::over(&HostKernel).on_read("self/status", Ok(NO_NSPID.as_bytes())))
})
.join()
.expect("verdict thread");
assert!(matches!(view, ProcView::Diverged), "got {view:?}");
}
#[skuld::test]
fn namespaces_no_nspid_under_this_namespaces_own_procfs_is_same(#[fixture(namespaces)] _group: &Group) {
ns::run(fixture_path!(fixture_own_procfs_driver));
}
#[skuld::test]
fn fixture_own_procfs_driver() {
if !ns::is_child() {
return;
}
ns::enter_new_pid_ns_for_children();
ns::run(fixture_path!(fixture_own_procfs_init));
}
#[skuld::test]
fn fixture_own_procfs_init() {
if !ns::is_child_in_new_pid_ns() {
return;
}
ns::enter_private_mount_ns();
ns::mount_proc(std::path::Path::new("/proc"));
let view = proc_view_with(&FakeKernel::over(&HostKernel).on_read("self/status", Ok(NO_NSPID.as_bytes())));
assert!(matches!(view, ProcView::Same(_)), "got {view:?}");
ns::run_dropping_to_nobody(fixture_path!(fixture_own_procfs_unprivileged));
}
#[skuld::test]
fn fixture_own_procfs_unprivileged() {
if !ns::is_child() {
return;
}
ns::drop_to_nobody();
rustix::process::set_dumpable_behavior(rustix::process::DumpableBehavior::NotDumpable).expect("PR_SET_DUMPABLE 0");
match proc_view_with(&FakeKernel::over(&HostKernel).on_read("self/status", Ok(NO_NSPID.as_bytes()))) {
ProcView::Unassessable(why) => {
assert!(why.reason.contains("1/ns/pid"), "{why}");
assert_eq!(
why.source.as_ref().and_then(io::Error::raw_os_error),
Some(libc::EACCES),
"{why}"
);
}
other => panic!("an unreadable pid 1 namespace link must be Unassessable, got {other:?}"),
}
}
#[skuld::test]
fn pids_lists_the_numeric_entries_including_this_process() {
let pids = ProcDir::open().expect("/proc opens").pids().expect("list");
assert!(pids.contains(&std::process::id()), "{pids:?}");
}
fn names(list: &[&[u8]]) -> Vec<io::Result<Vec<u8>>> {
list.iter().map(|n| Ok(n.to_vec())).collect()
}
#[skuld::test]
fn collect_pids_excludes_names_that_are_not_pids() {
let listed: &[&[u8]] = &[
b"1",
b"self",
b"thread-self",
b"net",
b"sys",
b"",
b"+5",
b"-5",
b"1a",
b" 7",
b"\xff\xfe",
b"4194304",
];
assert_eq!(collect_pids(names(listed)).expect("list"), vec![1, 4_194_304]);
}
#[skuld::test]
fn collect_pids_is_an_error_for_an_all_digit_name_that_overflows() {
for name in [&b"4294967296"[..], b"99999999999999999999"] {
let err = collect_pids(names(&[b"1", name])).expect_err("a corrupt listing is an error");
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{err}");
assert!(err.to_string().contains(std::str::from_utf8(name).unwrap()), "{err}");
}
}
#[skuld::test]
fn collect_pids_propagates_a_listing_error() {
let items = vec![Ok(b"1".to_vec()), Err(io::Error::from_raw_os_error(libc::EIO))];
let err = collect_pids(items).expect_err("listing error");
assert_eq!(err.raw_os_error(), Some(libc::EIO));
}
#[skuld::test]
fn into_dir_names_why_a_view_is_not_usable() {
let same = ProcView::Same(ProcDir::open().expect("/proc opens"));
assert!(same.into_dir().is_ok());
let diverged = ProcView::Diverged.into_dir().expect_err("diverged");
assert!(diverged.reason.contains("outer pid namespace"), "{diverged}");
let why = ViewUnreadable::new("boom", None);
let unassessable = ProcView::Unassessable(why).into_dir().expect_err("unassessable");
assert_eq!(unassessable.reason, "boom");
}