artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
use super::*;
use crate::platform::files::canonicalize;

const PAYLOAD: &str = "NATIVE_LAUNCH_PAYLOAD";
const CHILD_ARGS: [&str; 4] = [
    "--ignored",
    "--exact",
    "platform::executable::tests::payload",
    "--nocapture",
];

#[test]
#[ignore = "launched only by the verified executable fixture"]
fn payload() {
    let value = std::env::var_os(PAYLOAD).expect("fixture environment");
    assert_eq!(value, "explicit-env");
    assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_none());
    assert_eq!(std::fs::read("identity").unwrap(), b"verified cwd");
    std::fs::write("executed", b"verified child executed").unwrap();
    println!("verified child executed");
}

struct Fixture {
    _work: tempfile::TempDir,
    cwd: std::path::PathBuf,
    args: Vec<OsString>,
    environment: BTreeMap<OsString, OsString>,
}

impl Fixture {
    fn new() -> Self {
        let work = tempfile::tempdir().unwrap();
        let cwd = canonicalize(work.path()).unwrap();
        std::fs::write(cwd.join("identity"), b"verified cwd").unwrap();
        Self {
            _work: work,
            cwd,
            args: CHILD_ARGS.map(OsString::from).into(),
            environment: BTreeMap::from([(PAYLOAD.into(), "explicit-env".into())]),
        }
    }

    fn test_binary(&self) -> std::path::PathBuf {
        canonicalize(&std::env::current_exe().unwrap()).unwrap()
    }

    fn native_image(&self) -> std::path::PathBuf {
        let source = self.test_binary();
        let path = self.cwd.join(source.file_name().unwrap());
        std::fs::copy(source, &path).unwrap();
        path
    }

    fn copy_program(&self, name: &str) -> std::path::PathBuf {
        let path = self.cwd.join(name);
        std::fs::copy(self.test_binary(), &path).unwrap();
        path
    }

    fn script(&self, name: &str, contents: &str) -> std::path::PathBuf {
        let path = self.cwd.join(name);
        std::fs::write(&path, contents).unwrap();
        path
    }

    fn launch<'a>(&'a self, executable: Executable, args: &'a [OsString]) -> Launch<'a> {
        Launch {
            executable,
            cwd: &self.cwd,
            directory: open_verified_directory(&self.cwd).unwrap(),
            args,
            environment: &self.environment,
        }
    }
}

async fn assert_child(mut child: Child, marker: &str) {
    use tokio::io::AsyncReadExt;
    let mut stdout = child.stdout().take().unwrap();
    let mut stderr = child.stderr().take().unwrap();
    let mut output = String::new();
    let mut diagnostic = String::new();
    let (out, err) = tokio::join!(
        stdout.read_to_string(&mut output),
        stderr.read_to_string(&mut diagnostic)
    );
    out.unwrap();
    err.unwrap();
    assert!(
        child.wait().await.unwrap().success(),
        "{output}\n{diagnostic}"
    );
    assert!(output.contains(marker), "{output}\n{diagnostic}");
    child.cleanup().await.unwrap();
}

#[tokio::test]
async fn launch_uses_the_verified_bytes_cwd_and_environment() {
    let fixture = Fixture::new();
    let path = fixture.native_image();
    let child = fixture
        .launch(Executable::open(&path).unwrap(), &fixture.args)
        .spawn()
        .await
        .unwrap();
    assert_child(child, "verified child executed").await;
}

#[tokio::test]
async fn native_binding_does_not_admit_a_script() {
    let fixture = Fixture::new();
    let path = if cfg!(windows) {
        fixture.script("probe.cmd", "@exit /b 0\r\n")
    } else {
        fixture.script("probe", "#!/bin/sh\nexit 0\n")
    };
    let executable = Executable::open(&path).unwrap();
    let result = fixture
        .launch(executable, &[])
        .spawn_native_registered::<(), _>(Console::Inherit, async |_| {
            panic!("a script reached native admission")
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::InvalidData));
}

