mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Reading and writing the stored settings file.
//!
//! Every write lands whole or not at all: the new content is written beside the
//! target and then moved over it, so a stopped process never leaves a half
//! written file behind. On systems with file permissions the file is readable
//! by its owner alone, because a connection setting names a destination.

use crate::error::{Failure, Result};
use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::Path;

/// The stored settings, as raw text keyed by setting name.
///
/// Values stay as text here; reading them as their domain is the registry's
/// work, so an old file with a since-narrowed domain is reported rather than
/// silently dropped.
pub type Stored = BTreeMap<String, String>;

/// Reads the stored settings.
///
/// A missing file is not a failure: it means nothing was ever stored, and every
/// setting falls back to its built-in value.
///
/// # Errors
///
/// Returns a configuration failure when the file exists but cannot be read or
/// does not parse.
pub fn load(file: &Path) -> Result<Stored> {
    let text = match std::fs::read_to_string(file) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Stored::new()),
        Err(error) => {
            return Err(Failure::config(
                "config.unreadable",
                format!("the settings file at {} could not be read", file.display()),
            )
            .with_detail("detail", file.display().to_string())
            .with_hint("check that the file is readable by this user")
            .with_cause(error.to_string()))
        }
    };

    toml::from_str(&text).map_err(|error| {
        Failure::config(
            "config.malformed",
            format!(
                "the settings file at {} is not readable as stored settings",
                file.display()
            ),
        )
        .with_detail("detail", file.display().to_string())
        .with_hint("run `config doctor` to see what is wrong, or remove the file to start over")
        .with_cause(error.to_string())
    })
}

/// Writes one setting, leaving every other one untouched.
///
/// # Errors
///
/// Returns a configuration failure when the file cannot be read, written or
/// moved into place.
pub fn store(file: &Path, name: &str, raw: &str) -> Result<()> {
    let mut settings = load(file)?;
    settings.insert(name.to_owned(), raw.to_owned());
    write_all(file, &settings)
}

/// Removes one setting, so it falls back to its built-in value.
///
/// Returns whether anything was actually stored under that name.
///
/// # Errors
///
/// Returns a configuration failure when the file cannot be read or written.
pub fn remove(file: &Path, name: &str) -> Result<bool> {
    let mut settings = load(file)?;
    let existed = settings.remove(name).is_some();
    if existed {
        write_all(file, &settings)?;
    }
    Ok(existed)
}

/// Replaces the whole file in one move.
fn write_all(file: &Path, settings: &Stored) -> Result<()> {
    let directory = file.parent().unwrap_or_else(|| Path::new("."));
    std::fs::create_dir_all(directory).map_err(|error| {
        Failure::config(
            "config.directory_not_writable",
            format!(
                "the settings directory at {} could not be created",
                directory.display()
            ),
        )
        .with_detail("detail", directory.display().to_string())
        .with_hint("check that this user may write there")
        .with_cause(error.to_string())
    })?;

    let text = toml::to_string(settings).map_err(|error| {
        Failure::config(
            "config.not_serialisable",
            "the settings could not be written out",
        )
        .with_cause(error.to_string())
    })?;

    // The temporary file sits in the target directory so the move that follows
    // stays within one file system and is therefore a single step.
    let mut handle = tempfile::NamedTempFile::new_in(directory).map_err(|error| {
        Failure::config(
            "config.not_writable",
            format!(
                "no temporary file could be created in {}",
                directory.display()
            ),
        )
        .with_detail("detail", directory.display().to_string())
        .with_hint("check that this user may write there")
        .with_cause(error.to_string())
    })?;

    handle
        .write_all(text.as_bytes())
        .and_then(|()| handle.as_file().sync_all())
        .map_err(|error| {
            Failure::config("config.not_writable", "the settings could not be written")
                .with_detail("detail", file.display().to_string())
                .with_cause(error.to_string())
        })?;

    restrict(handle.path())?;

    handle.persist(file).map_err(|error| {
        Failure::config(
            "config.not_writable",
            format!("the settings could not be moved into {}", file.display()),
        )
        .with_detail("detail", file.display().to_string())
        .with_cause(error.to_string())
    })?;
    Ok(())
}

