python
#!/usr/bin/env python3
"""
Secure Vault-Backed Secret Fetcher with Rotation and Break-Glass.
This module provides a Python class for securely fetching secrets from HashiCorp Vault (KV v2 engine).
- **Fetch**: Retrieves the latest secret version with automatic lease handling.
- **Rotation**: Automated rotation via a scheduled job (e.g., cron/Lambda) that generates a new secret,
rotates it in the target system (e.g., DB), and updates Vault.
- **Break-Glass**: Emergency access using a long-lived "break-glass" token stored in a separate, audited
path. Use only in crises (e.g., rotation failure, Vault outage). Logs all access for audit.
Prerequisites:
- HashiCorp Vault server with KV v2 mounted at 'secret/'.
- AppRole auth enabled (or adapt for Kubernetes/Cert auth).
- Vault policies: See below.
- `pip install hvac cryptography` for deps.
Example Usage:
fetcher = SecureVaultFetcher(vault_url='https://vault.example.com:8200',
role_id='your-role-id', secret_id='your-secret-id')
secret = fetcher.fetch('myapp/prod/dbpass')
# Rotate: Run rotator.py periodically
# Break-glass: fetcher.break_glass_fetch('myapp/prod/dbpass-emergency')
"""
import base64
import logging
import os
import secrets
import sys
from datetime import datetime, timedelta
from typing import Dict, Optional, Union
import hvac
from cryptography.fernet import Fernet
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class SecureVaultFetcher:
def __init__(
self,
vault_url: str,
role_id: str,
secret_id: str,
vault_path: str = "secret",
ttl_minutes: int = 60, # Lease TTL for fetched secrets
max_retries: int = 3,
):
self.client = hvac.Client(url=vault_url, verify=True)
self.role_id = role_id
self.secret_id = secret_id
self.vault_path = vault_path
self.ttl_minutes = ttl_minutes
self.max_retries = max_retries
self._auth()
def _auth(self) -> None:
"""Authenticate via AppRole."""
auth_data = self.client.auth.approle.login(role_id=self.role_id, secret_id=self.secret_id)
self.client.token = auth_data["auth"]["client_token"]
self.client.is_token_valid()
logger.info("Authenticated to Vault successfully.")
def fetch(self, secret_path: str, field: Optional[str] = None) -> Union[str, Dict]:
"""
Fetch the latest secret from Vault KV v2.
Handles lease renewal implicitly via short TTL.
"""
for attempt in range(self.max_retries):
try:
read_resp = self.client.secrets.kv.v2.read_secret_version(path=secret_path)
data = read_resp["data"]["data"]
if field:
secret = data[field]
else:
secret = data
# Auto-expire: In prod, wrap in TTL-checked cache
logger.info(f"Fetched secret '{secret_path}' (version {read_resp['data']['version']})")
return secret
except hvac.exceptions.InvalidRequest as e:
logger.warning(f"Fetch attempt {attempt+1} failed: {e}")
if attempt == self.max_retries - 1:
raise
self._auth() # Re-auth on failure
def break_glass_fetch(self, secret_path: str, field: Optional[str] = None, reason: str = "") -> Union[str, Dict]:
"""
BREAK-GLASS EMERGENCY FETCH.
Uses a separate, long-lived emergency secret path.
**AUDITED**: Logs to stdout + requires manual reason. Rotate post-use!
Emergency path: {secret_path}-emergency (admin-only policy).
"""
if not reason:
raise ValueError("Break-glass requires a reason (e.g., 'rotation-failed')")
logger.critical(f"BREAK-GLASS ACCESS: {secret_path} | Reason: {reason} | Time: {datetime.utcnow()}")
print(f"🚨 BREAK-GLASS LOG: User={os.getenv('USER', 'unknown')} | PID={os.getpid()} | Reason={reason}", file=sys.stderr)
try:
emergency_path = f"{secret_path}-emergency"
data = self.client.secrets.kv.v2.read_secret_version(path=emergency_path)["data"]["data"]
secret = data[field] if field else data
logger.critical(f"Break-glass fetch succeeded for {secret_path}")
return secret
except Exception as e:
logger.error(f"Break-glass fetch FAILED: {e}")
raise
# Rotation Script (run via cron every 30min, e.g., */30 * * * * python rotator.py)
def rotate_secret(
client: hvac.Client,
secret_path: str,
rotate_target: callable, # e.g., lambda new_pass: update_db_user('myuser', new_pass)
field: str = "password",
length: int = 32,
) -> None:
"""
Rotate a secret:
1. Generate new random secret.
2. Update target system (DB, AWS IAM, etc.).
3. Write to Vault (creates new version).
Handles rollback on failure.
"""
try:
new_secret = base64.b64encode(secrets.token_bytes(length)).decode('utf-8')
rotate_target(new_secret) # Update external system
# Write new version to Vault
current = client.secrets.kv.v2.read_secret_version(path=secret_path)["data"]["data"]
current[field] = new_secret
client.secrets.kv.v2.create_or_update_secret(path=secret_path, secret=current)
logger.info(f"Rotated {secret_path} successfully.")
except Exception as e:
logger.error(f"Rotation FAILED for {secret_path}: {e}")
raise
def example_db_rotator(new_pass: str) -> None:
"""Example: Rotate DB user password (adapt to your DB client, e.g., psycopg2/mysql)."""
# Placeholder: import your DB lib and execute ALTER USER
print(f"Would execute: ALTER USER myapp_prod PASSWORD '{new_pass}'")
# Real impl: Use SQLAlchemy/psycopg2 with admin creds from Vault.
# Example rotator runner
def main_rotator(vault_url: str, role_id: str, secret_id: str):
client = hvac.Client(url=vault_url)
auth = client.auth.approle.login(role_id=role_id, secret_id=secret_id)
client.token = auth["auth"]["client_token"]
rotate_secret(
client=client,
secret_path="myapp/prod/dbpass",
rotate_target=example_db_rotator,
field="password"
)
if __name__ == "__main__":
# Example usage
VAULT_URL = os.getenv("VAULT_URL", "https://vault.example.com:8200")
ROLE_ID = os.getenv("ROLE_ID")
SECRET_ID = os.getenv("SECRET_ID")
if len(sys.argv) > 1 and sys.argv[1] == "rotate":
main_rotator(VAULT_URL, ROLE_ID, SECRET_ID)
else:
fetcher = SecureVaultFetcher(VAULT_URL, ROLE_ID, SECRET_ID)
print(fetcher.fetch("myapp/prod/dbpass", field="password"))
hcl
# Normal app policy (read-only, short leases)
path "secret/data/myapp/prod/*" {
capabilities = ["read"]
}
# Rotator policy (full r/w for rotation)
path "secret/data/myapp/prod/dbpass" {
capabilities = ["read", "create", "update", "delete"]
}
# Break-glass policy (admin-only, audit-enabled)
path "secret/data/myapp/prod/*-emergency" {
capabilities = ["read"]
}
# Enable audit on break-glass paths
This setup ensures zero-downtime rotation, secure fetch, and audited emergency access. Audit logs capture all actions. Test in staging! 🛡️