mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! What is wrong with the stored settings.
//!
//! The answer is a list of findings, never prose. A caller decides what to do
//! from the kind of each finding, so the wording may change without breaking
//! anything that reads it.

use super::{keys, paths, store};
use crate::error::Result;
use serde::Serialize;
use std::path::Path;

/// What kind of problem was found.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    /// The settings file could not be read at all.
    Unreadable,
    /// A stored name is not a setting of this product.
    UnknownKey,
    /// A stored value falls outside its setting's domain.
    ValueOutsideDomain,
    /// The file is open to users other than its owner.
    OpenToOtherUsers,
    /// This system has no permission bits, so the file was never narrowed.
    ///
    /// # Why absence of a check is itself a finding
    ///
    /// FR-100 promises that a system which cannot restrict the file is told
    /// about rather than written to in silence. Where the bits exist, the
    /// promise is kept by [`Kind::OpenToOtherUsers`]. Where they do not, this
    /// diagnosis used to say nothing at all — and saying nothing reads exactly
    /// like saying the file is protected, which is the one thing it must never
    /// be mistaken for.
    NotNarrowedByThisSystem,
}

/// One thing that is wrong.
#[derive(Debug, Clone, Serialize)]
pub struct Finding {
    /// What kind of problem this is.
    pub kind: Kind,
    /// The setting or the file the problem is about.
    pub subject: String,
    /// The problem in human prose.
    pub detail: String,
    /// The concrete next action.
    pub remedy: String,
}

/// The whole diagnosis.
#[derive(Debug, Clone, Serialize)]
pub struct Report {
    /// Where the settings file lives.
    pub file: String,
    /// Whether a file exists there at all.
    pub file_exists: bool,
    /// Everything that is wrong, in the order it was found.
    pub findings: Vec<Finding>,
}

impl Report {
    /// Whether nothing is wrong.
    #[must_use]
    pub fn is_clean(&self) -> bool {
        self.findings.is_empty()
    }
}

/// Examines the stored settings and reports every problem at once.
///
/// A problem never stops the examination, because a caller fixing settings
/// wants the whole list rather than the first line of it.
///
/// # Errors
///
/// Returns a configuration failure only when the location itself cannot be
/// determined; a broken file is a finding, not a failure.
pub fn run(override_dir: Option<&Path>) -> Result<Report> {
    let file = paths::config_file(override_dir)?;
    let file_exists = file.exists();
    let mut findings = Vec::new();

    let settings = match store::load(&file) {
        Ok(settings) => settings,
        Err(failure) => {
            findings.push(Finding {
                kind: Kind::Unreadable,
                subject: file.display().to_string(),
                detail: failure.message().to_owned(),
                // Written here rather than borrowed from the failure. The
                // failure's own hint sends the reader to `config doctor`,
                // which is right for every other caller and is a closed loop
                // for this one: this IS `config doctor`, and a report that
                // tells its reader to run the report they are holding has
                // spent a line saying nothing.
                remedy: "remove the file to start from the built-in values, or \
                         rewrite it as stored settings"
                    .to_owned(),
            });
            return Ok(Report {
                file: file.display().to_string(),
                file_exists,
                findings,
            });
        }
    };

    for (name, raw) in &settings {
        inspect(name, raw, &mut findings);
    }
    inspect_permissions(&file, file_exists, &mut findings);

    Ok(Report {
        file: file.display().to_string(),
        file_exists,
        findings,
    })
}

/// Checks one stored pair against the registry.
fn inspect(name: &str, raw: &str, findings: &mut Vec<Finding>) {
    let Some(entry) = keys::spec(name) else {
        findings.push(Finding {
            kind: Kind::UnknownKey,
            subject: name.to_owned(),
            detail: format!("`{name}` is not a setting of this product"),
            remedy: format!("run `config unset {name}` to drop it"),
        });
        return;
    };

    if let Err(failure) = keys::validate(entry.name, raw) {
        findings.push(Finding {
            kind: Kind::ValueOutsideDomain,
            subject: entry.name.to_owned(),
            detail: failure.message().to_owned(),
            remedy: format!("accepted: {}", entry.domain.described()),
        });
    }
}

/// Checks that the file is readable by its owner alone.
#[cfg(unix)]
fn inspect_permissions(file: &Path, file_exists: bool, findings: &mut Vec<Finding>) {
    use std::os::unix::fs::PermissionsExt as _;

    if !file_exists {
        return;
    }
    let Ok(metadata) = std::fs::metadata(file) else {
        return;
    };

    let mode = metadata.permissions().mode() & 0o777;
    if mode != store::OWNER_ONLY {
        findings.push(Finding {
            kind: Kind::OpenToOtherUsers,
            subject: file.display().to_string(),
            detail: format!(
                "the settings file carries mode {mode:04o} instead of {:04o}",
                store::OWNER_ONLY
            ),
            remedy: "narrow the file to its owner alone".to_owned(),
        });
    }
}