/// The permission bits the settings file must carry, where the system has them.
#[cfg(unix)]
pub const OWNER_ONLY: u32 = 0o600;

/// Narrows the file to its owner alone.
#[cfg(unix)]
fn restrict(file: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt as _;

    std::fs::set_permissions(file, std::fs::Permissions::from_mode(OWNER_ONLY)).map_err(|error| {
        Failure::config(
            "config.permission_not_applied",
            "the settings file could not be narrowed to its owner",
        )
        .with_hint("the product refuses to store a setting it cannot protect")
        .with_cause(error.to_string())
    })
}

/// Systems without file permission bits say so rather than report success.
///
/// Returning `Ok(())` alone was the whole defect: the type cannot tell "the
/// file was narrowed" apart from "there was nothing to narrow it with", so
/// every caller read the second as the first. The write still goes through,
/// because refusing it would leave such a system unable to store anything at
/// all, but it no longer goes through quietly.
#[cfg(not(unix))]
fn restrict(file: &Path) -> Result<()> {
    crate::i18n::report::permissions_unavailable_settings(&file.display().to_string());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scratch() -> tempfile::TempDir {
        tempfile::tempdir().expect("scratch directory")
    }

    #[test]
    fn an_absent_file_means_nothing_was_ever_stored() {
        let dir = scratch();
        let settings = load(&dir.path().join("config.toml")).expect("absence is not a failure");
        assert!(settings.is_empty());
    }

    #[test]
    fn a_stored_value_survives_a_round_trip() {
        let dir = scratch();
        let file = dir.path().join("config.toml");
        store(&file, "output.format", "ndjson").expect("writes");
        let settings = load(&file).expect("reads");
        assert_eq!(
            settings.get("output.format").map(String::as_str),
            Some("ndjson")
        );
    }

    #[test]
    fn writing_one_setting_leaves_the_others_untouched() {
        let dir = scratch();
        let file = dir.path().join("config.toml");
        store(&file, "output.format", "tsv").expect("writes");
        store(&file, "limits.retries", "5").expect("writes");
        let settings = load(&file).expect("reads");
        assert_eq!(
            settings.get("output.format").map(String::as_str),
            Some("tsv")
        );
        assert_eq!(
            settings.get("limits.retries").map(String::as_str),
            Some("5")
        );
    }

    #[test]
    fn removing_reports_whether_anything_was_stored() {
        let dir = scratch();
        let file = dir.path().join("config.toml");
        store(&file, "log.to_file", "true").expect("writes");
        assert!(remove(&file, "log.to_file").expect("removes"));
        assert!(!remove(&file, "log.to_file").expect("nothing left"));
    }

    #[test]
    fn the_write_leaves_no_leftover_beside_the_target() {
        let dir = scratch();
        let file = dir.path().join("config.toml");
        store(&file, "output.format", "json").expect("writes");
        let entries: Vec<_> = std::fs::read_dir(dir.path())
            .expect("listing")
            .filter_map(std::result::Result::ok)
            .map(|entry| entry.file_name())
            .collect();
        assert_eq!(
            entries.len(),
            1,
            "a half written file was left behind: {entries:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn the_stored_file_is_readable_by_its_owner_alone() {
        use std::os::unix::fs::PermissionsExt as _;

        let dir = scratch();
        let file = dir.path().join("config.toml");
        store(&file, "conn.default", "production").expect("writes");
        let mode = std::fs::metadata(&file)
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, OWNER_ONLY, "the file is open to other users");
    }

    #[test]
    fn a_file_that_does_not_parse_is_reported_rather_than_ignored() {
        let dir = scratch();
        let file = dir.path().join("config.toml");
        std::fs::write(&file, "this is not settings at all\n").expect("writes");
        let failure = load(&file).expect_err("must report");
        assert_eq!(failure.code(), "config.malformed");
    }
}