stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
//! Exclusive creation and checked reading of files that hold secrets.

use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read as _, Write as _};
use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::path::{Path, PathBuf};

use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use rustix::process::geteuid;
use zeroize::Zeroizing;

/// The permission bits a private file is created with.
const PRIVATE_MODE: u32 = 0o600;

/// Permission bits that must be clear on a private file: any access by the
/// group or by others.
const GROUP_OTHER_BITS: u32 = 0o077;

/// Why a private file could not be created or read.
///
/// No variant carries any part of the file's contents.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PrivateFileError {
    /// The file exists and is never overwritten.
    #[error("file already exists and will not be overwritten")]
    AlreadyExists,
    /// The path is a symbolic link, which is refused for secret files.
    #[error("file is a symbolic link")]
    Symlink,
    /// The path is not a regular file.
    #[error("file is not a regular file")]
    NotRegularFile,
    /// The file grants access to its group or to others.
    #[error("file mode {mode:04o} is wider than 0600")]
    TooPermissive {
        /// The file's permission bits.
        mode: u32,
    },
    /// The file is larger than its format allows.
    #[error("file is larger than {limit} bytes")]
    TooLarge {
        /// The largest accepted size in bytes.
        limit: usize,
    },
    /// The file belongs to another user. Checked only for files that must
    /// be the operator's own, such as the key file, and not when running as
    /// root.
    #[error("file is owned by uid {uid}, not by the user running stratum")]
    WrongOwner {
        /// The file's owner.
        uid: u32,
    },
    /// An operating-system error.
    #[error("{0}")]
    Io(#[source] io::Error),
}

/// Policy for the permission bits of a file being read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ModePolicy {
    /// Refuse a file that grants any access to group or others.
    OwnerOnly,
    /// Accept any mode (the file belongs to someone else, such as the node).
    Any,
}

/// Reads a regular file of at most `limit` bytes into zeroising memory.
///
/// The file is opened once, with `O_NOFOLLOW` (a symbolic link in the
/// last component is refused by the kernel), `O_NONBLOCK` (opening a FIFO
/// or device returns at once instead of waiting for a writer) and
/// `O_CLOEXEC`. Its type, mode and owner are then checked on the open
/// descriptor, so nothing can be swapped in between a check and the open.
/// Under [`ModePolicy::OwnerOnly`] a mode wider than `0600`, or an owner
/// other than the effective user, is refused. The owner is not compared when
/// running as root (`sudo -E stratum setup` with the operator's own key
/// file): root can read the file anyway, and the trust boundary does not
/// defend against root.
pub(crate) fn read(
    path: &Path,
    limit: usize,
    policy: ModePolicy,
) -> Result<Zeroizing<Vec<u8>>, PrivateFileError> {
    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
    let fd = rustix::fs::open(path, flags, Mode::empty()).map_err(|errno| {
        if errno == Errno::LOOP {
            PrivateFileError::Symlink
        } else {
            PrivateFileError::Io(io::Error::from(errno))
        }
    })?;
    let file = File::from(fd);
    let opened = file.metadata().map_err(PrivateFileError::Io)?;
    if !opened.is_file() {
        return Err(PrivateFileError::NotRegularFile);
    }
    if policy == ModePolicy::OwnerOnly {
        let mode = opened.mode() & 0o7777;
        if mode & GROUP_OTHER_BITS != 0 {
            return Err(PrivateFileError::TooPermissive { mode });
        }
        let euid = geteuid();
        if !euid.is_root() && opened.uid() != euid.as_raw() {
            return Err(PrivateFileError::WrongOwner { uid: opened.uid() });
        }
    }
    let cap = u64::try_from(limit).map_or(u64::MAX, |n| n.saturating_add(1));
    let mut contents = Zeroizing::new(Vec::with_capacity(limit.saturating_add(1)));
    file.take(cap)
        .read_to_end(&mut contents)
        .map_err(PrivateFileError::Io)?;
    if contents.len() > limit {
        return Err(PrivateFileError::TooLarge { limit });
    }
    Ok(contents)
}

