Home / Blog

ARTICLE Comparison

Are API keys in environment variables safe for AI agents?

PastKeys · October 2026

"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.

PropertyKey in env varBrokered operation
Secret in agent processYesNo
Exposed to prompt injectionYesNo usable key to leak
Scope of a leakFull key, long-livedOne operation, expiring
Per-operation policyNoYes, default-deny
Audit of every useRarelyYes
Instant revocationRotate the key everywhereRevoke or lock down centrally
Env vars are not evil. They are the wrong layer to rely on when the process holding the secret is an agent.

For the full pattern see secrets management for AI agents, or get started with PastKeys.

Stop handing agents long-lived secrets.Zero-access custody, default-deny policy, short-lived credentials.

Create an accountRead the whitepaper