Answer#
Most leaks are accidents: a {:?} print of a config struct, an error message that includes a URL with a password in it. A newtype that refuses to print its content turns the accident into a harmless placeholder.
use std::fmt;
/// A value that never prints itself. The only way to read it is the explicit `expose` call.
struct Secret(String);
impl Secret {
fn from_env(name: &str) -> Option<Secret> {
std::env::var(name).ok().filter(|v| !v.is_empty()).map(Secret)
}
fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Secret(<redacted>)")
}
}
impl fmt::Display for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("<redacted>")
}
}
#[derive(Debug)]
struct Config {
api_url: String,
api_key: Secret,
}
fn main() {
let cfg = Config { api_url: "https://api.example.test".into(), api_key: Secret("sk-12345".into()) };
println!("{cfg:?}");
println!("key = {}", cfg.api_key);
println!("length = {}", cfg.api_key.expose().len());
println!("{}", Secret::from_env("A_NAME_THAT_IS_NOT_SET").is_none());
}Config { api_url: "https://api.example.test", api_key: Secret(<redacted>) }
key = <redacted>
length = 8
true(The compiler warns that api_url is never read in this demo; in a real program it would be used.)
How to do it#
- Store secrets in environment variables or a file outside the repository, and read them once at start-up.
- Wrap each in a type like
Secretand deriveDebugon the structs that hold it, as above. - Call
expose()only where the value is sent (an HTTP header, a database connection). - Do not put the secret in URLs (
https://user:password@host): URLs end up in logs and error messages. - Check
.gitignorefor the files that hold secrets, and rotate any key that was ever committed.
Common mistakes#
- Believing that a secret in an environment variable is safe from every log. It is only safe if nothing prints the environment.
- Implementing
CloneandSerializeforSecretwithout thinking: a serializer can write it out. Leave those off unless needed. - Deleting a leaked key from Git history and keeping it in use. Treat any leaked key as compromised and replace it.
Related questions#
Does a crate exist for this?#
Yes, crates such as secrecy provide a similar wrapper, and also clear the memory when it is dropped. The example above shows the idea in about twenty lines.
Sources#
- Standard library,
std::fmt::Debug: https://doc.rust-lang.org/std/fmt/trait.Debug.html