mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The one place on this surface that reads a secret.
//!
//! It reads from the standard input and never from a flag value, because a flag
//! value is visible in the process list of the whole machine.

use crate::error::{Failure, Result};
use secrecy::SecretString;

/// Reads one secret from the standard input.
///
/// The trailing line break a shell adds is dropped, because a caller piping a
/// secret from a file almost never means to include it, and a secret with an
/// invisible extra character fails in a way nobody can see.
///
/// # Errors
///
/// Returns a configuration failure when nothing can be read, or when what was
/// read is empty, since an empty secret is never what the caller meant.
pub(super) fn read_secret_from_standard_input(refuses_to_ask: bool) -> Result<SecretString> {
    use std::io::Read;

    // A secret typed at a terminal is the one read in this product that really
    // does wait for a person, so it is where `--no-input` has to bite.
    crate::settings::refuse_a_read_that_would_wait(refuses_to_ask, "a secret")?;

    let mut buffer = String::new();
    std::io::stdin()
        .read_to_string(&mut buffer)
        .map_err(|cause| {
            Failure::config(
                "secret.unreadable",
                "the secret could not be read from the standard input",
            )
            .with_hint(
                "pipe the secret in, as in `printf %s \"$SECRET\" | mariadb-cli conn add ...`",
            )
            .with_cause(cause.to_string())
        })?;

    let trimmed = buffer.trim_end_matches(['\n', '\r']);
    if trimmed.is_empty() {
        return Err(
            Failure::config("secret.empty", "the standard input carried no secret")
                .with_hint("pipe the secret in, or leave --password-stdin out"),
        );
    }
    Ok(SecretString::from(trimmed.to_owned()))
}