AI Skill Library

Secrets Management

Environment variables, .env files, secret vaults, rotation, CI/CD secrets.

securitydevopsbackend
# Secrets Management

## Environment variables (.env)
```bash
# .env.local (NEVER commit)
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
JWT_SECRET=super-secret-key
ADMIN_API_KEY=random-64-char-hex
```
```ts
// Load with dotenv or framework built-in
import 'dotenv/config'
const dbUrl = process.env.DATABASE_URL
if (!dbUrl) throw new Error('DATABASE_URL is required')
```

## .gitignore essentials
```
.env
.env.*
*.pem
*.key
*.p12
serviceAccountKey.json
```

## Generate strong secrets
```bash
# Random hex (64 chars)
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# Random base64
openssl rand -base64 32
```

## Cloud secret managers
```ts
// AWS Secrets Manager
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager'
const client = new SecretsManagerClient({})
const { SecretString } = await client.send(
  new GetSecretValueCommand({ SecretId: 'prod/myapp/db' })
)
```
Alternatives: Azure Key Vault, GCP Secret Manager, HashiCorp Vault, Doppler.

## CI/CD secrets
```yaml
# GitHub Actions
jobs:
  deploy:
    env:
      DATABASE_URL: ${{ secrets.DATABASE_URL }}
      JWT_SECRET: ${{ secrets.JWT_SECRET }}
```
Never echo secrets in logs. Use `::add-mask::` in GitHub Actions.

## Key rotation
1. Generate new secret.
2. Update application to accept BOTH old and new.
3. Deploy.
4. Revoke old secret.
5. Remove old secret from config.

## Checklist
- [ ] No secrets in source code or git history.
- [ ] `.env` files in `.gitignore`.
- [ ] Different secrets per environment (dev/staging/prod).
- [ ] Secrets encrypted at rest in CI/CD.
- [ ] Rotate secrets on team member departure.
- [ ] Audit: `git log --all -p -S 'password'` to check history.
- [ ] Use `git-secrets` or `trufflehog` to scan for leaked secrets.

API: /api/skills/secrets-management