Ana Sayfa / Blog / API key rotation stratejileri: 4 senaryoda uygulama

API key rotation stratejileri: 4 senaryoda uygulama

API key leak olursa ne olur? Rotation yapılmıyorsa yıllar süren risk. 4 gerçek senaryoda pratik rotation.

API key’ler modern web ekosisteminin temel access token’ları. Stripe secret key, Twilio auth token, AWS access key, Firebase service account. Her biri leak olsa ciddi risk.

Ama çoğu ekip API key rotation yapmıyor. “İşe yarıyorsa dokunma” mantalitesi. Leak olsun, bir süre bilmeyin, unauthorized kullanım birikir.

Bu yazıda 4 farklı senaryoda API key rotation stratejilerini anlatacağım.

Neden rotation önemli?

Key leak senaryoları:
– Git repository’ye kazayla commit
– Developer laptop çalındı
– Slack/Discord’da message olarak
– Log dosyasında plaintext
– Employee ayrıldı, erişimi hâlâ active
– Build system’de environment variable exposed
– Third-party SDK’nın compromise’i

Her biri gerçekleşebilir. Rotation compromise window’unu limit ediyor.

Senaryo 1: Compromised key (emergency rotation)

Key leak olduğu ortaya çıktı. Immediate action.

Process:

  1. Revoke old key. Provider dashboard’dan immediately disable.
  2. Generate new key. Same privilege level.
  3. Deploy new key. Production secrets update.
  4. Verify functionality. Smoke tests pass.
  5. Audit usage logs. Old key kullanım history, suspicious activity var mı?
  6. Post-mortem. Leak nasıl oldu, prevent için actions.

Toplam: 15 dakika – 2 saat. Speed critical.

Tools needed:
– Secrets management system (Vault, AWS Secrets Manager)
– CI/CD pipeline (new secret deploy için)
– Monitoring dashboard (verify functionality)

Manuel process’te hazırlıksız ekip saat kaybediyor. Automation şart.

Senaryo 2: Scheduled rotation (proactive)

Regular rotation schedule. Leak olmasa bile.

Typical intervals:
– High-privilege keys: 30-60 days
– Standard keys: 90 days
– Low-risk keys: 180 days

Process:

  1. Generate new key. Old key hâlâ active.
  2. Deploy new key to secondary slot. Code’da primary + secondary key support.
  3. Verify secondary works. Test request’ler new key ile.
  4. Swap primary and secondary. New key now primary.
  5. Wait safety period. 24-48 saat, dependent systems propagation.
  6. Revoke old key.

Zero-downtime. Both keys active transition period.

Code pattern:

def get_api_key():
    primary = os.getenv('API_KEY_PRIMARY')
    secondary = os.getenv('API_KEY_SECONDARY')
    
    # Prefer primary, fallback to secondary
    return primary or secondary

Some APIs multi-key support native (AWS IAM: multiple access keys per user). Yoksa manuel orchestration.

Senaryo 3: Employee turnover

Developer ekipten ayrıldı. Bu developer’ın oluşturduğu key’ler var.

Problem:
– Hangi key’ler eski employee’nin?
– Key’ler deprecate edilmiş mi?
– Automated job’lar bu key’lere bağlı mı?

Best practice:

  1. Shared service account’lar. Individual developer key yerine team shared account. Developer ayrılınca key’i rotate etmeye gerek yok.
  2. Ownership tracking. Her key’in “owner” metadata’sı. Developer ayrılınca their keys list ready.
  3. Automatic rotation on offboarding. Offboarding checklist’te “rotate all keys owned by X”.
  4. Inventory maintenance. Quarterly key audit. Orphan key’ler (no owner) investigate.

Senaryo 4: Multi-environment rotation

Dev, staging, production. Each different key. Rotation sırasında environment isolation.

Pattern:

  1. Dev environment first. Rotate, test.
  2. Staging next. Broader verification.
  3. Production last. After confidence built.

Her environment arasında 24-48 saat. Problem olursa next environment’a geçmeden yakalıyorsun.

