Protecting API Keys and Credentials in AI Agent Deployments
Best practices for securing API keys and credentials in AI agent deployments. Covers secrets management, environment variables, credential rotation, and monitoring.
Why AI Agents Are High-Value Targets
AI agents are uniquely attractive targets for attackers because they're a one-stop shop for valuable credentials:
| Credential Type | Value to Attacker | |-----------------|-------------------| | Anthropic/OpenAI API keys | Unlimited AI access, massive bills | | Discord/Telegram tokens | Bot takeover, spam, phishing | | Database credentials | Data theft, ransomware | | Payment API keys | Financial fraud | | OAuth tokens | Account takeover |
A single compromised AI agent can expose credentials worth thousands of dollars in unauthorized usage.
The "Butler Problem"
AI agents face a fundamental security tension: they need access to many services to be useful, but this concentrated access creates risk.
Think of it like a butler with keys to every room in the house:
- Too much access → One compromise exposes everything
- Too little access → Agent can't do its job
The solution isn't to limit access, but to protect credentials properly and detect unauthorized use quickly.
Secrets Management Best Practices
1. Never Store Secrets in Code
Wrong:
const client = new Anthropic({
apiKey: 'sk-ant-api03-xxxxx' // Never do this!
});
Right:
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
Secrets in code end up in:
- Git history (even if deleted later)
- Backups
- Log files
- Error reports
2. Use Environment Variables
Create a .env file with restricted permissions:
# Create the file
touch .env
# Set restrictive permissions (owner read/write only)
chmod 600 .env
Example .env file:
# API Keys
ANTHROPIC_API_KEY=sk-ant-xxxxx
OPENAI_API_KEY=sk-xxxxx
# Discord
DISCORD_TOKEN=xxxxx
DISCORD_CLIENT_ID=xxxxx
DISCORD_CLIENT_SECRET=xxxxx
# Database
DATABASE_URL=postgres://user:pass@localhost:5432/botdb
# Other Services
STRIPE_SECRET_KEY=sk_live_xxxxx
3. Add .env to .gitignore
echo ".env" >> .gitignore
echo ".env.local" >> .gitignore
echo ".env.production" >> .gitignore
echo "*.pem" >> .gitignore
echo "*.key" >> .gitignore
4. Use a .env.example File
Create a template without real values:
# .env.example - Copy to .env and fill in values
ANTHROPIC_API_KEY=your-anthropic-key-here
DISCORD_TOKEN=your-discord-token-here
DATABASE_URL=postgres://user:pass@localhost:5432/dbname
Loading Environment Variables
Node.js with dotenv
npm install dotenv
// Load at the very start of your app
require('dotenv').config();
// Or in ES modules
import 'dotenv/config';
// Access variables
const apiKey = process.env.ANTHROPIC_API_KEY;
Python with python-dotenv
pip install python-dotenv
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv('ANTHROPIC_API_KEY')
Credential Rotation
Regular rotation limits the damage from undetected compromises.
Rotation Schedule
| Credential Type | Rotation Frequency | |-----------------|-------------------| | API keys | Every 90 days | | Database passwords | Every 90 days | | Bot tokens | Every 90 days | | SSH keys | Annually | | After incident | Immediately |
Rotation Process
- Generate new credential in the service dashboard
- Update
.envfile with new credential - Restart the bot to pick up new values
- Verify functionality with the new credential
- Revoke old credential in the service dashboard
# Update .env
nano .env
# Restart bot
pm2 restart openclaw
# Verify it's working
pm2 logs openclaw --lines 20
Keep Old Credentials Temporarily
Don't revoke old credentials immediately. Wait until you confirm:
- New credentials work
- No other services depend on old credentials
- Logs show successful authentication
Monitoring for Unauthorized Access
API Usage Monitoring
Check service dashboards regularly:
- Anthropic Console - console.anthropic.com
- OpenAI Usage - platform.openai.com/usage
- Discord Insights - In Discord Developer Portal
Look for:
- Usage outside normal hours
- Unusual request patterns
- Higher than expected costs
Set Up Usage Alerts
Most API providers offer usage alerts:
Anthropic:
- Set spend limits in Console
- Enable email notifications for usage thresholds
OpenAI:
- Configure usage limits
- Set up billing alerts
Log Analysis
Monitor your bot logs for authentication issues:
# Watch for auth errors
pm2 logs openclaw | grep -i "auth\|401\|403\|unauthorized"
# Check for unusual patterns
pm2 logs openclaw | grep -i "error" | tail -50
Access Control Principles
Principle of Least Privilege
Each component should have only the permissions it needs:
# Separate keys for different environments
ANTHROPIC_API_KEY_DEV=sk-ant-dev-xxxxx
ANTHROPIC_API_KEY_PROD=sk-ant-prod-xxxxx
Separate Development and Production
Never use production credentials in development:
- Create separate API keys for dev/prod
- Use different Discord bots for testing
- Use separate database instances
Service-Specific Keys
When possible, create purpose-specific credentials:
- One Discord bot for testing
- One Discord bot for production
- Separate API keys per service integration
File Permission Security
Secure .env File
# Restrict to owner only
chmod 600 .env
# Verify permissions
ls -la .env
# Should show: -rw------- (600)
Secure Config Directory
# Create secure config directory
mkdir -p /opt/openclaw/config
chmod 700 /opt/openclaw/config
# Set ownership to service user
chown -R botservice:botservice /opt/openclaw
Check for Exposed Files
# Find world-readable .env files
find / -name ".env" -perm -004 2>/dev/null
# Find config files with sensitive data
find /opt -name "config.json" -perm -004 2>/dev/null
Secrets in Docker
If running in Docker, never put secrets in:
- Dockerfiles
- docker-compose.yml
- Build arguments
Use Docker secrets or environment files:
# docker-compose.yml
services:
bot:
image: openclaw
env_file:
- .env
Or use Docker secrets for swarm mode:
services:
bot:
secrets:
- anthropic_key
secrets:
anthropic_key:
external: true
Advanced: Secrets Managers
For larger deployments, consider dedicated secrets managers:
HashiCorp Vault
# Store a secret
vault kv put secret/openclaw anthropic_key=sk-ant-xxxxx
# Retrieve in application
vault kv get -field=anthropic_key secret/openclaw
AWS Secrets Manager
const { SecretsManager } = require('@aws-sdk/client-secrets-manager');
const client = new SecretsManager({ region: 'us-east-1' });
const secret = await client.getSecretValue({ SecretId: 'openclaw/prod' });
Cloud Provider Solutions
- AWS Secrets Manager
- Google Cloud Secret Manager
- Azure Key Vault
- Doppler
- 1Password Secrets Automation
What to Do If Credentials Are Compromised
Immediate Actions
- Rotate compromised credentials immediately
- Check usage logs for unauthorized access
- Review conversation history for data exposure
- Check for persistent access (new API keys created by attacker)
- Notify affected parties if data was exposed
Post-Incident
- Audit all credentials - rotate everything if unsure of scope
- Review access controls - how did the compromise happen?
- Improve monitoring - add alerts for unusual activity
- Document the incident - for future reference
Credential Security Checklist
- [ ] All secrets in environment variables, not code
- [ ]
.envfile has 600 permissions - [ ]
.envis in.gitignore - [ ]
.env.exampleexists without real values - [ ] Separate credentials for dev/prod
- [ ] Rotation schedule established
- [ ] Usage monitoring enabled
- [ ] Alerts configured for unusual activity
- [ ] Recovery plan documented
Professional Credential Management
Managing credentials properly requires constant vigilance. Our maintenance plans include:
- Regular credential rotation
- Usage monitoring and alerts
- Security audits
- Immediate response to compromises
Contact us to secure your AI agent deployment.
Related Guides
Need a VPS for Your Bot?
We recommend Hostinger KVM 2 VPS - reliable, fast, and perfect for AI chatbots. Get started with our recommended setup.
Get Hostinger VPSNeed Help With Setup?
Got your VPS? Let us handle the technical work. Professional setup and maintenance for OpenClaw (formerly Clawd.bot).