mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-06 15:12:30 +09:00
Encryption-at-rest (#16/#17) for the two provider stores still in plaintext: - crypto.py: add decrypt_secret_safe (decrypt with plaintext fallback) + is_encrypted. - DNS providers: encrypt api_key/api_secret on write; decrypt at point-of-use via _api_key/_api_secret in the Cloudflare/Route53/DigitalOcean/GoDaddy builders. - Storage: encrypt secrets in save_config; decrypt in get_config. - Idempotent encrypt_legacy_secrets() migrations run on startup, encrypting any pre-existing plaintext in place. Legacy values keep working via the decrypt fallback, so there is no flag day. Namecheap registrar: - RegistrarConnection.config_json column for non-secret extras (username, client_ip). - RegistrarService: Namecheap XML domains.getList (portfolio + expiry), test, and MM/DD/YYYY -> ISO date parsing. - Frontend: namecheap tile is live; the registrar form is provider-aware (GoDaddy key+secret vs Namecheap key + username + whitelisted IP). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
122 lines
3.6 KiB
Python
122 lines
3.6 KiB
Python
"""
|
|
Cryptographic utilities for ServerKit.
|
|
|
|
Provides encryption/decryption for sensitive data like API secrets.
|
|
"""
|
|
|
|
import os
|
|
import base64
|
|
import warnings
|
|
import logging
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
from cryptography.hazmat.primitives import hashes
|
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def get_encryption_key() -> bytes:
|
|
"""
|
|
Get the encryption key from environment variable.
|
|
|
|
The key should be a valid Fernet key (32 url-safe base64-encoded bytes).
|
|
Generate one with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
|
|
|
Returns:
|
|
bytes: The encryption key
|
|
|
|
Raises:
|
|
ValueError: If SERVERKIT_ENCRYPTION_KEY is not set
|
|
"""
|
|
key = os.environ.get('SERVERKIT_ENCRYPTION_KEY')
|
|
if not key:
|
|
if os.environ.get('FLASK_ENV') == 'production':
|
|
raise ValueError('CRITICAL: SERVERKIT_ENCRYPTION_KEY must be set in production')
|
|
logger.warning('SECURITY WARNING: Using derived development encryption key. Set SERVERKIT_ENCRYPTION_KEY for production.')
|
|
warnings.warn('Using derived development encryption key - not suitable for production')
|
|
# In development, use a default key (NOT for production!)
|
|
# This allows the system to work without explicit configuration
|
|
default_key = "DEV_ONLY_NOT_SECURE_CHANGE_IN_PRODUCTION_KEY"
|
|
# Derive a proper Fernet key from the default
|
|
kdf = PBKDF2HMAC(
|
|
algorithm=hashes.SHA256(),
|
|
length=32,
|
|
salt=b'serverkit_dev_salt',
|
|
iterations=100000,
|
|
)
|
|
key_bytes = base64.urlsafe_b64encode(kdf.derive(default_key.encode()))
|
|
return key_bytes
|
|
return key.encode()
|
|
|
|
|
|
def encrypt_secret(plaintext: str) -> str:
|
|
"""
|
|
Encrypt a secret using Fernet symmetric encryption.
|
|
|
|
Args:
|
|
plaintext: The secret to encrypt
|
|
|
|
Returns:
|
|
str: Base64-encoded encrypted data
|
|
"""
|
|
key = get_encryption_key()
|
|
f = Fernet(key)
|
|
encrypted = f.encrypt(plaintext.encode())
|
|
return encrypted.decode()
|
|
|
|
|
|
def decrypt_secret(encrypted: str) -> str:
|
|
"""
|
|
Decrypt a secret encrypted with encrypt_secret.
|
|
|
|
Args:
|
|
encrypted: Base64-encoded encrypted data
|
|
|
|
Returns:
|
|
str: The decrypted plaintext
|
|
|
|
Raises:
|
|
InvalidToken: If decryption fails (wrong key or corrupted data)
|
|
"""
|
|
key = get_encryption_key()
|
|
f = Fernet(key)
|
|
decrypted = f.decrypt(encrypted.encode())
|
|
return decrypted.decode()
|
|
|
|
|
|
def is_encryption_configured() -> bool:
|
|
"""
|
|
Check if encryption is properly configured.
|
|
|
|
Returns:
|
|
bool: True if SERVERKIT_ENCRYPTION_KEY is set
|
|
"""
|
|
return os.environ.get('SERVERKIT_ENCRYPTION_KEY') is not None
|
|
|
|
|
|
def decrypt_secret_safe(value: str) -> str:
|
|
"""Decrypt a value encrypted with ``encrypt_secret``; if it isn't valid
|
|
ciphertext (e.g. a legacy plaintext secret not yet migrated), return it
|
|
unchanged. Lets encrypted and not-yet-migrated values coexist during the
|
|
transition to encryption-at-rest.
|
|
"""
|
|
if not value:
|
|
return value
|
|
try:
|
|
return decrypt_secret(value)
|
|
except Exception:
|
|
return value
|
|
|
|
|
|
def is_encrypted(value: str) -> bool:
|
|
"""Best-effort check that ``value`` is our Fernet ciphertext (so migrations
|
|
can skip already-encrypted values). A real plaintext secret will not decrypt,
|
|
so this is safe in practice."""
|
|
if not value:
|
|
return False
|
|
try:
|
|
decrypt_secret(value)
|
|
return True
|
|
except Exception:
|
|
return False
|