Implement API key rotation mechanism
✓Works with OpenClaudeYou are a security engineer implementing API key rotation. The user wants to build a production-ready mechanism to automatically rotate API keys before expiration, maintain backward compatibility during rotation, and audit all key changes.
What to check first
- Verify your secret management system supports key versioning (e.g., AWS Secrets Manager, HashiCorp Vault, or environment variable storage with version tracking)
- Check if your API clients support multiple concurrent API keys or if you need a grace period strategy
- Confirm your database schema has fields for
key_hash,created_at,expires_at,status(active/inactive/revoked), androtation_id
Steps
- Design a rotation schedule using a cron job (e.g., rotate every 30 days, trigger 7 days before expiration)
- Generate new API keys with cryptographically secure random generation (minimum 32 bytes of entropy)
- Store the new key in your secrets manager with
status: pendingand a grace period end date - Update your API validation logic to accept both the current active key and the pending key during the grace period (typically 24-48 hours)
- Mark the old key as
inactiveafter the grace period expires and all client connections have migrated - Implement a cleanup job to delete revoked keys after a retention period (30+ days for audit trail)
- Log all rotation events with timestamp, key fingerprint (first 8 chars of hash), rotation reason, and performer identity
- Add monitoring alerts for rotation failures, orphaned keys, and unauthorized access attempts with old keys
Code
import hashlib
import secrets
import json
from datetime import datetime, timedelta
from typing import Optional, Dict
import logging
logger = logging.getLogger(__name__)
class APIKeyRotationManager:
def __init__(self, secret_store, db_connection, rotation_interval_days=30):
self.secret_store = secret_store # AWS Secrets Manager, Vault, etc.
self.db = db_connection
self.rotation_interval_days = rotation_interval_days
self.grace_period_hours = 48
def generate_api_key(self) -> str:
"""Generate a cryptographically secure API key"""
return "sk_" + secrets.token_urlsafe(32)
def hash_key(self, api_key: str) -> str:
"""Create a hash for storage (never store raw keys)"""
return hashlib.sha256(api_key.encode()).hexdigest()
def rotate_key(self, client_id: str, reason: str = "scheduled") -> Dict:
"""Execute full key rotation workflow"""
try:
# Step 1: Generate new key
new_key = self.generate_api_key()
new_key_hash = self.hash_key(new_key)
rotation_id = secrets.token_hex(8)
now = datetime.utcnow()
grace_until
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Security Skills
Other Claude Code skills in the same category — free to download.
Dependency Audit
Audit dependencies for known vulnerabilities
Secret Scanner
Scan codebase for leaked secrets and credentials
CSP Generator
Generate Content Security Policy headers
Input Sanitizer
Add input sanitization to prevent injection attacks
Auth Middleware
Create authentication middleware
RBAC Setup
Implement role-based access control
CSRF Protection
Add CSRF protection to forms and APIs
Security Headers
Configure security headers (HSTS, X-Frame-Options, etc.)
Want a Security skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.