artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
//! Launch from verified native handles without a second executable lookup.
//!
//! To check an executable by digest or request consent, inspect an [`Executable`] and
//! give that same snapshot to [`Launch`]. A digest by itself does not verify a pathname.

use std::{
    collections::BTreeMap,
    ffi::OsString,
    fs::File,
    future::Future,
    io::{self, Read, Seek, SeekFrom},
    path::{Path, PathBuf},
};

use super::process::{self, Child, ChildIdentity, ResolvedCommand};
use sha2::{Digest, Sha256};

#[cfg(not(target_os = "linux"))]
use {super::private::PrivateTempDir, std::sync::Arc};

#[cfg(unix)]
pub(super) mod unix;
#[cfg(windows)]
pub(super) mod windows;
#[cfg(unix)]
use unix as os;
#[cfg(windows)]
use windows as os;

pub use os::{open_executable, open_verified_directory, same_directory, same_file};

// Bound chunks for hashing and copying executable images.
const COPY_BUFFER: usize = 64 * 1024;

type DigestBytes = [u8; 32];

fn digest(reader: &mut impl Read) -> io::Result<DigestBytes> {
    let mut digest = Sha256::new();
    let mut buffer = [0; COPY_BUFFER];
    loop {
        let read = reader.read(&mut buffer)?;
        if read == 0 {
            return Ok(digest.finalize().into());
        }
        digest.update(&buffer[..read]);
    }
}

fn file_digest(file: &mut File) -> io::Result<DigestBytes> {
    file.seek(SeekFrom::Start(0))?;
    let digest = digest(file)?;
    file.seek(SeekFrom::Start(0))?;
    Ok(digest)
}

/// Snapshot of a selected executable's handle and byte digest. Only [`Launch`] can use
/// this snapshot to spawn; ordinary commands do not carry it.
pub struct Executable {
    path: PathBuf,
    file: File,
    digest: DigestBytes,
}

impl Executable {
    /// Snapshot an executable at the caller's resolved absolute path.
    pub fn open(path: &Path) -> io::Result<Self> {
        require_absolute(path)?;
        Self::snapshot(path, open_executable(path)?)
    }

    /// Snapshot an already inspected handle only if it is the regular file currently
    /// named by the resolved absolute path. Hash the inspected handle, not the reopened
    /// file used for the identity check.
    pub fn from_file(path: &Path, file: File) -> io::Result<Self> {
        require_absolute(path)?;
        if !file.metadata()?.is_file() || !same_file(&file, path)? {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "executable handle does not match the resolved file",
            ));
        }
        Self::snapshot(path, file)
    }

    fn snapshot(path: &Path, mut file: File) -> io::Result<Self> {
        let digest = file_digest(&mut file)?;
        Ok(Self {
            path: path.to_owned(),
            file,
            digest,
        })
    }

    /// The resolved name at selection, not a claim about what the path names now.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// The snapshot's SHA-256 in lowercase hex, for comparison or consent. Pass this
    /// snapshot, not its path, to the launch after checking the digest.
    pub fn sha256(&self) -> String {
        self.digest
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect()
    }
}

fn require_absolute(path: &Path) -> io::Result<()> {
    if !path.is_absolute() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "executable requires a resolved absolute path",
        ));
    }
    Ok(())
}

fn verify_image(image: &mut File, expected: DigestBytes) -> io::Result<()> {
    if file_digest(image)? != expected {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "verified executable changed before spawn",
        ));
    }
    Ok(())
}

/// Bind a selected file and working directory to native admission.
/// For an [`Executable`] snapshot, the launch also checks the captured digest.
pub struct Launch<'a> {
    pub executable: Executable,
    pub cwd: &'a Path,
    pub directory: File,
    pub args: &'a [OsString],
    pub environment: &'a BTreeMap<OsString, OsString>,
}

/// Owns the staged image or pinned script paths until the child exits.
#[derive(Clone, Default)]
pub(super) struct Lease {
    #[cfg(not(target_os = "linux"))]
    kind: Option<Arc<LeaseKind>>,
}

#[cfg(not(target_os = "linux"))]
enum LeaseKind {
    #[cfg(not(target_os = "linux"))]
    Staged {
        #[cfg(windows)]
        _guards: Vec<File>,
        _directory: PrivateTempDir,
    },
    #[cfg(windows)]
    Pinned { _files: Vec<File> },
}

