mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The credential, and how it is kept from leaking.
//!
//! A secret is read from the input channel and never from a flag value, because
//! a flag value is visible in the process list of the whole machine. It is held
//! in memory that is wiped when dropped, it never appears in a diagnostic
//! rendering, and every place that would show it shows a redaction instead.

use crate::error::{Failure, Result};
use secrecy::{ExposeSecret as _, SecretString};
use std::io::Read;

/// What every rendering of a secret shows instead of the secret.
///
/// The mark is fixed rather than proportional to the secret, because a mark
/// that grew with the value would publish its length.
pub const REDACTION: &str = "********";

/// Replaces any value with a form that reveals neither its content nor its
/// length.
///
/// The empty value is the one exception worth telling apart, because "nothing
/// stored" and "something stored" are different states a caller must act on.
#[must_use]
pub fn redact(value: &str) -> String {
    if value.is_empty() {
        return String::new();
    }
    REDACTION.to_owned()
}

/// A credential held for the life of one invocation.
///
/// The wrapper exists so no caller can print the value by accident: it has no
/// rendering of its own beyond the redaction.
#[derive(Clone)]
pub struct Secret(SecretString);

impl Secret {
    /// Takes ownership of a credential already in memory.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(SecretString::from(value.into()))
    }

    /// Hands the credential to the one place that must see it.
    ///
    /// Every call site of this is a place a secret could leak, so there are
    /// deliberately few of them.
    #[must_use]
    pub fn expose(&self) -> &str {
        self.0.expose_secret()
    }

    /// Whether anything was actually given.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.expose_secret().is_empty()
    }

    /// What any rendering of this credential shows.
    #[must_use]
    pub fn redacted(&self) -> String {
        redact(self.0.expose_secret())
    }
}

impl std::fmt::Debug for Secret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Secret({})", self.redacted())
    }
}

impl std::fmt::Display for Secret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.redacted())
    }
}

/// Reads a credential from a reader, which is how it always arrives.
///
/// One trailing line ending is dropped, because a caller piping a line of text
/// did not mean the ending to be part of the credential.
///
/// # Errors
///
/// Returns a configuration failure when the input channel cannot be read.
pub fn read_from(source: &mut impl Read) -> Result<Secret> {
    let mut buffer = String::new();
    source.read_to_string(&mut buffer).map_err(|error| {
        Failure::config(
            "secret.unreadable",
            "the credential could not be read from the input",
        )
        .with_hint("pass the credential on the input channel, never as a flag value")
        .with_cause(error.to_string())
    })?;

    let trimmed = buffer.strip_suffix('\n').unwrap_or(&buffer);
    let trimmed = trimmed.strip_suffix('\r').unwrap_or(trimmed);
    Ok(Secret::new(trimmed))
}

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

    #[test]
    fn a_redaction_reveals_neither_content_nor_length() {
        let short = redact("a");
        let long = redact("a very long credential indeed");
        assert_eq!(short, long, "the mark must not grow with the value");
        assert!(!long.contains("credential"));
    }

    #[test]
    fn nothing_stored_is_told_apart_from_something_stored() {
        assert!(redact("").is_empty());
        assert!(!redact("x").is_empty());
    }

    #[test]
    fn a_diagnostic_rendering_never_carries_the_credential() {
        let secret = Secret::new("hunter2");
        assert!(!format!("{secret:?}").contains("hunter2"));
        assert!(!format!("{secret}").contains("hunter2"));
        assert!(format!("{secret:?}").contains(REDACTION));
    }

    /// FR-002. The credential arrives through the input channel, which is the
    /// half of the requirement this layer can carry: a value read from a
    /// stream was never an argument, so it was never in the process list.
    #[test]
    fn the_credential_is_read_from_the_input_channel() {
        let mut source = std::io::Cursor::new(b"hunter2\n".to_vec());
        let secret = read_from(&mut source).expect("reads");
        assert_eq!(
            secret.expose(),
            "hunter2",
            "the line ending is not part of it"
        );
    }

    #[test]
    fn an_input_carrying_a_windows_line_ending_is_read_the_same_way() {
        let mut source = std::io::Cursor::new(b"hunter2\r\n".to_vec());
        assert_eq!(read_from(&mut source).expect("reads").expose(), "hunter2");
    }

    #[test]
    fn an_empty_input_is_a_credential_that_was_not_given() {
        let mut source = std::io::Cursor::new(Vec::new());
        assert!(read_from(&mut source).expect("reads").is_empty());
    }
}