0Pricing
AI Agents · Lesson

Secrets Rotation and Security

Secret expiry, rotation strategies, and vault solutions (AWS Secrets Manager).

Secrets Rotation and Security is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Secrets Need to Be Rotated

Even if a secret is never explicitly exposed, rotating it regularly limits the damage of an undetected breach. A key that was silently stolen 6 months ago becomes useless after rotation.

Many security standards (SOC 2, PCI-DSS) require periodic secret rotation. Building rotation-friendly agent code is a professional practice.

API Key Expiry Policies

Different providers have different expiry policies. Some allow you to set expiry dates on keys; others issue keys that never expire unless manually rotated. Audit your keys regularly and set calendar reminders for manual rotation.

# Key rotation schedule by provider (as of mid-2025):
# OpenAI: no automatic expiry, rotate manually every 90 days
# Anthropic: no automatic expiry, rotate manually every 90 days
# Google Cloud: API keys can have expiry dates set in the console
# AWS: IAM access keys: rotate every 90 days (AWS Security Hub recommends)
# Tavily: no automatic expiry, rotate when suspected compromise

# Best practices:
# - Set a recurring calendar event: 'Rotate API keys'
# - Document when each key was last rotated
# - Store rotation date in a secrets manager, not a spreadsheet
print('Schedule key rotation every 60-90 days as a standing task')

AWS Secrets Manager for Agents

AWS Secrets Manager stores secrets securely and supports automatic rotation. Your agent fetches the current secret value at runtime via the SDK — no hard-coded keys, no .env files in production.

# pip install boto3
import boto3
import json

def get_secret(secret_name: str, region: str = 'us-east-1') -> dict:
    client = boto3.client('secretsmanager', region_name=region)
    response = client.get_secret_value(SecretId=secret_name)
    return json.loads(response['SecretString'])

# Store secrets as JSON in Secrets Manager:
# Secret name: 'prod/myagent/api-keys'
# Secret value: {'OPENAI_API_KEY': 'sk-...', 'SEARCH_API_KEY': 'tvly-...'}

# Fetch at agent startup:
# secrets = get_secret('prod/myagent/api-keys')
# openai_key = secrets['OPENAI_API_KEY']

HashiCorp Vault for Secrets

HashiCorp Vault is an open-source secrets management system popular in enterprise environments. It supports dynamic secrets, fine-grained access control, and audit logging of every secret access.

# pip install hvac
import hvac
import os

def get_vault_secret(path: str, key: str) -> str:
    client = hvac.Client(
        url=os.environ['VAULT_ADDR'],
        token=os.environ['VAULT_TOKEN']  # from env, not hard-coded
    )

    if not client.is_authenticated():
        raise RuntimeError('Vault authentication failed')

    response = client.secrets.kv.read_secret_version(path=path)
    return response['data']['data'][key]

# Usage:
# openai_key = get_vault_secret('secret/myagent', 'OPENAI_API_KEY')

# Vault provides:
# - Audit log of every secret read
# - Lease-based secrets that expire automatically
# - Fine-grained ACL policies

Secret Scanning: truffleHog

truffleHog scans git repositories for secrets that may have been accidentally committed. It checks the entire commit history, not just the current code. Run it before making a repository public.

# pip install trufflehog
# Or: brew install trufflehog (Mac)

# Scan current git repository:
# trufflehog git file://.

# Scan only recent commits:
# trufflehog git file://. --since-commit HEAD~50

# Scan a GitHub repository:
# trufflehog github --repo https://github.com/yourorg/yourrepo

# truffleHog detects:
# - OpenAI API keys (sk-proj-...)
# - Anthropic keys (sk-ant-...)
# - AWS access keys (AKIA...)
# - Private keys (BEGIN RSA PRIVATE KEY)
# - And 700+ other secret patterns

print('Run truffleHog before open-sourcing any private repository')

git-secrets: Pre-Commit Protection

git-secrets is a git hook tool from AWS that blocks commits containing secrets matching configured patterns. It runs before each commit and rejects it if a secret pattern is found.

# Install:
# brew install git-secrets  (Mac)
# or: git clone https://github.com/awslabs/git-secrets && make install

# Set up in your repo:
# git secrets --install
# git secrets --register-aws  (adds AWS key patterns)

# Add custom patterns (e.g., OpenAI keys):
# git secrets --add 'sk-proj-[A-Za-z0-9_-]{48,}'

# Now attempting to commit a secret:
# git add agent.py  # file containing API key
# git commit -m 'add agent'
# [ERROR] Untracked secret found in agent.py
# Commit blocked!

print('git-secrets prevents secrets from ever entering git history')

What to Do If a Key Is Exposed

A step-by-step response plan for a compromised API key. Speed is critical — automated scanners harvest exposed keys within minutes of a commit.