impl Lease {
    #[cfg(not(target_os = "linux"))]
    fn staged(directory: PrivateTempDir, #[cfg(windows)] guards: Vec<File>) -> Self {
        Self {
            kind: Some(Arc::new(LeaseKind::Staged {
                #[cfg(windows)]
                _guards: guards,
                _directory: directory,
            })),
        }
    }

    #[cfg(windows)]
    fn pinned(files: Vec<File>) -> Self {
        Self {
            kind: Some(Arc::new(LeaseKind::Pinned { _files: files })),
        }
    }

    #[cfg(not(target_os = "linux"))]
    pub(super) fn has_resources(&self) -> bool {
        self.kind.is_some()
    }
}

struct Prepared {
    command: ResolvedCommand,
    lease: Lease,
}

/// Identity of the inert child created by foundation and the native image it will run.
/// This record cannot change the launch or admit the child.
pub struct Admission {
    pub identity: ChildIdentity,
    pub image: PathBuf,
}

/// Whether to show the native console when admitting a verified child.
#[derive(Clone, Copy, Default)]
pub enum Console {
    #[default]
    Inherit,
    Hidden,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ImageKind {
    Executable,
    Native,
}

impl Launch<'_> {
    /// Spawn the verified image under native supervision, with its lease attached to the child.
    pub async fn spawn(self) -> io::Result<Child> {
        let (child, ()) = self
            .spawn_registered(Console::Inherit, async |_| Ok(()))
            .await?;
        Ok(child)
    }

    /// Spawn the verified image, letting the caller observe or veto admission before any
    /// program code runs. The callback cannot change the executable or supply a child.
    pub async fn spawn_registered<R, F>(
        self,
        console: Console,
        before_admit: impl FnOnce(Admission) -> F,
    ) -> io::Result<(Child, R)>
    where
        F: Future<Output = io::Result<R>>,
    {
        self.spawn_prepared(ImageKind::Executable, console, before_admit)
            .await
    }

    /// Admit only the verified native image, not a shell or batch script. The callback
    /// can only observe or veto admission of that image.
    pub async fn spawn_native_registered<R, F>(
        self,
        console: Console,
        before_admit: impl FnOnce(Admission) -> F,
    ) -> io::Result<(Child, R)>
    where
        F: Future<Output = io::Result<R>>,
    {
        self.spawn_prepared(ImageKind::Native, console, before_admit)
            .await
    }

    async fn spawn_prepared<R, F>(
        self,
        kind: ImageKind,
        console: Console,
        before_admit: impl FnOnce(Admission) -> F,
    ) -> io::Result<(Child, R)>
    where
        F: Future<Output = io::Result<R>>,
    {
        if !self.cwd.is_absolute() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "verified launch requires an absolute working directory",
            ));
        }
        let Launch {
            executable,
            cwd,
            directory,
            args,
            environment,
        } = self;
        let cwd = cwd.to_owned();
        let args = args.to_vec();
        let environment = environment.clone();
        let Prepared { command, lease } = tokio::task::spawn_blocking(move || {
            os::prepare(
                Launch {
                    executable,
                    cwd: &cwd,
                    directory,
                    args: &args,
                    environment: &environment,
                },
                kind,
            )
        })
        .await
        .map_err(|error| {
            if error.is_panic() {
                std::panic::resume_unwind(error.into_panic());
            }
            io::Error::other(error)
        })??;
        let image = PathBuf::from(command.as_std().get_program());
        let (gate, spawning) = process::spawn_for_admission(command, console)?;
        let admitted = async {
            let gate = gate.identify().await?;
            let admission = Admission {
                identity: process::child_identity(gate.pid())?,
                image,
            };
            let registration = before_admit(admission).await?;
            gate.admit()?;
            Ok::<_, io::Error>(registration)
        }
        .await;
        let registration = match admitted {
            Ok(registration) => registration,
            Err(error) => {
                // The gate was dropped without admission. Reap the inert child before
                // returning the veto or native error, keeping the image pinned until then.
                let _ = spawning.await;
                return Err(error);
            }
        };
        let mut child = spawning.await.map_err(io::Error::other)??;
        child.retain_image(lease);
        Ok((child, registration))
    }
}

#[cfg(test)]
mod tests;