mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Where secrets actually live on disk.
//!
//! The connection layer declares the interface and never implements it. Storage
//! belongs here, together with the file permissions and the wiping, so a secret
//! has exactly one home.

use crate::conn::profile::{SecretRef, SecretVault};
use crate::error::{Failure, Result};
use secrecy::{ExposeSecret, SecretString};
use std::path::{Path, PathBuf};

/// Where a secret is allowed to come to rest.
///
/// The published setting `secret.storage_mode` carries two words and both had
/// to mean something. It did not: the vault wrote to its file whichever word
/// was stored, so `config set secret.storage_mode none` answered success and
/// left the credential on disk exactly as before. An instruction about a
/// secret that is accepted and discarded is worse than one that is refused,
/// because the caller has been told it was obeyed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretStorage {
    /// Kept in the vault file, to be read back on later invocations.
    File,
    /// Kept nowhere. The credential is supplied again on every invocation.
    Nowhere,
}

impl SecretStorage {
    /// Reads the mode from the word the registry publishes for it.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is not one this build
    /// knows, which can only happen if the registry and this list drift apart.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "file" => Ok(Self::File),
            "none" => Ok(Self::Nowhere),
            // The detail is the bare word, never a sentence. A sentence built
            // here would be interpolated into the translated message and the
            // reader would get their own language wrapped around English.
            other => Err(
                Failure::config("config.unknown_secret_storage", other.to_owned())
                    .with_detail("detail", other.to_owned())
                    .with_hint("the ways are `file` and `none`"),
            ),
        }
    }

    /// Whether a secret may be written down at all.
    #[must_use]
    pub const fn keeps_anything(self) -> bool {
        matches!(self, Self::File)
    }
}

/// A vault backed by a file of its own, beside the configuration.
///
/// Secrets live apart from settings so that sharing a configuration file never
/// shares a credential by accident.
#[derive(Debug)]
pub struct FileVault {
    file: PathBuf,
    storage: SecretStorage,
}

/// The file name secrets are kept under, inside the configuration directory.
const VAULT_FILE: &str = "secrets.toml";

impl FileVault {
    /// Opens the vault living in the given configuration directory.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the directory cannot be resolved.
    pub fn open(directory: &Path) -> Result<Self> {
        Self::open_keeping(directory, SecretStorage::File)
    }

    /// Opens the vault under the way of keeping the caller published.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the directory cannot be resolved.
    pub fn open_keeping(directory: &Path, storage: SecretStorage) -> Result<Self> {
        Ok(Self {
            file: directory.join(VAULT_FILE),
            storage,
        })
    }

    /// Where this vault keeps its file.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.file
    }

    /// The way of keeping this vault was opened under.
    #[must_use]
    pub const fn storage(&self) -> SecretStorage {
        self.storage
    }
}

impl SecretVault for FileVault {
    fn store(&mut self, reference: &SecretRef, secret: &SecretString) -> Result<()> {
        // Refused rather than quietly skipped. A caller who piped a credential
        // in has done the one thing that cannot be undone by reading the answer
        // again, so the answer has to say the credential was not kept. Skipping
        // in silence would repeat the very defect this mode was written to end.
        if !self.storage.keeps_anything() {
            return Err(kept_nowhere());
        }
        crate::config::store::store(&self.file, reference.key(), secret.expose_secret())
    }

    fn load(&self, reference: &SecretRef) -> Result<Option<SecretString>> {
        // Absent rather than a failure, which is the same answer an unrecorded
        // secret already gives. The caller's own missing-secret path then
        // reports it, with the wording that path has always used.
        if !self.storage.keeps_anything() {
            return Ok(None);
        }
        let stored = crate::config::store::load(&self.file)?;
        Ok(stored
            .get(reference.key())
            .map(|raw| SecretString::from(raw.to_owned())))
    }

    fn forget(&mut self, reference: &SecretRef) -> Result<()> {
        // Forgetting is allowed under either way of keeping. A vault switched
        // to keeping nothing still has to be able to clear what an earlier
        // invocation wrote, or the setting would trap the very secrets it was
        // turned on to be rid of.
        crate::config::store::remove(&self.file, reference.key())?;
        Ok(())
    }
}

/// The failure raised when a secret is offered to a vault that keeps nothing.
#[must_use]
pub fn kept_nowhere() -> Failure {
    Failure::config(
        "vault.keeps_nothing",
        "this host keeps no secret, so the one offered was not written down",
    )
    .with_hint(
        "supply it on every invocation, or allow storage with \
         `config set secret.storage_mode file`",
    )
}

/// Reads a secret from the caller's input stream.
///
/// The failure raised when a profile needs a secret that was never recorded.
#[must_use]
pub fn missing(profile: &str) -> Failure {
    Failure::config(
        "vault.secret_missing",
        format!("profile `{profile}` has no recorded secret"),
    )
    .with_detail("detail", profile)
    .with_hint("record one with `conn edit <name> --password-stdin`")
}

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

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

    #[test]
    fn a_recorded_secret_comes_back_intact() {
        let dir = scratch();
        let mut vault = FileVault::open(dir.path()).expect("opens");
        let reference = SecretRef::for_profile("staging");

        vault
            .store(&reference, &SecretString::from("s3cr3t".to_owned()))
            .expect("records");

        let found = vault.load(&reference).expect("reads").expect("present");
        assert_eq!(found.expose_secret(), "s3cr3t");
    }

    #[test]
    fn an_unrecorded_secret_is_absent_rather_than_a_failure() {
        let dir = scratch();
        let vault = FileVault::open(dir.path()).expect("opens");
        let found = vault
            .load(&SecretRef::for_profile("never-set"))
            .expect("reads");
        assert!(found.is_none());
    }

    #[test]
    fn forgetting_leaves_nothing_behind() {
        let dir = scratch();
        let mut vault = FileVault::open(dir.path()).expect("opens");
        let reference = SecretRef::for_profile("gone");

        vault
            .store(&reference, &SecretString::from("value".to_owned()))
            .expect("records");
        vault.forget(&reference).expect("forgets");

        assert!(vault.load(&reference).expect("reads").is_none());
    }

    #[test]
    fn secrets_live_apart_from_settings() {
        let dir = scratch();
        let vault = FileVault::open(dir.path()).expect("opens");
        let settings = crate::config::paths::config_file(Some(dir.path())).expect("location");
        assert_ne!(
            vault.path(),
            settings,
            "a shared configuration file must never carry a credential"
        );
    }

    /// FR-100. Another user of the same host cannot read the secret file: the
    /// mode carries no bit for anybody but the owner.
    #[cfg(unix)]
    #[test]
    fn the_vault_file_is_readable_only_by_its_owner() {
        use std::os::unix::fs::PermissionsExt;

        let dir = scratch();
        let mut vault = FileVault::open(dir.path()).expect("opens");
        vault
            .store(
                &SecretRef::for_profile("guarded"),
                &SecretString::from("value".to_owned()),
            )
            .expect("records");

        let mode = std::fs::metadata(vault.path())
            .expect("the file exists")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600, "unexpected mode {:o}", mode & 0o777);
    }
}