Are API keys in environment variables safe for AI agents?
"Put it in an environment variable" is the default advice for API keys, and for a normal service it is reasonable. For an AI agent it quietly fails, because the thing reading the environment is driven by a model that untrusted input can influence. The env var is not the problem; giving the agent's process a usable long-lived key is.
What env vars do and do not protect against
An environment variable keeps a secret out of source control and off the command line. Good. It does nothing about what happens once the process reads it, and for an agent that is the whole risk:
- The value is in process memory, reachable by any code path the agent can be steered into.
- Prompt injection can make the agent print or transmit it.
- Agent frameworks log and persist context, so the key spreads to logs, traces, and memory stores.
- The key is typically long-lived and broadly scoped, so one leak is lasting, wide access.
Things that help a little
- A secret manager instead of a raw env var. Better storage and rotation, but once fetched the plaintext is in the agent's process, exposed the same ways.
- Scoping the key down. Worth doing, but most provider keys cannot be scoped to a single operation, and a narrowed key is still long-lived.
- Output filters. Useful defense in depth, not a guarantee.
The approach that actually changes the risk
Do not give the agent a usable key at all. Put a broker between the agent and the provider: the agent requests an operation, the broker performs it with a credential the agent cannot read, and returns the result. The credential is scoped to that operation and short-lived where the provider allows it.
| Property | Key in env var | Brokered operation |
|---|---|---|
| Secret in agent process | Yes | No |
| Exposed to prompt injection | Yes | No usable key to leak |
| Scope of a leak | Full key, long-lived | One operation, expiring |
| Per-operation policy | No | Yes, default-deny |
| Audit of every use | Rarely | Yes |
| Instant revocation | Rotate the key everywhere | Revoke or lock down centrally |
For the full pattern see secrets management for AI agents, or get started with PastKeys.