# INCIDENT RESPONSE: Exposed API Key
#
# Step 1 (IMMEDIATE): Revoke the exposed key
#   OpenAI: platform.openai.com/api-keys -> Delete key
#   Anthropic: console.anthropic.com -> API Keys -> Delete
#   AWS: IAM console -> Access Keys -> Deactivate/Delete
#
# Step 2: Generate a new key
#   Create a replacement key with the same permissions
#
# Step 3: Update everywhere
#   - Local .env
#   - Staging environment
#   - Production environment (Secrets Manager / Vault)
#   - CI/CD secrets (GitHub Actions, GitLab CI)
#
# Step 4: Audit usage
#   - Check provider usage logs for unauthorized activity
#   - Check billing for unexpected charges
#
# Step 5: Prevent recurrence
#   - Add pattern to git-secrets
#   - Enable pre-commit hooks
print('Revoke first. Then rotate. Then audit. Then prevent.')

Detecting Unauthorized Usage

After rotating a key, check if it was used without authorization. Most providers offer usage logs and spending alerts that can reveal if a stolen key was used to make API calls.

import openai
import datetime

client = openai.OpenAI(api_key='YOUR_NEW_API_KEY')

# Check OpenAI usage for the past day
# (requires usage read permissions on the key)
def check_recent_usage():
    # OpenAI billing/usage dashboard: platform.openai.com/usage
    # Set up spending alerts: platform.openai.com/account/limits
    # - 'Email alert' when monthly spend exceeds $X

    print('Suspicious usage indicators to look for:')
    print('1. Spikes in token usage outside business hours')
    print('2. Requests from unexpected IP addresses')
    print('3. Models or endpoints you do not use')
    print('4. Unusual cost patterns')
    print('\nAlways set spending limits and alerts on new API keys')

check_recent_usage()

Setting Spending Limits on API Keys

Set hard spending limits on your API keys to cap the damage from a compromised key. Even if someone uses your key, they cannot run up an unlimited bill.

# OpenAI spending limits:
# platform.openai.com/account/limits
# - Set 'Monthly budget' (hard limit — API stops when reached)
# - Set 'Email notification threshold' (soft alert)

# Best practice for agent keys:
# - Development key: $5-10/month hard limit
# - Staging key: $20-50/month hard limit
# - Production key: Based on expected usage + 2x buffer
# - CI/CD test key: $5/month hard limit (mocks should handle most tests)

# Anthropic:
# console.anthropic.com -> Settings -> Spending Limits

# Use separate keys per environment so limits are independent
print('Spending limits cap the blast radius of a compromised key')

Principle of Least Privilege for Keys

Give each API key only the permissions it needs. A key that only reads data should not have write or delete permissions. Most providers support scoped or permission-limited keys.

# Principle of Least Privilege applied to agent API keys:

# OpenAI key scopes (if API allows scoped keys):
# - Read-only key: for logging/audit agents
# - Write key: for agents that create content
# - Admin key: NEVER use in agent code — only for management

# Tavily API:
# - Basic plan: limited search results
# - Research plan: more results, images
# Use the plan appropriate to the agent's needs

# AWS IAM for agents:
# Create a dedicated IAM role/user per agent with only the S3/DynamoDB
# paths it needs to read/write. No admin permissions.

# Rule: If the key is compromised, how much damage can be done?
# Minimize the answer through scoped permissions.
print('Least privilege limits blast radius of any single key compromise')

Building a Key Health Check

Validate that your API keys are still valid at agent startup. Catch expired or revoked keys immediately rather than failing mid-task after the agent has already consumed resources.

import openai

def check_openai_key_health(api_key: str) -> bool:
    try:
        client = openai.OpenAI(api_key=api_key)
        # Make a minimal API call to verify the key
        models = client.models.list()
        print(f'OpenAI key valid. {len(list(models))} models available.')
        return True
    except openai.AuthenticationError:
        print('ERROR: OpenAI API key is invalid or expired.')
        return False
    except openai.PermissionDeniedError:
        print('ERROR: API key lacks required permissions.')
        return False

# At agent startup:
# import os
# if not check_openai_key_health(os.environ['OPENAI_API_KEY']):
#     raise SystemExit('Cannot start: invalid API key')

Knowledge Check: Secrets Rotation and Security

Test your understanding of secrets rotation and security practices.

Recap: Secrets Rotation and Security

You now have a complete secrets security strategy for production agents:

  • Rotate API keys every 60-90 days as a standing practice
  • Use AWS Secrets Manager or HashiCorp Vault for production environments
  • Run truffleHog before open-sourcing any repository
  • Install git-secrets as a pre-commit hook to prevent accidental commits
  • If a key is exposed: revoke immediately, then rotate, then audit usage
  • Set spending limits on all API keys to cap damage from compromise
  • Apply least privilege — give each key only the permissions it needs

Frequently asked questions

Is the “Secrets Rotation and Security” lesson free?

Yes — the full text of “Secrets Rotation and Security” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Secrets Rotation and Security”?

Secret expiry, rotation strategies, and vault solutions (AWS Secrets Manager). You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Secrets Rotation and Security” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Environment Variables for Agents
  2. .env Files and python-dotenv
  3. Secrets Rotation and Security
  4. Configuration Profiles for Dev and Prod
← Back to AI Agents