mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The three commands that alter a stored destination, and the marking of the
//! one that applies when the caller names none.
//!
//! None of them reaches a server, and none of them ever puts a secret on a
//! channel.

use super::secret::read_secret_from_standard_input;
use crate::cli::conn::EditableFields;
use crate::conn::profile::{Profile, SecretRef, SecretVault};
use crate::conn::store::ProfileStore;
use crate::error::Result;
use crate::output::Envelope;
use serde_json::json;

/// Changes fields of an existing destination.
pub(super) fn edit(
    name: &str,
    fields: &EditableFields,
    database: Option<&str>,
    store: &mut ProfileStore,
    vault: &mut dyn SecretVault,
    conditions: super::Conditions,
) -> Result<Envelope> {
    let super::Conditions {
        refuses_to_ask,
        dry_run,
    } = conditions;
    let reference = SecretRef::for_profile(name);
    let secret = if fields.password_stdin {
        Some(read_secret_from_standard_input(refuses_to_ask)?)
    } else {
        None
    };

    let profile = store.get_mut(name)?;
    apply(profile, fields, database);
    if secret.is_some() {
        profile.secret = Some(reference.clone());
    }
    profile.ensure_reachable()?;
    profile.ensure_pin_names_a_database()?;
    let shown = profile.redacted();

    // Everything above runs either way: the fields are copied onto a store that
    // lives in this process alone, and both refusals have already had their say.
    // What a simulation withholds is the persisting, so a caller learns whether
    // the edit is admissible and what it would leave behind without leaving it.
    if !dry_run {
        if let Some(secret) = secret {
            vault.store(&reference, &secret)?;
        }
        store.save()?;
    }

    Ok(Envelope::new(
        "conn edit",
        json!({ "changed": true, "profile": shown, "simulated": dry_run }),
    ))
}

/// Copies the named fields onto the destination, leaving the rest untouched.
///
/// A field the caller did not name keeps its value, so an edit changes exactly
/// what it mentions and never resets anything by omission.
fn apply(profile: &mut Profile, fields: &EditableFields, database: Option<&str>) {
    if let Some(host) = &fields.host {
        profile.host = Some(host.clone());
    }
    if let Some(port) = fields.port {
        profile.port = Some(port);
    }
    if let Some(socket) = &fields.socket {
        profile.socket = Some(socket.clone());
    }
    if let Some(user) = &fields.user {
        profile.user = Some(user.clone());
    }
    if let Some(database) = database {
        profile.database = Some(database.to_owned());
    }
    if let Some(pinned) = fields.pin_database {
        profile.pin_database = pinned;
    }
    if let Some(read_only) = fields.read_only_profile {
        profile.read_only = read_only;
    }
    if let Some(auth) = &fields.auth {
        profile.auth_method = Some(auth.clone());
    }
    if let Some(certificate) = &fields.client_cert {
        profile.client_cert = Some(certificate.clone());
    }
    if let Some(key) = &fields.client_key {
        profile.client_key = Some(key.clone());
    }
    if let Some(authority) = &fields.ca {
        profile.ca = Some(authority.clone());
    }
    if let Some(demanded) = fields.require_tls {
        profile.require_tls = Some(demanded);
    }
    // The empty text is how a caller asks for the empty list, for the reason
    // given where the field is declared. Anything else replaces, and an absent
    // flag leaves the stored adjustments as they were.
    if !fields.session_setup.is_empty() {
        profile.session_setup = if fields.session_setup == [String::new()] {
            Vec::new()
        } else {
            fields.session_setup.clone()
        };
    }
}

/// Deletes a destination and the secret it pointed at.
pub(super) fn remove(
    name: &str,
    store: &mut ProfileStore,
    vault: &mut dyn SecretVault,
    marked: Option<&str>,
    settings_file: &std::path::Path,
    dry_run: bool,
) -> Result<Envelope> {
    // Removing from the store in hand is what tells us the destination exists
    // and what secret it pointed at, and the store in hand dies with this
    // process. The three writes below are the ones that outlive it.
    let removed = store.remove(name)?;
    if !dry_run {
        if let Some(reference) = &removed.secret {
            vault.forget(reference)?;
        }
        store.save()?;
    }

    // The default must never name a destination the store no longer has, or the
    // next call with no name would fail on a setting the caller never touched.
    // It moves to whatever is left, and is cleared when nothing is.
    let still_marked = if marked == Some(name) {
        let next = store.list().first().map(|profile| profile.name.clone());
        if !dry_run {
            if let Some(name) = &next {
                crate::config::store::store(settings_file, "conn.default", name)?;
            } else {
                crate::config::store::remove(settings_file, "conn.default")?;
            }
        }
        next
    } else {
        marked.map(ToOwned::to_owned)
    };

    Ok(Envelope::new(
        "conn remove",
        json!({
            "removed": true,
            "name": removed.name,
            "secret_removed": removed.secret.is_some(),
            "default": still_marked,
            "simulated": dry_run,
        }),
    ))
}