#[test]
fn a_snapshot_rejects_an_unrelated_file_even_with_the_same_contents() {
    let fixture = Fixture::new();
    let first = fixture.script("selected", "same bytes");
    let second = fixture.script("unrelated", "same bytes");
    let result = Executable::from_file(&first, File::open(&second).unwrap());
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::InvalidInput));
}

#[tokio::test]
async fn modified_bytes_never_reach_spawn() {
    use std::io::Write;

    let fixture = Fixture::new();
    let path = fixture.native_image();
    // Allow a second writable open on Windows so the test exercises digest rejection
    // even when the snapshot came from a caller's less restrictive handle.
    let executable = Executable::from_file(&path, File::open(&path).unwrap()).unwrap();
    std::fs::OpenOptions::new()
        .append(true)
        .open(&path)
        .unwrap()
        .write_all(b"different bytes")
        .unwrap();
    let result = fixture
        .launch(executable, &[])
        .spawn_native_registered::<(), _>(Console::Inherit, async |_| {
            panic!("a changed executable reached spawn")
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::PermissionDenied));
}

// Only Windows opens a batch script inside a separate command interpreter after spawning.
#[cfg(windows)]
#[tokio::test]
async fn verified_batch_path_is_pinned_for_the_launch_lease() {
    let fixture = Fixture::new();
    fixture.script("sibling.txt", "verified script\r\n");
    let path = fixture.script("verified.cmd", "@type \"%~dp0sibling.txt\"\r\n");
    use tokio::io::AsyncReadExt;

    let mut child = fixture
        .launch(Executable::open(&path).unwrap(), &[])
        .spawn()
        .await
        .unwrap();
    assert!(std::fs::remove_file(&path).is_err());
    let mut output = String::new();
    child
        .stdout()
        .take()
        .unwrap()
        .read_to_string(&mut output)
        .await
        .unwrap();
    assert!(child.wait().await.unwrap().success());
    assert!(output.contains("verified script"));
    drop(child);
    std::fs::remove_file(&path).unwrap();
}

// Windows may append .exe to a supplied application path. The verified native image
// must still run under an extensionless name rather than opening its .exe neighbor.
#[cfg(windows)]
#[tokio::test]
async fn extensionless_launch_uses_only_the_verified_image() {
    let fixture = Fixture::new();
    let path = fixture.copy_program("verified");
    fixture.script("verified.exe", "not the program");
    let child = fixture
        .launch(Executable::open(&path).unwrap(), &fixture.args)
        .spawn()
        .await
        .unwrap();
    assert_child(child, "verified child executed").await;
}

// Windows uses an image section that keeps the original name without allowing writes.
#[cfg(windows)]
#[tokio::test]
async fn a_verified_program_cannot_be_changed_or_renamed_before_admission() {
    let fixture = Fixture::new();
    let path = fixture.copy_program("verified.exe");
    let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
    assert!(Executable::open(&path).is_err());
    drop(writer);

    let executable = Executable::open(&path).unwrap();
    let assert_pinned = || {
        assert!(std::fs::OpenOptions::new().write(true).open(&path).is_err());
        assert!(std::fs::rename(&path, fixture.cwd.join("replacement.exe")).is_err());
    };
    assert_pinned();
    let marker = fixture.cwd.join("executed");
    let (child, ()) = fixture
        .launch(executable, &fixture.args)
        .spawn_registered(Console::Inherit, async |admission| {
            assert_eq!(canonicalize(&admission.image)?, canonicalize(&path)?);
            assert_pinned();
            assert!(!marker.exists());
            Ok(())
        })
        .await
        .unwrap();
    assert_child(child, "verified child executed").await;
    assert!(marker.is_file());
}

// Unix stages the executable bytes rather than preventing changes to the original file.
#[cfg(unix)]
#[tokio::test]
async fn editing_the_source_after_staging_cannot_change_the_launched_image() {
    let fixture = Fixture::new();
    let path = fixture.copy_program("verified");
    let (child, ()) = fixture
        .launch(Executable::open(&path).unwrap(), &fixture.args)
        .spawn_registered(Console::Inherit, async |_| {
            std::fs::write(&path, b"changed bytes").unwrap();
            Ok(())
        })
        .await
        .unwrap();
    assert_child(child, "verified child executed").await;
}