/// Creates `path` exclusively with mode `0600`, writes `contents` and syncs
/// the file and its directory.
///
/// The contents are written to a new temporary file in the same directory
/// (`.<name>.tmp-<random>`, created exclusively with mode `0600`), synced,
/// and only then moved to `path` with [`place_new`], which never replaces
/// anything already there. So the file is never readable by others, an
/// existing file or symbolic link at `path` is never followed or
/// overwritten (including one that appears while the contents are being
/// written), and a process killed part-way never leaves a partial file
/// under the final name: at worst it leaves the hidden temporary file,
/// which no later run reads or collides with. On any error the temporary
/// file is removed.
pub(crate) fn create(path: &Path, contents: &[u8]) -> Result<(), PrivateFileError> {
    create_with(path, |file| file.write_all(contents))
}

/// As [`create`], with `write` filling the file; the seam the tests use to
/// stop a write part-way.
fn create_with(
    path: &Path,
    write: impl FnOnce(&mut File) -> io::Result<()>,
) -> Result<(), PrivateFileError> {
    // Refuse early, so a secret is not written to disk only to be discarded.
    // The exclusive placement below is what guarantees it.
    if fs::symlink_metadata(path).is_ok() {
        return Err(PrivateFileError::AlreadyExists);
    }
    let temp = temporary_name(path)?;
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(PRIVATE_MODE)
        .open(&temp)
        .map_err(PrivateFileError::Io)?;
    let written = write(&mut file)
        .and_then(|()| file.sync_all())
        .map_err(PrivateFileError::Io);
    drop(file);
    let placed = written.and_then(|()| {
        place_new(&temp, path).map_err(|err| {
            if err.kind() == io::ErrorKind::AlreadyExists {
                PrivateFileError::AlreadyExists
            } else {
                PrivateFileError::Io(err)
            }
        })
    });
    if let Err(err) = placed {
        // Best effort: the error being returned is the one that matters.
        let _removed = fs::remove_file(&temp);
        return Err(err);
    }
    sync_parent(path);
    Ok(())
}

/// A fresh hidden name beside `path`: `.<name>.tmp-<12 hex digits>`.
fn temporary_name(path: &Path) -> Result<PathBuf, PrivateFileError> {
    let name = path.file_name().ok_or_else(|| {
        PrivateFileError::Io(io::Error::new(
            io::ErrorKind::InvalidInput,
            "the path does not name a file",
        ))
    })?;
    let mut tag = [0u8; 6];
    getrandom::fill(&mut tag).map_err(|_| {
        PrivateFileError::Io(io::Error::other("the system random source is unavailable"))
    })?;
    let mut temp = OsString::from(".");
    temp.push(name);
    temp.push(format!(".tmp-{}", hex::encode(tag)));
    Ok(path.with_file_name(temp))
}

/// Moves the file at `temp` to `target` only if nothing exists at `target`;
/// an existing file, directory or symbolic link there is never replaced and
/// gives [`io::ErrorKind::AlreadyExists`].
///
/// On Linux this is one `renameat2(RENAME_NOREPLACE)`. Where the kernel or
/// filesystem lacks that flag (and on other systems) it is a hard link to
/// `target`, which fails the same way when `target` exists, followed by
/// removing `temp`. Either way there is no window in which a file at
/// `target` could be overwritten. Both names must be in the same
/// filesystem.
pub(crate) fn place_new(temp: &Path, target: &Path) -> io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "android"))]
    {
        use rustix::fs::{renameat_with, RenameFlags, CWD};
        match renameat_with(CWD, temp, CWD, target, RenameFlags::NOREPLACE) {
            Ok(()) => return Ok(()),
            Err(errno) if [Errno::INVAL, Errno::NOSYS, Errno::OPNOTSUPP].contains(&errno) => {}
            Err(errno) => return Err(io::Error::from(errno)),
        }
    }
    link_new(temp, target)
}

