API-Keys sicher speichern
Security · 5 min

API-Keys gehören in einen Vault oder Environment Variables — niemals in Code oder Git. Regelmäßig rotieren (alle 3-6 Monate), minimale Rechte pro Key, bei Leak sofort revoken.

API-Keys sind das Gold deiner Infrastruktur. Ein geleakter Key kann zu unbefugtem Zugriff, Kosten oder Datenverlust führen. Hier ist, wie wir es machen.
API-Keys, Tokens und Passwörter haben in Git nichts verloren. Ein einziger Commit mit einem Key im Code reicht — selbst nach dem Löschen bleibt er in der Git-History.
Was ist ein Vault?
Ein Vault ist ein sicherer Speicher für Credentials. Bei uns nutzen wir ein Python-Skript, das Keys aus einer verschlüsselten Datei liest:
# vault.py
import os
import json
import base64
from cryptography.fernet import Fernet
VAULT_FILE = "vault.json.enc"
KEY_FILE = ".vault.key"
def get_key():
"""Lade oder erstelle Vault-Key"""
if os.path.exists(KEY_FILE):
with open(KEY_FILE, 'rb') as f:
return f.read()
key = Fernet.generate_key()
with open(KEY_FILE, 'wb') as f:
f.write(key)
return key
def decrypt(filepath):
"""Entschlüssle Vault-Datei"""
key = get_key()
f = Fernet(key)
with open(filepath, 'rb') as data:
encrypted = data.read()
return json.loads(f.decrypt(encrypted))
def get(service, key):
"""Hole einen Key aus dem Vault"""
decrypted = decrypt(VAULT_FILE)
return decrypted[service][key]
# Verwendung
api_key = vault.get("stripe", "secret_key")
print(f"Stripe Key: {api_key[:8]}...") # sk_live_xxxx → sk_live_x...Umgebungsvariablen
Die sicherste Methode: Keys als Environment Variables:
# .env Datei (NIEMALS committen!)
STRIPE_SECRET_KEY=sk_live_xxxxx
GRAFANA_API_KEY=eyJxxxxx
OLLAMA_API_KEY=
# .env.example (Diesen committen)
STRIPE_SECRET_KEY=
GRAFANA_API_KEY=In Python mit python-dotenv:
# config.py
from dotenv import load_dotenv
import os
load_dotenv()
STRIPE_KEY = os.getenv("STRIPE_SECRET_KEY")
GRAFANA_KEY = os.getenv("GRAFANA_API_KEY")
# Error wenn Key fehlt
if not STRIPE_KEY:
raise ValueError("STRIPE_SECRET_KEY nicht gesetzt")Wichtig: .env in .gitignore eintragen!
# .gitignore
.env
.env.local
vault.json.enc
.vault.key
*.pem
*.keyUnser System
| Service | Storage |
|---|---|
| Stripe | .env |
| Grafana | Vault |
| n8n | n8n Credentials |
| Team-Chat | Vault |
| Ollama | Keine (lokal) |
Praktische Regeln
- • NIEMALS Keys in Git committen
- • Keys regelmäßig rotieren (alle 3-6 Monate)
- • Minimale Rechte — nur was nötig ist
- • Bei Leak: Sofort revoken und neuen Key erstellen
- • Monitoring: Ungewohnte Nutzung erkennen
Key Rotation Script
# rotate_keys.py - Keys automatisch rotieren
import os
import subprocess
from datetime import datetime, timedelta
def rotate_stripe_key():
"""Neuen Stripe Key erstellen und alten revoke"""
# 1. API Call zu Stripe
result = subprocess.run([
"stripe", "api_key", "create",
"--description", f"Rotated {datetime.now()}"
], capture_output=True, text=True)
new_key = result.stdout.strip()
# 2. .env updaten
with open(".env", "r") as f:
content = f.read()
content = content.replace(
"STRIPE_SECRET_KEY=sk_live_xxx",
f"STRIPE_SECRET_KEY={new_key}"
)
with open(".env", "w") as f:
f.write(content)
# 3. Alten Key revoke
subprocess.run(["stripe", "api_keys", "delete", "old_key_id"])
print(f"✓ Key rotiert: {new_key[:12]}...")
# Cron: 0 0 1 */6 * → alle 6 MonateCheckliste
- [ ] .env in .gitignore?
- [ ] Keys in Vault oder .env?
- [ ] Keine Keys in Code?
- [ ] Regelmäßige Rotation?
- [ ] Minimale Rechte pro Key?
Zusammenfassung
API-Keys sind kritisch. Mit Vault und Environment Variables bleibst du sicher. Einmal leaken ist schwer rückgängig zu machen.
Quellen
- OWASP: Use of Hard-coded Credentials
- GitHub: Secret Scanning — Automatische Erkennung geleakter Secrets
- GitHub: pyca/cryptography — Python Fernet Encryption
- The Twelve-Factor App: Config — Environment Variables Best Practice
Verwandte Artikel
War dieser Artikel hilfreich?
Weiter im Lernpfad
Der Lernpfad bringt diese Artikel in eine Reihenfolge, und der Hub führt die Bausteine, die wir im eigenen Betrieb geprüft haben.
- Lokal und selbst gehostet
- Dokumentiert und prüfbar
- Aus eigenem Betrieb
- Made in Austria