Answer#
A secret that is compiled into the program or committed to Git is a secret you cannot rotate and cannot take back: everyone with the code or its history has it. Keep secrets outside the build and hand them to the process when it starts.
The two usual channels are an environment variable (DB_PASSWORD) and a file whose path is in a variable (DB_PASSWORD_FILE). Files are handy with secret managers and container platforms, which can mount a secret as a file with restricted permissions. A function that accepts both keeps the program independent of how it is deployed.
use std::{env, fs, io};
/// Read a secret from `NAME`, or from the file named by `NAME_FILE`. Never falls back to a default.
fn read_secret(name: &str) -> io::Result<String> {
if let Ok(path) = env::var(format!("{name}_FILE")) {
let text = fs::read_to_string(&path)?;
return Ok(text.trim_end_matches(['\r', '\n']).to_string());
}
env::var(name).map_err(|_| {
io::Error::new(io::ErrorKind::NotFound, format!("{name} (or {name}_FILE) is not set"))
})
}
fn main() -> io::Result<()> {
// Demonstration only: a real deployment points DB_PASSWORD_FILE at a file the host protects.
let dir = std::env::temp_dir();
let file = dir.join("demo-db-password.txt");
fs::write(&file, "s3cret-value\r\n")?;
env::set_var("DB_PASSWORD_FILE", &file);
let password = read_secret("DB_PASSWORD")?;
println!("read {} characters", password.chars().count());
match read_secret("API_TOKEN") {
Ok(_) => println!("unexpected"),
Err(e) => println!("error: {e}"),
}
fs::remove_file(file)
}read 12 characters
error: API_TOKEN (or API_TOKEN_FILE) is not set(std::env::set_var is used only to make the demonstration self-contained; a real program never sets its own secrets.)
How to do it#
- Decide the names once (
NAMEandNAME_FILE) and document them for whoever deploys the program. - Read secrets once at start-up and keep them in a struct; do not re-read the environment all over the code.
- Return an error that names the missing setting, not its content.
- Put the secret file outside the repository, readable by the service account only.
- Never put a secret in a command-line argument: other users on the machine can often see the process arguments.
Common mistakes#
- Providing a default such as
"changeme""for development". It will reach production one day. Fail instead; see the thread on refusing to start. - Treating environment variables as private from everything. A crash report, a debug endpoint or a child process can expose them.
- Forgetting the trailing newline that most editors add to a secret file, which makes a correct password fail to match.
Related questions#
Is a .env file acceptable?#
For local development, yes, if it is listed in .gitignore. In production prefer what your host offers for secrets. A .env file is just a file; it has no extra protection.
How do I stop the secret from showing up in logs?#
Wrap it in a type that prints a placeholder, as in the thread "How do I keep API keys and passwords out of logs and error messages?".
Sources#
- The Twelve-Factor App, "Config": https://12factor.net/config
- OWASP Secrets Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
- Standard library,
std::env::var: https://doc.rust-lang.org/std/env/fn.var.html