mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Named destinations and the store that keeps them.
//!
//! A profile records where a server is and how to reach it. It never records
//! the secret itself: it records a reference to one, and the value stays with
//! the vault. That separation is what lets a profile be listed, shown, copied
//! and written to disk without a secret ever travelling with it.

use crate::error::{Failure, Result};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::PathBuf;

/// What a shown secret looks like on any channel.
///
/// One fixed mark for every stored secret, so the length of the real value is
/// never leaked by the length of its mark.
const REDACTED: &str = "***";

/// A handle to a secret held elsewhere.
///
/// The handle is safe to write to disk, print and log; the value it points at
/// is not, and never leaves the vault except into the driver's option set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretRef(String);

impl SecretRef {
    /// Builds the reference belonging to one profile.
    #[must_use]
    pub fn for_profile(name: &str) -> Self {
        Self(format!("profile.{name}.secret"))
    }

    /// The stable key the vault stores this secret under.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.0
    }
}

/// Where secret values actually live.
///
/// The connection layer declares this interface and never implements it: the
/// configuration layer owns the storage, the file permissions and the wiping.
pub trait SecretVault {
    /// Records a secret under its reference, replacing any earlier value.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the secret cannot be written.
    fn store(&mut self, reference: &SecretRef, secret: &SecretString) -> Result<()>;

    /// Reads the secret behind a reference, if one was ever recorded.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the store cannot be read.
    fn load(&self, reference: &SecretRef) -> Result<Option<SecretString>>;

    /// Removes a secret, so deleting a profile leaves nothing behind.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the secret cannot be removed.
    fn forget(&mut self, reference: &SecretRef) -> Result<()>;
}

/// One named destination.
///
/// Every field beyond the name is optional, because a destination may be
/// described by a socket path alone just as well as by a host and a port.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Profile {
    /// The name the caller addresses this destination by.
    pub name: String,
    /// Server host, when the destination is reached over the network.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub host: Option<String>,
    /// Server port; absent means the configured default applies.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub port: Option<u16>,
    /// Local socket path, when the destination is reached without a network.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub socket: Option<PathBuf>,
    /// The user the credential belongs to.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub user: Option<String>,
    /// Database pinned to this destination.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub database: Option<String>,
    /// Whether this destination's database is the only one it may be used with.
    ///
    /// A destination that names a database still accepted another one on the
    /// command line, and swapped it in without saying so: the caller asked for
    /// one database, the work ran in a second, and the answer looked the same
    /// either way. Pinned, the parameter is refused instead of obeyed, so the
    /// mistake is a message rather than a result read from the wrong place.
    #[serde(default)]
    pub pin_database: bool,
    /// The declared authentication method, when the server needs it named.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub auth_method: Option<String>,
    /// Where the secret lives; never the secret itself.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub secret: Option<SecretRef>,
    /// Certificate presented to the server.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub client_cert: Option<PathBuf>,
    /// Key matching the presented certificate.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub client_key: Option<PathBuf>,
    /// Authority used to verify the server's certificate.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ca: Option<PathBuf>,
    /// Whether this destination demands an encrypted channel.
    ///
    /// Three states, not two. A bare truth value cannot tell "this destination
    /// says it does not need encryption" from "this destination says nothing",
    /// and collapsing the two makes the stored default unbeatable: a caller
    /// writing `require_tls=false` would be ignored in silence. Absent means the
    /// stored key decides; present means this destination has the last word.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub require_tls: Option<bool>,
    /// Session adjustments applied every time this destination is opened.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub session_setup: Vec<String>,
    /// Refuse every change made through this destination.
    #[serde(default)]
    pub read_only: bool,
}

