env-reader 0.1.0

Read configuration from environment variables: blank is absent, every problem is reported at once, and a secret never prints.
Documentation
//! A configuration value that must not be printed.

use std::fmt;

/// What a secret renders as, everywhere.
const MASK: &str = "<redacted>";

/// A configuration value that never appears in output.
///
/// Wraps a connection string, a password, a shared access key or an API
/// key. Both [`Debug`] and [`Display`] render `<redacted>`; the value comes
/// out only through [`Secret::expose`], which is deliberately awkward to
/// type and easy to grep for.
///
/// # Why both `Debug` and `Display`
///
/// Deriving `Debug` on a configuration struct is the normal thing to do,
/// and the resulting line ends up in a log eventually. Masking `Debug`
/// alone is the common half-measure: it leaves `format!("{secret}")` and
/// every `Display`-based logging macro wide open. This type masks both.
///
/// # Examples
///
/// ```
/// use env_reader::Secret;
///
/// #[derive(Debug)]
/// struct Config {
///     endpoint: String,
///     access_key: Secret,
/// }
///
/// let config = Config {
///     endpoint: "sb://example".into(),
///     access_key: Secret::new("hunter2"),
/// };
///
/// let printed = format!("{config:?}");
/// assert!(printed.contains("sb://example"));
/// assert!(!printed.contains("hunter2"));
/// assert_eq!(config.access_key.expose(), "hunter2");
/// ```
///
/// # `PartialEq` compares in ordinary time
///
/// It is derived, so a comparison is not constant-time. That is right for
/// what this type is for — comparing two *configurations*, usually in a
/// test — and wrong for checking a presented credential against a stored
/// one. Do not use it for the latter.
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);

impl Secret {
    /// Wrap a value.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Secret;
    ///
    /// assert_eq!(Secret::new("hunter2").to_string(), "<redacted>");
    /// ```
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// The value itself.
    ///
    /// Named to be conspicuous at a call site and in a code review: every
    /// use of it is a place a secret leaves this type.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Secret;
    ///
    /// assert_eq!(Secret::new("hunter2").expose(), "hunter2");
    /// ```
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.0
    }

    /// The value itself, consuming this.
    ///
    /// For handing ownership to a client library that wants a `String`.
    #[must_use]
    pub fn into_exposed(self) -> String {
        self.0
    }

    /// Whether the wrapped value is empty.
    ///
    /// Lets a caller branch on "is this configured" without exposing it.
    ///
    /// # Examples
    ///
    /// ```
    /// use env_reader::Secret;
    ///
    /// assert!(Secret::new("").is_empty());
    /// assert!(!Secret::new("hunter2").is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// How long the wrapped value is, in bytes.
    ///
    /// The one measurement this type will report. Enough to tell a
    /// truncated key from an absent one in a log line, and nothing more.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(MASK)
    }
}

impl fmt::Display for Secret {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(MASK)
    }
}

impl From<String> for Secret {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for Secret {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

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

    /// A value distinctive enough that finding it anywhere is unambiguous.
    const MARKER: &str = "SharedAccessKey=NEEDLE-9f2c";

    #[test]
    fn debug_does_not_print_the_value() {
        let printed = format!("{:?}", Secret::new(MARKER));
        assert_eq!(printed, MASK);
        assert!(!printed.contains("NEEDLE"));
    }

    #[test]
    fn display_does_not_print_the_value() {
        assert!(!Secret::new(MARKER).to_string().contains("NEEDLE"));
        // The half-measure this type exists to avoid: masking `Debug` only
        // leaves every `Display`-based logging macro wide open.
        assert!(!format!("{}", Secret::new(MARKER)).contains("NEEDLE"));
    }

    #[test]
    fn a_secret_inside_a_derived_debug_stays_hidden() {
        // The case that actually happens. The fields are read by the
        // derived `Debug` and nowhere else, which is what this test is
        // about.
        #[derive(Debug)]
        #[allow(dead_code)]
        struct Config {
            /// A field whose presence proves the rest of the struct printed.
            queue: &'static str,
            /// The field under test.
            key: Secret,
        }

        let printed = format!(
            "{:?}",
            Config {
                queue: "orders",
                key: Secret::new(MARKER),
            }
        );
        assert!(printed.contains("orders"));
        assert!(!printed.contains("NEEDLE"));
    }

    #[test]
    fn the_value_is_reachable_when_asked_for() {
        assert_eq!(Secret::new(MARKER).expose(), MARKER);
        assert_eq!(Secret::new(MARKER).into_exposed(), MARKER);
    }

    #[test]
    fn a_length_is_reportable_but_the_content_is_not() {
        let secret = Secret::new(MARKER);
        assert_eq!(secret.len(), MARKER.len());
        assert!(!secret.is_empty());
        assert!(Secret::new("").is_empty());
    }

    #[test]
    fn conversion_from_the_usual_string_types() {
        assert_eq!(Secret::from("x").expose(), "x");
        assert_eq!(Secret::from(String::from("y")).expose(), "y");
    }
}