artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    fs::{self, File, OpenOptions, Permissions},
    io,
    os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
    path::Path,
};

#[cfg(not(target_os = "macos"))]
use std::{fs::DirBuilder, os::unix::fs::DirBuilderExt};

#[cfg(target_os = "macos")]
use super::macos;

/// Owner-only directory mode (rwx------): only their owner may list or enter them.
const PRIVATE_DIR_MODE: u32 = 0o700;

/// Owner-only file mode (rw-------): only their owner may read or write them.
const PRIVATE_FILE_MODE: u32 = 0o600;

/// How a private directory and file are described in messages.
pub const PRIVATE_DIRECTORY: &str = "owner-only (mode 0700)";
pub const PRIVATE_FILE: &str = "readable by their owner only (mode 0600)";

/// The access bits of a mode, excluding the file type and special mode bits.
const PERMISSION_BITS: u32 = 0o777;
/// Include special bits when restoring an existing directory to exactly 0700.
const DIRECTORY_MODE_BITS: u32 = 0o7777;

/// Create one directory as exactly 0700, whatever the umask.
pub fn create_private_dir(path: &Path) -> io::Result<()> {
    #[cfg(target_os = "macos")]
    macos::create_dir(path, PRIVATE_DIR_MODE as libc::mode_t)?;
    #[cfg(target_os = "linux")]
    DirBuilder::new().mode(PRIVATE_DIR_MODE).create(path)?;
    restrict_directory(path)
}

/// Open without following a final link before checking the owner or changing permissions.
pub(super) fn restrict_directory(path: &Path) -> io::Result<()> {
    #[cfg(target_os = "macos")]
    let directory = macos::open_directory_for_acl(path)?;
    #[cfg(target_os = "linux")]
    let directory = {
        let (path, _) = super::super::files::terminal_component(path);
        open_directory_for_mode(rustix::fs::CWD, path)?
    };
    restrict_directory_handle(&directory)
}

pub(super) fn restrict_directory_handle(directory: &File) -> io::Result<()> {
    let metadata = directory.metadata()?;
    if metadata.uid() != rustix::process::geteuid().as_raw() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "private directory must belong to the current user",
        ));
    }
    #[cfg(target_os = "macos")]
    if !macos::has_no_grants(directory)? {
        macos::clear_acl(directory)?;
    }
    if metadata.mode() & DIRECTORY_MODE_BITS != PRIVATE_DIR_MODE {
        #[cfg(target_os = "macos")]
        directory.set_permissions(Permissions::from_mode(PRIVATE_DIR_MODE))?;
        #[cfg(target_os = "linux")]
        set_directory_mode(directory)?;
    }
    Ok(())
}

#[cfg(target_os = "linux")]
pub(super) fn open_directory_for_mode(
    parent: impl std::os::fd::AsFd,
    path: &Path,
) -> io::Result<File> {
    use rustix::fs::{Mode, OFlags, openat};

    let flags = OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
    match openat(&parent, path, OFlags::RDONLY | flags, Mode::empty()) {
        Ok(directory) => Ok(directory.into()),
        // A directory with no read bit still needs to be repairable by its owner.
        Err(rustix::io::Errno::ACCESS) => {
            Ok(openat(parent, path, OFlags::PATH | flags, Mode::empty())?.into())
        }
        Err(error) => Err(error.into()),
    }
}