Prevent cross-environment confusion:
– Key naming: stripe_prod_key, stripe_staging_key
– Visual distinction dashboard’larda (green production, blue staging)
– Production key access limited (2-3 kişi)

Secrets management tools

Manual rotation tedious ve error-prone. Tool’lar:

HashiCorp Vault:
– Dynamic secret generation
– Automatic rotation policies
– Audit logs
– Self-hosted veya managed

AWS Secrets Manager:
– AWS-native
– Automatic rotation for supported services (RDS, DocumentDB)
– Integration with IAM

Doppler, Infisical:
– Developer-friendly SaaS
– Environment variable management
– Integrations with CI/CD

Google Secret Manager:
– GCP-native
– Version management
– Access control

Scale’ine göre tercih. 10 developer’lı startup Doppler OK. Enterprise Vault.

Key hygiene practices

1. Never commit to Git.

.gitignore:

.env
.env.local
secrets.yml
*.pem

Pre-commit hook: sensitive content detect. Tools: git-secrets, truffleHog.

2. Environment variables only.

Code’da key literal yazma. Environment’tan oku:

API_KEY = os.getenv('API_KEY')
if not API_KEY:
    raise Exception('API_KEY not set')

3. Limited scope.

Read-only access yeter ise write key kullanma. Stripe’ta “restricted API key” specific endpoints için.

4. Logging doesn’t include keys.

Log statement’larda API key görünmesin:

logger.info(f"Calling API...")  # OK
logger.info(f"Using key: {api_key}")  # BAD

5. Audit logs active.

Provider dashboard’da API key usage log’ları. Anomaly detection (unexpected IP, unusual time, unusual volume).

Rotation automation

Scheduled rotation automation:

# Lambda function (triggered by EventBridge, weekly)
def rotate_stripe_key():
    # 1. Generate new key via Stripe API
    new_key = stripe.create_api_key(...)
    
    # 2. Store in Secrets Manager (secondary slot)
    secrets_manager.update_secret(
        SecretId='stripe_key',
        SecretString=json.dumps({
            'primary': get_secret('stripe_key')['primary'],
            'secondary': new_key
        })
    )
    
    # 3. Trigger deployment (update running instances)
    trigger_deployment()
    
    # 4. Wait for propagation
    time.sleep(3600)
    
    # 5. Swap primary and secondary
    secrets_manager.update_secret(
        SecretId='stripe_key',
        SecretString=json.dumps({
            'primary': new_key,
            'secondary': None
        })
    )
    
    # 6. Revoke old key (after grace period)
    time.sleep(86400)
    stripe.revoke_api_key(old_key)

Bu pipeline quarterly tetikleniyor. Team müdahalesi yok.

Challenges

Rotation sırasında encounter problems:

1. Cached keys. Old key hâlâ cache’de. Propagation gecikmeli.

Fix: Cache TTL kısa. Explicit invalidation.

2. Third-party integration. Customer’ın webhook’larında key embedded. Her customer’ı notify etmek gerekli.

Fix: Advance notice (30 gün). Clear migration guide.

3. Running batch jobs. Job 2 saat’tir çalışıyor, key rotate edildi. Job fail.

Fix: Grace period (overlap window). Long-running jobs detection.

4. Documentation. Key rotation sürecinde docs, code sample, example’lar old key reference.

Fix: Variable substitution. Docs’ta hard-coded key olmasın.

Monitoring rotation health

Track:
– Last rotation date per key
– Keys overdue for rotation
– Failed rotation attempts
– Anomalous key usage patterns
– Leaked keys detected (GitHub secret scanning)

Dashboard: Datadog, Grafana. Alert: rotation overdue by 30+ days.

Sonuç

API key rotation discipline. Compromise mitigation, proactive security, employee turnover hygiene.

4 senaryo: emergency, scheduled, employee transition, multi-environment. Her biri farklı urgency ve process.

Secrets management tools essential scale için. Manual rotation 3-5 key’e kadar manageable, beyond şart automated.

Key rotation invisible iş. Ama leak olduğunda difference’ı life-saving.

Bu konuda bir projeniz mi var?

Kısa bir özet bırakın, 24 saat içinde size dönüş yapayım.

İletişime Geç