AI Agent Secret Management: The Hardcoded Key That Cost $50,000
API Key hardcoded in the code → accidentally pushed to GitHub → stolen and used by someone else → hit with a $50,000 bill next month. This isn't hypothetical—it's a real incident that actually happened.
📜 Table of Contents
📖 Keep reading
A leaked API key in a public repository is one of the more expensive mistakes in this field. The pattern repeats: a key committed to GitHub, scraped by automated bots within minutes, used until the bill arrives. The exact figures from any given incident are hard to verify, but the shape of the failure is not in doubt.

Three Principles
1. Never hard-code
API keys, database passwords, tokens — none of them belong in source code.
# wrong
api_key = "sk-xxxxx"
# right
import os
api_key = os.getenv("OPENAI_API_KEY")
2. Least privilege
If the agent only needs to read, do not give it write. If it calls one API, do not hand it a key that opens every API on the account. Scope keys per service and per operation, not per organisation.
3. Rotate on a schedule
Rotate every 90 days. Rotation does not prevent a leak; it caps how long a leaked key stays useful. A key that lives for a year is a year of exposure.
Where to Store Them
| Environment | Approach |
|---|---|
| Development | A .env file that never enters Git |
| Production | Environment variables, Vault, or a cloud secrets manager |
Multi-Environment Config
# config.yaml
development:
openai_key: ${DEV_OPENAI_KEY}
redis_url: localhost:6379
production:
openai_key: ${PROD_OPENAI_KEY}
redis_url: ${REDIS_URL}
Do not branch on environment inside your code. Let a settings library — python-decouple, pydantic-settings — inject the right values per environment.
Rotation
#!/bin/bash
# run every 90 days
NEW_KEY=$(openssl rand -hex 32)
export API_KEY=$NEW_KEY
echo "Key rotated at $(date)" >> /var/log/key-rotation.log
Rotation is only real if the old key stops working. Revoke at the provider, then deploy the new one, in that order — the script above generates a value, but the revocation step is what actually removes the exposure.
The Point
Never trust anything written into the code itself. Environment variables, a secrets manager, and scheduled rotation cover the three ways keys leak. None of them is exotic; the failures happen because the simplest path is also the most convenient one.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.