#[cfg(target_os = "linux")]
fn set_directory_mode(directory: &File) -> io::Result<()> {
    use rustix::fs::{AtFlags, Mode, OFlags, PROC_SUPER_MAGIC, chmodat, fchmod, fstatfs, open};
    use std::os::fd::AsRawFd;

    match fchmod(directory, Mode::RWXU) {
        Ok(()) => return Ok(()),
        Err(rustix::io::Errno::BADF) => {}
        Err(error) => return Err(error.into()),
    }
    // fchmod rejects O_PATH handles. A procfs descriptor link reaches the same
    // inode without looking up the original pathname again, including on old kernels.
    let fds = open(
        "/proc/self/fd",
        OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    if fstatfs(&fds)?.f_type != PROC_SUPER_MAGIC {
        return Err(io::ErrorKind::Unsupported.into());
    }
    chmodat(
        fds,
        directory.as_raw_fd().to_string(),
        Mode::RWXU,
        AtFlags::empty(),
    )?;
    Ok(())
}

/// Whether a directory is owned by the current user and has owner-only access.
pub fn is_private_dir(path: &Path) -> io::Result<bool> {
    let (path, _) = super::super::files::terminal_component(path);
    let metadata = fs::symlink_metadata(path)?;
    if !metadata.is_dir()
        || metadata.mode() & DIRECTORY_MODE_BITS != PRIVATE_DIR_MODE
        || metadata.uid() != rustix::process::geteuid().as_raw()
    {
        return Ok(false);
    }
    #[cfg(target_os = "macos")]
    return is_owner_only(&macos::open_directory_for_acl(path)?);
    #[cfg(not(target_os = "macos"))]
    Ok(true)
}

/// Whether an open file is a regular, single-link 0600 file.
pub fn is_private_file(file: &File) -> io::Result<bool> {
    let metadata = file.metadata()?;
    if !metadata.is_file()
        || metadata.mode() & PERMISSION_BITS != PRIVATE_FILE_MODE
        || metadata.nlink() != 1
    {
        return Ok(false);
    }
    owner_only(file, &metadata)
}

/// Options for a file already protected by its directory. New files can inherit an ACL
/// on macOS; use `create_private_file` for an explicit owner-only create in a shared path.
pub fn private_options() -> OpenOptions {
    let mut options = OpenOptions::new();
    options.mode(PRIVATE_FILE_MODE);
    options
}

/// Create a new owner-only read/write file, including in a shared directory.
pub fn create_private_file(path: &Path) -> io::Result<File> {
    #[cfg(target_os = "macos")]
    let file = macos::create_file(path, PRIVATE_FILE_MODE as libc::mode_t)?;
    #[cfg(not(target_os = "macos"))]
    let file = private_options()
        .read(true)
        .write(true)
        .create_new(true)
        .open(path)?;
    // Creation starts with at most owner access. Restore any owner bits masked by umask.
    restrict_file(&file)?;
    Ok(file)
}

/// Make an open file 0600 and remove access independently granted by ACLs.
pub fn restrict_file(file: &File) -> io::Result<()> {
    #[cfg(target_os = "macos")]
    macos::clear_acl(file)?;
    file.set_permissions(Permissions::from_mode(PRIVATE_FILE_MODE))
}

const GROUP_OTHER_BITS: u32 = 0o077;

/// Persist a directory's entries, such as a file just renamed into it.
pub fn sync_dir(path: &Path) -> io::Result<()> {
    super::super::files::open_directory(path).and_then(|directory| directory.sync_all())
}

/// A file's identity on its volume: its device and inode.
pub fn file_identity(file: &File) -> io::Result<super::FileIdentity> {
    let metadata = file.metadata()?;
    Ok(super::FileIdentity {
        volume: metadata.dev(),
        index: metadata.ino().into(),
    })
}

/// Stable effective UID, not an environment-provided username.
pub fn user_identity() -> io::Result<String> {
    Ok(rustix::process::geteuid().as_raw().to_string())
}

fn owner_only_mode(metadata: &fs::Metadata, user: u32) -> bool {
    metadata.mode() & GROUP_OTHER_BITS == 0 && metadata.uid() == user
}

fn owner_only(_file: &File, metadata: &fs::Metadata) -> io::Result<bool> {
    if !owner_only_mode(metadata, rustix::process::geteuid().as_raw()) {
        return Ok(false);
    }
    #[cfg(target_os = "macos")]
    return macos::has_no_grants(_file);
    #[cfg(not(target_os = "macos"))]
    Ok(true)
}

/// Whether an open file or directory belongs to the current user and grants nothing to its
/// group or others.
pub fn is_owner_only(file: &File) -> io::Result<bool> {
    owner_only(file, &file.metadata()?)
}

/// No Windows-style pending sharing disposition survives group cleanup.
pub fn remove_tree(path: &Path) -> io::Result<()> {
    std::fs::remove_dir_all(path)
}