> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agents-squads.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Secrets Management

> Securely handle API keys, tokens, and sensitive configuration

## Principles

1. **Never commit secrets** to version control
2. **Centralize secrets** in one secure location
3. **Use environment variables** for runtime access
4. **Rotate regularly** and audit access

## Environment Variables

### Structure

```
project/
├── .env              # Local secrets (git-ignored)
├── .env.example      # Template (committed)
└── .gitignore        # Must include .env
```

### .env.example Template

```bash theme={null}
# API Keys
ANTHROPIC_API_KEY=your-key-here
OPENAI_API_KEY=your-key-here

# Service Credentials
DATABASE_URL=postgres://user:pass@host:5432/db
REDIS_URL=redis://localhost:6379

# Feature Flags
DEBUG=false
LOG_LEVEL=info
```

### Loading Environment Variables

```bash theme={null}
# In shell
source .env

# Or use dotenv in code
npm install dotenv
```

```javascript theme={null}
// index.js
require('dotenv').config();
const apiKey = process.env.ANTHROPIC_API_KEY;
```

## Git Safety

### Essential .gitignore

```gitignore theme={null}
# Secrets
.env
.env.local
.env.*.local
*.pem
*.key
credentials.json
secrets/

# IDE
.idea/
.vscode/settings.json

# OS
.DS_Store
Thumbs.db
```

### Pre-commit Hook

Prevent accidental commits of secrets:

```bash theme={null}
#!/bin/sh
# .git/hooks/pre-commit

# Check for potential secrets
if git diff --cached --name-only | xargs grep -l -E "(API_KEY|SECRET|PASSWORD|TOKEN)=.+" 2>/dev/null; then
  echo "ERROR: Potential secrets detected in staged files"
  exit 1
fi
```

## Cloud Secrets Management

### Google Cloud Secret Manager

```bash theme={null}
# Create secret
gcloud secrets create my-api-key --data-file=./secret.txt

# Access in code
gcloud secrets versions access latest --secret=my-api-key

# Use in Cloud Run
gcloud run services update my-service \
  --set-secrets=API_KEY=my-api-key:latest
```

### Environment-Specific Secrets

```
production/
├── secrets/           # Stored in cloud secret manager
└── .env.production    # Non-sensitive config

development/
├── .env.local         # Local development secrets
└── .env.development   # Non-sensitive config
```

## Agent-Specific Patterns

### Centralized .env in HQ

```
agents-squads/
├── hq/
│   └── .env          # All secrets here
├── engineering/
│   └── (references hq/.env)
└── website/
    └── (references hq/.env)
```

### Accessing Secrets in Agents

```markdown theme={null}
# Agent: Deploy Service

## Prerequisites
- GOOGLE_CLOUD_PROJECT set in environment
- ANTHROPIC_API_KEY available

## Instructions
1. Load environment: `source ../hq/.env`
2. Run deployment: `gcloud run deploy ...`
```

### MCP Server Credentials

```json theme={null}
{
  "mcpServers": {
    "supabase": {
      "command": "npx",
      "args": ["-y", "@supabase/mcp-server"],
      "env": {
        "SUPABASE_ACCESS_TOKEN": "${SUPABASE_ACCESS_TOKEN}"
      }
    }
  }
}
```

## Audit & Rotation

### Regular Rotation Schedule

| Secret Type        | Rotation Frequency |
| ------------------ | ------------------ |
| API Keys           | 90 days            |
| Database passwords | 30 days            |
| Service accounts   | 180 days           |
| Access tokens      | 24 hours (auto)    |

### Audit Checklist

<Check>
  * [ ] All .env files are git-ignored
  * [ ] No secrets in commit history
  * [ ] .env.example exists with placeholders
  * [ ] Production secrets in secure manager
  * [ ] Rotation schedule documented
  * [ ] Access logs reviewed monthly
</Check>

## Emergency Response

### If Secrets Are Leaked

1. **Immediately rotate** the compromised credentials
2. **Revoke** any active sessions
3. **Audit** access logs for unauthorized use
4. **Clean** git history if committed:

```bash theme={null}
# Remove from history (requires force push)
git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch .env" \
  --prune-empty --tag-name-filter cat -- --all
```

5. **Update** all systems using the credential
6. **Document** the incident

<Warning>
  **Force pushing rewrites history** - coordinate with your team before running `git filter-branch` or `git push --force`.
</Warning>

## Best Practices

<Check>
  * Use `.env.example` for documentation
  * Never log or print secrets
  * Use secret managers in production
  * Implement least-privilege access
  * Automate rotation where possible
  * Encrypt secrets at rest
</Check>

## Related

<CardGroup cols={2}>
  <Card title="MCP Configuration" icon="plug" href="/guides/mcp-configuration">
    Configure external service connections
  </Card>

  <Card title="Hooks" icon="webhook" href="/guides/hooks">
    Automate security checks
  </Card>
</CardGroup>