/// Marks which destination applies when the caller names none.
pub(super) fn set_default(
    name: &str,
    store: &ProfileStore,
    settings_file: &std::path::Path,
    dry_run: bool,
) -> Result<Envelope> {
    // The store owns whether the name exists; the registry owns which one is
    // the default. Writing it in both places is what made `config set
    // conn.default` a value the work never read.
    store.ensure_exists(name)?;
    if !dry_run {
        crate::config::store::store(settings_file, "conn.default", name)?;
    }
    Ok(Envelope::new(
        "conn default",
        json!({ "default": name, "changed": true, "simulated": dry_run }),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::conn::tests::{settings_file_in, store_in, MemoryVault};
    use secrecy::SecretString;

    /// An edit changes exactly what it names and leaves the rest alone.
    #[test]
    fn an_edit_changes_only_what_it_names() {
        let mut profile = Profile {
            host: Some("old.example".to_owned()),
            user: Some("reader".to_owned()),
            database: Some("sales".to_owned()),
            ..Profile::named("main")
        };
        let fields = EditableFields {
            host: Some("new.example".to_owned()),
            read_only_profile: Some(true),
            ..nothing_named()
        };
        apply(&mut profile, &fields, None);
        assert_eq!(profile.host.as_deref(), Some("new.example"));
        assert_eq!(profile.user.as_deref(), Some("reader"));
        assert_eq!(profile.database.as_deref(), Some("sales"));
        assert!(profile.read_only);
    }

    /// An edit that names nothing, so a proof can name one field and mean it.
    fn nothing_named() -> EditableFields {
        EditableFields {
            host: None,
            port: None,
            socket: None,
            user: None,
            password_stdin: false,
            pin_database: None,
            read_only_profile: None,
            auth: None,
            client_cert: None,
            client_key: None,
            ca: None,
            require_tls: None,
            session_setup: Vec::new(),
        }
    }

    /// The identity a destination presents can be replaced where it was set.
    ///
    /// FR-080 names `conn edit` alongside `conn add` as the pair that carries
    /// the client certificate. Only `conn add` did, so the certificate could be
    /// written once and never rotated: replacing it meant deleting the profile
    /// and building it again, which the caller cannot do without the secret the
    /// profile was holding for them.
    #[test]
    fn the_identity_a_destination_presents_can_be_replaced() {
        let mut profile = Profile {
            client_cert: Some("old.pem".into()),
            client_key: Some("old.key".into()),
            ca: Some("old-ca.pem".into()),
            ..Profile::named("main")
        };
        let fields = EditableFields {
            client_cert: Some("new.pem".into()),
            client_key: Some("new.key".into()),
            ..nothing_named()
        };
        apply(&mut profile, &fields, None);
        assert_eq!(profile.client_cert.as_deref(), Some("new.pem".as_ref()));
        assert_eq!(profile.client_key.as_deref(), Some("new.key".as_ref()));
        // Named nothing, so it kept what it had rather than being reset.
        assert_eq!(profile.ca.as_deref(), Some("old-ca.pem".as_ref()));
    }

    /// The adjustments can be taken away, not only added to.
    ///
    /// An empty list is what an unmentioned flag already looks like, so without
    /// the spelled empty text below there would be no way to say "none" and the
    /// field would only ever grow.
    #[test]
    fn the_session_adjustments_can_be_cleared_as_well_as_replaced() {
        let mut profile = Profile {
            session_setup: vec!["SET a=1".to_owned()],
            ..Profile::named("main")
        };

        apply(&mut profile, &nothing_named(), None);
        assert_eq!(profile.session_setup, vec!["SET a=1".to_owned()], "unnamed");

        let replaced = EditableFields {
            session_setup: vec!["SET b=2".to_owned()],
            ..nothing_named()
        };
        apply(&mut profile, &replaced, None);
        assert_eq!(profile.session_setup, vec!["SET b=2".to_owned()]);

        let cleared = EditableFields {
            session_setup: vec![String::new()],
            ..nothing_named()
        };
        apply(&mut profile, &cleared, None);
        assert!(profile.session_setup.is_empty(), "the empty text clears");
    }

    /// Encryption keeps three states through an edit, as it has everywhere else.
    #[test]
    fn an_edit_can_say_a_destination_does_not_demand_encryption() {
        let mut profile = Profile {
            require_tls: Some(true),
            ..Profile::named("main")
        };
        apply(&mut profile, &nothing_named(), None);
        assert_eq!(profile.require_tls, Some(true), "silence changes nothing");

        let refused = EditableFields {
            require_tls: Some(false),
            ..nothing_named()
        };
        apply(&mut profile, &refused, None);
        assert_eq!(profile.require_tls, Some(false));
    }

    /// Removing a destination takes its secret with it, so nothing is left
    /// behind pointing at a server the caller deleted.
    #[test]
    fn removing_a_destination_takes_its_secret_with_it() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        let reference = SecretRef::for_profile("main");
        vault
            .store(&reference, &SecretString::from("hunter2"))
            .expect("stored");
        store
            .add(Profile {
                host: Some("db.example".to_owned()),
                secret: Some(reference.clone()),
                ..Profile::named("main")
            })
            .expect("added");

        let file = settings_file_in(directory.path());
        let envelope =
            remove("main", &mut store, &mut vault, Some("main"), &file, false).expect("removed");
        assert_eq!(envelope.data["secret_removed"], true);
        assert!(vault.load(&reference).expect("readable").is_none());
        assert!(store.list().is_empty());
    }

    /// Marking a default only accepts a name the store actually carries.
    #[test]
    fn the_default_may_only_be_a_stored_name() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let file = settings_file_in(directory.path());
        let failure = set_default("ghost", &store, &file, false).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Absence);

        store
            .add(Profile {
                host: Some("db.example".to_owned()),
                ..Profile::named("main")
            })
            .expect("added");
        let envelope = set_default("main", &store, &file, false).expect("marked");
        assert_eq!(envelope.data["default"], "main");
    }
}