pub struct SecretString(/* private fields */);Expand description
A string wrapper that masks its value when printed via Debug or
Display, to prevent secrets (API keys, tokens,
passwords, …) from accidentally ending up in logs or error messages.
The real value is reachable only through
expose_secret, which is what makes an
audit of where a secret escapes a grep rather than a reading of every
call site.
This is the Rust analogue of upstream’s SecretString, which upstream
#8127 rewrote from a str subclass into a wrapper for the same reason:
the subclass masked repr() while every other path — str(), f-strings,
concatenation, JSON encoding — silently produced the secret. Rust has no
implicit string coercions, so Debug and Display are the equivalent
surface, and both are masked here.
§It deliberately does not implement Serialize
A Serialize impl would put the secret in cleartext into anything a
caller encodes a config struct into — a log line, a checkpoint, an HTTP
body — with no call site to audit, which is the whole failure the type
exists to prevent. Upstream reached the same conclusion from the other
side: since #8127 a SecretString rejects JSON encoding rather than
exposing its value.
A masked Serialize is not the alternative: it would round-trip
"***" back as the value and silently replace the secret with the mask.
So #[derive(Serialize)] on a struct holding one fails to compile — at
which point the author decides what to write instead, which is the point.
Deserialize is kept: reading a secret in from a config file is what
the type is for.
Implementations§
Source§impl SecretString
impl SecretString
Sourcepub fn new(value: impl Into<String>) -> SecretString
pub fn new(value: impl Into<String>) -> SecretString
Wrap value as a SecretString.
Sourcepub fn expose_secret(&self) -> &str
pub fn expose_secret(&self) -> &str
Return the real, unmasked value.
Named to match upstream’s get_secret_value() / the common Rust
secrecy-crate convention, and to make call sites grep-able for
audits of where secrets are actually exposed.
Trait Implementations§
Source§impl Clone for SecretString
impl Clone for SecretString
Source§fn clone(&self) -> SecretString
fn clone(&self) -> SecretString
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more