Guide

How to store API keys in Rust safely

In Rust, read secrets with std::env::var, which returns a Result so a missing variable is handled explicitly. Use the dotenvy crate for .env files in development, and wrap sensitive values in the secrecy crate's SecretString so they are not printed by accident.

Read the key from the environment

use std::env;

fn main() {
    let api_key = env::var("STRIPE_SECRET_KEY")
        .expect("STRIPE_SECRET_KEY must be set");
    // pass api_key to your client; never print it
    let _ = api_key;
}

Local development

Add dotenvy and call dotenvy::dotenv().ok(); at the top of main to load a git-ignored .env in development. Keep real production keys out of that file. For types that hold secrets, secrecy::SecretString redacts its Debug output and zeroises memory on drop, and you call expose_secret() only at the point of use.

Production

Provide variables through your deployment platform's secret store or mount secret files and read them at start-up. Do not use env! or option_env! for secrets: those macros read variables at compile time and bake the value into the binary. Use std::env::var at run time instead.

Mistakes to avoid

  • Using env!("KEY") or include_str! on a secrets file, which embeds the value in the compiled binary.
  • Deriving Debug on a config struct that holds a plain String secret, so {:?} or a panic message prints it; use SecretString.
  • Using unwrap() on env::var in library code, which turns a missing variable into an unexplained panic.
  • Committing .env or leaving secrets in Cargo.toml build scripts and CI logs.

When an AI agent works on your Rust project

Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.

Frequently asked questions

How do I read an environment variable in Rust?

Call std::env::var("NAME"), which returns Result<String, VarError>. Handle the error or use expect at start-up with a clear message.

How do I stop a Rust secret printing in logs?

Wrap it in secrecy::SecretString, which hides its value in Debug output, and only call expose_secret() where the value is actually used.

Should I keep API keys in a .env file for Rust?

A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.

Other languages and frameworks

Give agents access. Keep the keys.

BotPassword is in early access. Request an invite and we'll email you when your spot opens.