// POSIX kernels have a shebang interpreter boundary rather than Windows batch dispatch.
#[cfg(unix)]
#[tokio::test]
async fn a_verified_script_passes_its_arguments_to_the_protected_interpreter() {
    let fixture = Fixture::new();
    let script = fixture.script(
        "script",
        "#!/bin/sh\nprintf 'script argument: %s\\n' \"$1\"\n",
    );
    let child = fixture
        .launch(
            Executable::open(&script).unwrap(),
            &["literal value".into()],
        )
        .spawn()
        .await
        .unwrap();
    assert_child(child, "script argument: literal value").await;
}

// A Unix shebang may name an executable other OS users can replace; never admit it.
#[cfg(unix)]
#[tokio::test]
async fn a_verified_script_cannot_delegate_to_a_shared_interpreter_directory() {
    use crate::platform::tests::shared_directory;
    let fixture = Fixture::new();
    let shared = fixture.cwd.join("shared");
    shared_directory(&shared);
    let interpreter = shared.join("interpreter");
    std::fs::copy(fixture.test_binary(), &interpreter).unwrap();
    let script = fixture.script("script", &format!("#!{}\n", interpreter.display()));
    let result = fixture
        .launch(Executable::open(&script).unwrap(), &[])
        .spawn_registered::<(), _>(Console::Inherit, async |_| {
            panic!("a shared interpreter reached spawn")
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::PermissionDenied));
}

// Darwin stages to a private native pathname instead of Linux's sealed file descriptor.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn launch_rejects_a_changed_staged_path() {
    let fixture = Fixture::new();
    let path = fixture.test_binary();
    let result = fixture
        .launch(Executable::open(&path).unwrap(), &fixture.args)
        .spawn_registered(Console::Inherit, async |admission| {
            let staged = admission.image;
            std::fs::remove_file(&staged).unwrap();
            std::fs::copy(&path, &staged).unwrap();
            Ok(())
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::PermissionDenied));
}

// Linux accepts some class-mismatched ELF headers via its native loader; the
// launch contract must reject ambiguity before handing the image to that loader.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn launch_rejects_an_elf_with_a_non_native_class() {
    use std::os::unix::fs::FileExt;
    let fixture = Fixture::new();
    let path = fixture.copy_program("wrong-abi");
    std::fs::OpenOptions::new()
        .write(true)
        .open(&path)
        .unwrap()
        .write_all_at(&[1], 4) // EI_CLASS is byte 4; 1 denotes ELF32.
        .unwrap();
    let result = fixture
        .launch(Executable::open(&path).unwrap(), &fixture.args)
        .spawn_registered::<(), _>(Console::Inherit, async |_| {
            panic!("a non-native ELF class reached spawn")
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::InvalidData));
}

// Linux procfs descriptors are process-relative, even in an absolute pathname.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn a_script_cannot_delegate_its_interpreter_to_a_procfs_descriptor() {
    use std::os::fd::AsRawFd;
    let fixture = Fixture::new();
    let interpreter = open_executable(&fixture.test_binary()).unwrap();
    let script = fixture.script(
        "script",
        &format!("#!/proc/self/fd/{}\n", interpreter.as_raw_fd()),
    );
    let result = fixture
        .launch(Executable::open(&script).unwrap(), &[])
        .spawn_registered::<(), _>(Console::Inherit, async |_| {
            panic!("an interpreter from procfs reached spawn")
        })
        .await;
    assert!(result.is_err());
}

#[tokio::test]
async fn verified_launch_refuses_a_mismatched_working_directory_handle() {
    let fixture = Fixture::new();
    let path = fixture.native_image();
    let different = tempfile::tempdir().unwrap();
    let mut launch = fixture.launch(Executable::open(&path).unwrap(), &fixture.args);
    launch.directory = open_verified_directory(different.path()).unwrap();
    let result = launch
        .spawn_registered::<(), _>(Console::Inherit, async |_| {
            panic!("a mismatched working directory reached admission")
        })
        .await;
    assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::PermissionDenied));
}