artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
use std::process::Stdio;

use super::*;

// Darwin killpg excludes zombies and returns EPERM for a zombie-only group.
// Other Unix kernels already accept this signal; their cleanup tests cover it.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn killing_a_zombie_only_group_succeeds_without_reaping_it_first() {
    let command = fixture_exit();
    let (gate, spawning) = spawn_gated(command).unwrap();
    let gate = gate.identify().await.unwrap();
    let pid = gate.pid();
    assert!(!process_group_exited(pid).unwrap());
    gate.admit().unwrap();
    let mut child = spawning.await.unwrap().unwrap();
    tokio::task::spawn_blocking(move || wait_for_zombie(pid))
        .await
        .unwrap();
    assert!(process_group_exited(pid).unwrap());
    // Exercise the real EPERM path, not an injected error or a delay.
    assert_eq!(
        signal_group(native_pid(pid).unwrap(), Signal::KILL).unwrap_err(),
        Errno::PERM
    );
    child.kill().unwrap();
    assert!(child.wait().await.unwrap().success());
    assert!(process_group_exited(pid).unwrap());
    child.kill().unwrap();
}

#[tokio::test]
async fn a_cleaned_group_no_longer_owns_a_signal_target() {
    let command = fixture_exit();
    let (gate, spawning) = spawn_gated(command).unwrap();
    let gate = gate.identify().await.unwrap();
    let pid = gate.pid();
    gate.admit().unwrap();
    let mut child = spawning.await.unwrap().unwrap();
    assert!(child.wait_leader().await.unwrap().success());
    // Observing and polling the leader's exit must not surrender its native identity.
    assert!(child.try_wait_leader().unwrap().unwrap().success());
    assert!(process_start_time(pid).is_ok());
    GROUP_SIGNALS.with(|count| count.set(0));
    child.cleanup().await.unwrap();
    let initial = GROUP_SIGNALS.with(std::cell::Cell::get);
    assert!(process_start_time(pid).is_err());
    child.interrupt().unwrap();
    child.cleanup().await.unwrap();
    drop(child);
    assert_eq!(
        GROUP_SIGNALS.with(std::cell::Cell::get),
        initial,
        "a cleaned group must never be signalled again"
    );
}

#[tokio::test]
async fn disconnect_before_identity_publication_cancels_and_reaps_native_child() {
    let mut command = fixture_exit();
    let mut checkpoint = BeforeIdentity::hold(&mut command.command);
    let (gate, spawning) = spawn_gated(command).unwrap();
    let pid = checkpoint.pid().await;
    // The native child exists, but it cannot publish its PID to the gate until
    // released. Its PID write now meets a disconnected socket and SIGPIPE.
    drop(gate);
    checkpoint.release().await;
    let error = spawning
        .await
        .expect("pre-admission cancellation must not panic")
        .err()
        .expect("an unadmitted native child must not be returned");
    assert_eq!(error.raw_os_error(), Some(libc::ECANCELED));
    assert!(
        process_start_time(pid).is_err(),
        "the native child must be reaped"
    );
}

#[tokio::test]
async fn native_death_before_identity_publication_closes_pid_observation_and_reaps() {
    let mut command = fixture_exit();
    let mut checkpoint = BeforeIdentity::hold(&mut command.command);
    let (gate, spawning) = spawn_gated(command).unwrap();
    let pid = checkpoint.pid().await;
    kill_owned(pid);
    // The parent's captured child endpoint must be closed after native spawn
    // returns, or PID observation would never learn that this child died.
    let error = gate
        .identify()
        .await
        .err()
        .expect("the gate must observe the early exit");
    assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
    let error = spawning
        .await
        .expect("pre-admission death must not panic")
        .err()
        .expect("an unadmitted native child must not be returned");
    assert_eq!(error.raw_os_error(), Some(libc::ECANCELED));
    assert!(
        process_start_time(pid).is_err(),
        "the native child must be reaped"
    );
}

/// Hold a child immediately before its identity is published. Closing this owner on
/// assertion unwind releases pre_exec with cancellation, so spawning still reaps it.
pub struct BeforeIdentity(tokio::net::UnixStream);

impl BeforeIdentity {
    pub fn hold(command: &mut tokio::process::Command) -> Self {
        use std::{io, os::fd::AsRawFd, os::unix::net::UnixStream};

        let (parent, child) = UnixStream::pair().unwrap();
        parent.set_nonblocking(true).unwrap();
        let parent_fd = parent.as_raw_fd();
        // SAFETY: the forked child uses only async-signal-safe syscalls and stack
        // data. Both endpoints stay alive until spawn; closing the inherited parent
        // endpoint ensures dropping the fixture parent releases the child with EOF.
        unsafe {
            command.pre_exec(move || {
                libc::close(parent_fd);
                let fd = child.as_raw_fd();
                let pid = (libc::getpid() as u32).to_ne_bytes();
                let mut offset = 0;
                while offset < pid.len() {
                    let written =
                        libc::write(fd, pid[offset..].as_ptr().cast(), pid.len() - offset);
                    if written < 0 {
                        let error = io::Error::last_os_error();
                        if error.raw_os_error() == Some(libc::EINTR) {
                            continue;
                        }
                        return Err(error);
                    }
                    if written == 0 {
                        return Err(io::Error::from_raw_os_error(libc::EPIPE));
                    }
                    offset += written as usize;
                }
                let mut release = 0_u8;
                loop {
                    match libc::read(fd, (&mut release as *mut u8).cast(), 1) {
                        1 => return Ok(()),
                        -1 => {
                            let error = io::Error::last_os_error();
                            if error.raw_os_error() != Some(libc::EINTR) {
                                return Err(error);
                            }
                        }
                        _ => return Err(io::Error::from_raw_os_error(libc::ECANCELED)),
                    }
                }
            });
        }
        Self(tokio::net::UnixStream::from_std(parent).unwrap())
    }

