Files
OpenVPN-Monitoring-Simple/APP_CORE/secret_key.py
T

42 lines
1.9 KiB
Python
Raw Normal View History

"""JWT signing key rule (fail closed). Identical copy lives in APP_PROFILER/utils/secret_key.py."""
ENV_NAME = "OVPMON_API_SECRET_KEY"
LEGACY_ENV_NAME = "OVPMON_SECRET_KEY"
DEFAULT_KEY = "ovpmon-secret-change-me"
MIN_LENGTH = 32
HOW_TO_FIX = f"Generate one with: openssl rand -hex 32, and set it in {ENV_NAME} (or [api] secret_key in config.ini)."
class SecretKeyError(Exception):
"""The signing key is missing or weak. The message never contains the key value."""
def resolve_secret_key(env, ini_value, legacy_env=None):
"""Return (key, source) where source is "environment" or "config.ini".
env: value of OVPMON_API_SECRET_KEY (or None); ini_value: [api] secret_key (or None);
legacy_env: value of OVPMON_SECRET_KEY (not used by the application, only for the hint).
Priority: environment > config.ini. Raises SecretKeyError; does not log or exit.
"""
if env is not None:
key, source = env, f"environment variable {ENV_NAME}"
result_source = "environment"
else:
key, source = ini_value, "[api] secret_key in config.ini"
result_source = "config.ini"
if key is None or not key.strip():
msg = f"JWT secret key is not set (checked {ENV_NAME} and [api] secret_key in config.ini)."
if legacy_env is not None and legacy_env.strip():
msg += (f" {LEGACY_ENV_NAME} is set but is not used by the application: "
f"rename it to {ENV_NAME}.")
raise SecretKeyError(f"{msg} {HOW_TO_FIX}")
lowered = key.strip().lower()
if lowered == DEFAULT_KEY or "change-me" in lowered or "changeme" in lowered:
raise SecretKeyError(f"JWT secret key from {source} is a placeholder/default value. {HOW_TO_FIX}")
if len(key) < MIN_LENGTH:
raise SecretKeyError(f"JWT secret key from {source} is too short "
f"({len(key)} characters, at least {MIN_LENGTH} required). {HOW_TO_FIX}")
return key, result_source