/// Systems without permission bits report that the file was never narrowed.
#[cfg(not(unix))]
fn inspect_permissions(file: &Path, file_exists: bool, findings: &mut Vec<Finding>) {
    if file_exists {
        findings.push(not_narrowed_by_this_system(file));
    }
}

/// The finding a system without permission bits owes its caller.
///
/// # Why this is not written inside the block that uses it
///
/// The block above is compiled on one family of systems and this suite runs on
/// another, so a mistake in the wording, the remedy or the kind would travel
/// all the way to a release without one proof having read it. Here, the
/// decision is ordinary code on every system, and the proofs below check it
/// wherever they happen to run. What stays behind the flag is only the call.
///
/// It is compiled where it is called and where it is proved, and nowhere else,
/// so a system that keeps its own permission bits does not carry a function it
/// has no use for.
#[cfg(any(not(unix), test))]
pub(crate) fn not_narrowed_by_this_system(file: &Path) -> Finding {
    Finding {
        kind: Kind::NotNarrowedByThisSystem,
        subject: file.display().to_string(),
        detail: "this system has no file permission bits, so the settings file was stored \
                 without being narrowed to its owner"
            .to_owned(),
        remedy: "keep this file where the account's own directory is already closed to other \
                 users, because the product cannot close it here"
            .to_owned(),
    }
}

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

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

    /// A system that cannot narrow the file says so instead of staying quiet.
    ///
    /// FR-100 asks for a warning where the restriction cannot be applied, and
    /// the answer used to be an empty block: nothing was checked and nothing
    /// was said, which a caller cannot tell apart from a file that is properly
    /// closed. This runs on every system because it reads the decision rather
    /// than the platform, so the wording and the kind are held here even where
    /// the branch that calls it is not compiled.
    #[test]
    fn a_system_without_permission_bits_reports_that_it_narrowed_nothing() {
        let finding = not_narrowed_by_this_system(Path::new("/somewhere/config.toml"));

        assert_eq!(finding.kind, Kind::NotNarrowedByThisSystem);
        assert!(
            finding.subject.contains("config.toml"),
            "the finding names the file it is about: {}",
            finding.subject
        );
        assert!(
            !finding.remedy.is_empty(),
            "a finding a caller can do nothing about is still owed a next step"
        );
    }

    /// The absence of protection is never reported as the presence of it.
    ///
    /// FR-100. The two kinds a caller may see about this file mean opposite
    /// things, and a product that reused `OpenToOtherUsers` for a system with
    /// no bits at all would send its reader off to fix permissions that the
    /// system does not have.
    #[test]
    fn not_being_narrowed_is_a_different_finding_from_being_open() {
        let finding = not_narrowed_by_this_system(Path::new("/somewhere/config.toml"));

        assert_ne!(finding.kind, Kind::OpenToOtherUsers);
    }

    #[test]
    fn a_location_with_nothing_stored_is_clean() {
        let dir = scratch();
        let report = run(Some(dir.path())).expect("examines");
        assert!(report.is_clean());
        assert!(!report.file_exists);
    }

    #[test]
    fn settings_written_by_the_product_are_clean() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        store::store(&file, "output.format", "ndjson").expect("writes");
        let report = run(Some(dir.path())).expect("examines");
        assert!(
            report.is_clean(),
            "unexpected findings: {:?}",
            report.findings
        );
    }

    #[test]
    fn a_stored_name_outside_the_registry_is_pointed_out() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(&file, "\"output.nonsense\" = \"1\"\n").expect("writes");

        let report = run(Some(dir.path())).expect("examines");
        let found = report
            .findings
            .iter()
            .find(|finding| finding.kind == Kind::UnknownKey)
            .expect("the unknown name must be pointed out");
        assert_eq!(found.subject, "output.nonsense");
    }

    #[test]
    fn a_stored_value_outside_its_domain_is_pointed_out() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(&file, "\"limits.retries\" = \"many\"\n").expect("writes");

        let report = run(Some(dir.path())).expect("examines");
        assert_eq!(report.findings[0].kind, Kind::ValueOutsideDomain);
    }

    #[test]
    fn a_file_that_does_not_parse_is_pointed_out_as_unreadable() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(&file, "not settings at all\n").expect("writes");

        let report = run(Some(dir.path())).expect("examines");
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].kind, Kind::Unreadable);
    }

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

        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        store::store(&file, "output.format", "json").expect("writes");
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).expect("widens");

        let report = run(Some(dir.path())).expect("examines");
        assert_eq!(report.findings[0].kind, Kind::OpenToOtherUsers);
    }

    #[test]
    fn every_problem_is_reported_at_once() {
        let dir = scratch();
        let file = paths::config_file(Some(dir.path())).expect("location");
        std::fs::create_dir_all(dir.path()).expect("directory");
        std::fs::write(
            &file,
            "\"output.nonsense\" = \"1\"\n\"limits.retries\" = \"many\"\n",
        )
        .expect("writes");

        let report = run(Some(dir.path())).expect("examines");
        assert!(
            report.findings.len() >= 2,
            "the examination stopped at the first problem: {:?}",
            report.findings
        );
    }
}