    pub async fn pid(&mut self) -> u32 {
        use tokio::io::AsyncReadExt;
        let mut pid = [0; size_of::<u32>()];
        self.0.read_exact(&mut pid).await.unwrap();
        u32::from_ne_bytes(pid)
    }

    pub async fn release(&mut self) {
        use tokio::io::AsyncWriteExt;
        self.0.write_all(&[1]).await.unwrap();
    }
}

#[test]
fn exit_successfully() {}

fn fixture_exit() -> ResolvedCommand {
    let mut command = super::super::resolved_command(
        &std::env::current_exe().unwrap(),
        [
            "--exact",
            "platform::process::unix::tests::exit_successfully",
        ],
    )
    .unwrap();
    command
        .env_clear()
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    command
}

fn kill_owned(pid: u32) {
    // SAFETY: the test owns this exact PID and has not released its gate.
    unsafe { libc::kill(pid as i32, libc::SIGKILL) };
}

// Only the Darwin test requires a zombie that has not yet been reaped.
#[cfg(target_os = "macos")]
fn wait_for_zombie(pid: u32) {
    let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::uninit();
    // SAFETY: waitid writes siginfo_t for our child, and WNOWAIT keeps it unreaped.
    let result = unsafe {
        libc::waitid(
            libc::P_PID,
            pid,
            info.as_mut_ptr(),
            libc::WEXITED | libc::WNOWAIT,
        )
    };
    assert_eq!(result, 0, "{}", std::io::Error::last_os_error());
}

#[tokio::test]
async fn ordinary_gated_spawn_uses_the_selected_program_in_a_shared_installation() {
    use crate::platform::{process::resolve_with, tests::shared_directory};
    use std::{fs, os::unix::fs::PermissionsExt, path::Path};

    let fixture = tempfile::tempdir().unwrap();
    let selected = fixture.path().join("selected");
    shared_directory(&selected);
    let path = selected.join("fixture-program");
    script_at(&path, "#!/bin/sh\nprintf selected > receipt\n");
    // A cooperative installation may allow its owning group to update the executable.
    const GROUP_WRITABLE_EXECUTABLE: u32 = 0o775;
    fs::set_permissions(&path, fs::Permissions::from_mode(GROUP_WRITABLE_EXECUTABLE)).unwrap();
    let decoy = fixture.path().join("decoy");
    fs::create_dir(&decoy).unwrap();
    script_at(
        &decoy.join("fixture-program"),
        "#!/bin/sh\nprintf decoy > receipt\n",
    );
    let program = resolve_with(Path::new("fixture-program"), fixture.path(), |name| {
        (name == "PATH").then(|| selected.clone().into_os_string())
    })
    .unwrap();
    let mut command = program.command(std::iter::empty::<&str>()).unwrap();
    command
        .current_dir(fixture.path())
        .env_clear()
        .env("PATH", &decoy);
    let (gate, spawning) = spawn_gated(command).unwrap();
    let gate = gate.identify().await.unwrap();
    let receipt = fixture.path().join("receipt");
    assert!(!receipt.exists());
    gate.admit().unwrap();
    let mut child = spawning.await.unwrap().unwrap();
    assert!(child.wait().await.unwrap().success());
    child.cleanup().await.unwrap();
    assert_eq!(fs::read_to_string(receipt).unwrap(), "selected");
}

fn script_at(path: &std::path::Path, content: &str) {
    use std::{fs, os::unix::fs::PermissionsExt};

    fs::write(path, content).unwrap();
    // Only the fixture owner may write or execute this script.
    const OWNER_EXECUTABLE: u32 = 0o700;
    fs::set_permissions(path, fs::Permissions::from_mode(OWNER_EXECUTABLE)).unwrap();
}

#[tokio::test]
async fn native_env_script_keeps_its_path_arguments_cwd_and_environment() {
    use crate::platform::process::resolve_with;
    use std::{fs, path::Path};

    let fixture = tempfile::tempdir().unwrap();
    let script = fixture.path().join("fixture script");
    script_at(
        &script,
        "#!/usr/bin/env sh\nprintf '%s\\n' \"$0\" \"$1\" \"$FIXTURE_VALUE\" > receipt\n",
    );
    let cwd = fixture.path().join("cwd");
    fs::create_dir(&cwd).unwrap();
    let search = Path::new("/bin").as_os_str().to_owned();
    let program =
        resolve_with(&script, &cwd, |key| (key == "PATH").then(|| search.clone())).unwrap();
    let native = fs::canonicalize(&script).unwrap();
    let mut command = program.command(["literal argument"]).unwrap();
    command
        .current_dir(&cwd)
        .env_clear()
        .env("PATH", search)
        .env("FIXTURE_VALUE", "literal environment");
    let (gate, spawning) = spawn_gated(command).unwrap();
    let gate = gate.identify().await.unwrap();
    assert!(!cwd.join("receipt").exists());
    gate.admit().unwrap();
    let mut child = spawning.await.unwrap().unwrap();
    assert!(child.wait().await.unwrap().success());
    child.cleanup().await.unwrap();
    assert_eq!(
        fs::read_to_string(cwd.join("receipt")).unwrap(),
        format!(
            "{}\nliteral argument\nliteral environment\n",
            native.display()
        )
    );
}