impl Profile {
    /// Builds an empty profile carrying only its name.
    #[must_use]
    pub fn named(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Self::default()
        }
    }

    /// The profile as it may be shown on any channel.
    ///
    /// The secret reference is replaced by a fixed mark, so a shown profile
    /// tells the caller whether a secret exists without telling anyone what it
    /// is or even how long it is.
    #[must_use]
    pub fn redacted(&self) -> Value {
        json!({
            "name": self.name,
            "host": self.host,
            "port": self.port,
            "socket": self.socket,
            "user": self.user,
            "database": self.database,
            "pin_database": self.pin_database,
            "auth_method": self.auth_method,
            "secret": self.secret.as_ref().map(|_| REDACTED),
            "client_cert": self.client_cert,
            "client_key": self.client_key,
            "ca": self.ca,
            "require_tls": self.require_tls,
            "session_setup": self.session_setup,
            "read_only": self.read_only,
        })
    }

    /// Refuses a profile that names no way of reaching a server.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when neither a host nor a socket path
    /// is present, because there is then nothing to open.
    pub fn ensure_reachable(&self) -> Result<()> {
        if self.host.is_none() && self.socket.is_none() {
            return Err(Failure::config(
                "profile.no_destination",
                format!("profile `{}` names neither a host nor a socket", self.name),
            )
            .with_detail("profile", self.name.clone())
            .with_hint("set a host with --host, or a local socket with --socket"));
        }
        Ok(())
    }

    /// Refuses a pin that has no database to pin.
    ///
    /// Fixing the database and naming none is an argument list that cannot mean
    /// anything, and the harm of accepting it is silent: the destination would
    /// carry a pin that refuses every named database while itself pointing at
    /// whichever one the server hands out.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when the destination pins a database it does not
    /// name.
    pub fn ensure_pin_names_a_database(&self) -> Result<()> {
        if self.pin_database && self.database.is_none() {
            return Err(Failure::usage(
                "profile.pinned_database_missing",
                format!(
                    "profile `{}` fixes its database without naming one",
                    self.name
                ),
            )
            .with_detail("profile", self.name.clone())
            .with_hint("name it in the same call, as in `--database loja --pin-database`"));
        }
        Ok(())
    }

    /// Refuses the database parameter when this destination fixed its own.
    ///
    /// Refused, and not compared: a destination that fixed its database stopped
    /// taking the parameter at all, so a caller passing the pinned name is
    /// passing something this destination no longer reads, and answering it as
    /// though it had been honoured would teach the wrong contract.
    ///
    /// # Errors
    ///
    /// Returns a usage failure naming the pinned database when the parameter is
    /// present on a destination that fixed one.
    pub fn ensure_accepts_a_named_database(&self, named: Option<&str>) -> Result<()> {
        let (true, Some(named)) = (self.pin_database, named) else {
            return Ok(());
        };
        let pinned = self.database.as_deref().unwrap_or("<none>");
        // The three moving parts travel as named details rather than baked
        // into one English sentence. A sentence built here is interpolated
        // into the translated message as `$detail`, which hands a reader one
        // line of their own language wrapped around one line of English. Named
        // details let each language place the three names in its own order.
        Err(Failure::usage(
            "profile.database_is_pinned",
            format!(
                "profile `{}` is fixed on database `{pinned}` and takes no database parameter, \
                 so `{named}` cannot be honoured",
                self.name
            ),
        )
        .with_detail("profile", self.name.clone())
        .with_detail("pinned", pinned.to_owned())
        .with_detail("named", named.to_owned())
        .with_hint(format!(
            "drop --database, or point at a destination whose database is not fixed; \
             `conn edit {} --pin-database false` releases this one",
            self.name
        )))
    }
}

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

    fn sample(name: &str) -> Profile {
        Profile {
            host: Some("db.example".to_owned()),
            user: Some("reader".to_owned()),
            secret: Some(SecretRef::for_profile(name)),
            ..Profile::named(name)
        }
    }

    /// A shown profile says a secret exists without revealing it or its length.
    #[test]
    fn a_shown_profile_never_reveals_the_secret() {
        let shown = sample("main").redacted();
        assert_eq!(shown["secret"], REDACTED);
        let text = serde_json::to_string(&shown).expect("serialises");
        assert!(
            !text.contains("profile.main.secret"),
            "no handle leaks: {text}"
        );
    }

    /// A profile with no secret says so, rather than showing an empty mark.
    #[test]
    fn a_profile_without_a_secret_shows_none() {
        assert!(Profile::named("socketonly").redacted()["secret"].is_null());
    }

    /// A stored profile never carries the secret itself, only a handle to it.
    #[test]
    fn a_stored_profile_carries_a_handle_and_never_a_value() {
        let written = toml::to_string(&sample("main")).expect("serialises");
        assert!(
            written.contains("profile.main.secret"),
            "the handle is stored"
        );
        assert!(!written.contains("hunter2"));
    }

    /// A profile naming neither a host nor a socket cannot be opened, and says
    /// so before any connection is attempted.
    #[test]
    fn a_profile_with_no_destination_is_refused() {
        let failure = Profile::named("empty")
            .ensure_reachable()
            .expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_destination");
        assert_eq!(failure.category(), crate::error::Category::Config);
    }

    /// A socket alone is enough to reach a server, so it is accepted.
    #[test]
    fn a_socket_alone_is_a_destination() {
        let profile = Profile {
            socket: Some(PathBuf::from("/run/mysqld/mysqld.sock")),
            ..Profile::named("local")
        };
        assert!(profile.ensure_reachable().is_ok());
    }
}