use crate::error::{Failure, Result};
use secrecy::{ExposeSecret as _, SecretString};
use std::io::Read;
pub const REDACTION: &str = "********";
#[must_use]
pub fn redact(value: &str) -> String {
if value.is_empty() {
return String::new();
}
REDACTION.to_owned()
}
#[derive(Clone)]
pub struct Secret(SecretString);
impl Secret {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(SecretString::from(value.into()))
}
#[must_use]
pub fn expose(&self) -> &str {
self.0.expose_secret()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.expose_secret().is_empty()
}
#[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())
}
}
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));
}
#[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());
}
}