Skip to content

Commit 172efc9

Browse files
secrecy: have DebugSecret take a formatter (#467)
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.
1 parent d913267 commit 172efc9

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

secrecy/src/lib.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ pub use self::{boxed::SecretBox, string::SecretString, vec::SecretVec};
9898
#[cfg(feature = "bytes")]
9999
pub use self::bytes::SecretBytesMut;
100100

101-
use core::fmt::{self, Debug};
101+
use core::{
102+
any,
103+
fmt::{self, Debug},
104+
};
102105

103106
#[cfg(feature = "serde")]
104107
use serde::{de, ser, Deserialize, Serialize};
@@ -155,7 +158,9 @@ where
155158
S: Zeroize + DebugSecret,
156159
{
157160
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158-
write!(f, "Secret({})", S::debug_secret())
161+
f.write_str("Secret(")?;
162+
S::debug_secret(f)?;
163+
f.write_str(")")
159164
}
160165
}
161166

@@ -197,11 +202,14 @@ pub trait ExposeSecret<S> {
197202

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

0 commit comments

Comments
 (0)