/// The portable half of [`place_new`]: a hard link, which never replaces
/// an existing `target`, then removing `temp`.
fn link_new(temp: &Path, target: &Path) -> io::Result<()> {
    fs::hard_link(temp, target)?;
    // Best effort: the file is in place under `target` already.
    let _removed = fs::remove_file(temp);
    Ok(())
}

/// Removes a file and syncs its directory.
pub(crate) fn remove(path: &Path) -> Result<(), PrivateFileError> {
    fs::remove_file(path).map_err(PrivateFileError::Io)?;
    sync_parent(path);
    Ok(())
}

/// Syncs the directory holding `path` so a creation or removal is durable.
///
/// Best effort: some filesystems refuse to sync a directory, and the file
/// itself has already been synced.
fn sync_parent(path: &Path) {
    let parent = match path.parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir,
        _ => Path::new("."),
    };
    if let Ok(dir) = File::open(parent) {
        let _synced = dir.sync_all();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::panic::{self, AssertUnwindSafe};

    /// The names in `dir`, sorted.
    fn names(dir: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(dir)
            .expect("read dir")
            .map(|entry| {
                entry
                    .expect("entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        names.sort();
        names
    }

    #[test]
    fn a_complete_file_is_private_and_nothing_else_is_left() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("key.nsec");
        create(&path, b"secret\n").expect("create");
        assert_eq!(fs::read(&path).expect("read"), b"secret\n", "contents");
        let mode = fs::metadata(&path).expect("metadata").mode() & 0o7777;
        assert_eq!(mode, PRIVATE_MODE, "mode");
        assert_eq!(names(dir.path()), ["key.nsec"], "no temporary file is left");
        assert!(
            matches!(
                create(&path, b"other"),
                Err(PrivateFileError::AlreadyExists)
            ),
            "an existing file is refused"
        );
        assert_eq!(fs::read(&path).expect("read"), b"secret\n", "and kept");
    }

    #[test]
    fn a_write_stopped_part_way_leaves_nothing_under_the_final_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("key.nsec");
        // A panic part-way stands in for a kill: no error path runs.
        let stopped = panic::catch_unwind(AssertUnwindSafe(|| {
            create_with(&path, |file| {
                file.write_all(b"nsec1part")?;
                panic!("killed mid-write");
            })
        }));
        assert!(stopped.is_err(), "the write was stopped");
        assert!(
            fs::symlink_metadata(&path).is_err(),
            "no partial file under the final name: {:?}",
            names(dir.path())
        );
        create(&path, b"secret\n").expect("the next create succeeds");
    }

    #[test]
    fn a_file_appearing_during_the_write_is_kept() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("key.nsec");
        let result = create_with(&path, |file| {
            fs::write(&path, b"theirs")?;
            file.write_all(b"ours")
        });
        assert!(
            matches!(result, Err(PrivateFileError::AlreadyExists)),
            "{result:?}"
        );
        assert_eq!(fs::read(&path).expect("read"), b"theirs", "never replaced");
        assert_eq!(
            names(dir.path()),
            ["key.nsec"],
            "the temporary file is removed"
        );
    }

    #[test]
    fn both_placements_refuse_an_existing_target() {
        let dir = tempfile::tempdir().expect("tempdir");
        let target = dir.path().join("final");
        for place in [place_new, link_new] {
            let temp = dir.path().join("temp");
            fs::write(&temp, b"ours").expect("temp");
            fs::write(&target, b"theirs").expect("theirs");
            let err = place(&temp, &target).expect_err("refused");
            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{err}");
            assert_eq!(fs::read(&target).expect("target"), b"theirs", "kept");
            fs::remove_file(&target).expect("clear");
            place(&temp, &target).expect("placed");
            assert_eq!(fs::read(&target).expect("target"), b"ours", "placed");
            assert!(fs::metadata(&temp).is_err(), "the temporary name is gone");
            fs::remove_file(&target).expect("clear");
        }
    }
}