Skip to content

Commit

Permalink
secrecy: have DebugSecret take a formatter (#467)
Browse files Browse the repository at this point in the history
Adds a `fmt::Formatter` argument to `DebugSecret::debug_secret`, making
it into a full-fledged equivalent of `Debug::fmt`, but without a `&self`
parameter which thereby ensures that there is no way to expose the
underlying secret value.

This makes it possible to change the default impl to use the recently
added `any::type_name` in order to display the *type* of the secret in
the debug message.
  • Loading branch information
tony-iqlusion authored Jul 8, 2020
1 parent d913267 commit 172efc9
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions secrecy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ pub use self::{boxed::SecretBox, string::SecretString, vec::SecretVec};
#[cfg(feature = "bytes")]
pub use self::bytes::SecretBytesMut;

use core::fmt::{self, Debug};
use core::{
any,
fmt::{self, Debug},
};

#[cfg(feature = "serde")]
use serde::{de, ser, Deserialize, Serialize};
Expand Down Expand Up @@ -155,7 +158,9 @@ where
S: Zeroize + DebugSecret,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Secret({})", S::debug_secret())
f.write_str("Secret(")?;
S::debug_secret(f)?;
f.write_str(")")
}
}

Expand Down Expand Up @@ -197,11 +202,14 @@ pub trait ExposeSecret<S> {

/// Debugging trait which is specialized for handling secret values
pub trait DebugSecret {
/// Information about what the secret contains.
/// Format information about the secret's type.
///
/// Static so as to discourage unintentional secret exposure.
fn debug_secret() -> &'static str {
"[REDACTED]"
/// This can be thought of as an equivalent to [`Debug::fmt`], but one
/// which by design does not permit access to the secret value.
fn debug_secret(f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("[REDACTED ")?;
f.write_str(any::type_name::<Self>())?;
f.write_str("]")
}
}

Expand Down

0 comments on commit 172efc9

Please sign in to comment.