Load .env file at startup and validate BROKER_TOKEN_KEY format

Adds python-dotenv so secrets survive pm2 restarts without relying on
PM2 env vars. Validates the Fernet key format at startup so a bad/missing
key fails immediately with a clear message rather than crashing mid-request.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Thigazhezhilan J 2026-05-03 12:49:18 +05:30
parent e525753394
commit 0a7e038be9
2 changed files with 12 additions and 0 deletions

View File

@ -2,6 +2,9 @@ import os
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from urllib.parse import urlparse from urllib.parse import urlparse
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
@ -108,6 +111,14 @@ def _validate_runtime_secrets():
broker_token_key = (os.getenv("BROKER_TOKEN_KEY") or "").strip() broker_token_key = (os.getenv("BROKER_TOKEN_KEY") or "").strip()
if not broker_token_key: if not broker_token_key:
raise RuntimeError("BROKER_TOKEN_KEY must be configured in production") raise RuntimeError("BROKER_TOKEN_KEY must be configured in production")
try:
from cryptography.fernet import Fernet
Fernet(broker_token_key.encode("utf-8"))
except Exception:
raise RuntimeError(
"BROKER_TOKEN_KEY is set but invalid — must be a 32-byte URL-safe base64 key. "
"Generate one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
)
if (os.getenv("ENABLE_SUPER_ADMIN_BOOTSTRAP") or "").strip() in {"1", "true", "yes"}: if (os.getenv("ENABLE_SUPER_ADMIN_BOOTSTRAP") or "").strip() in {"1", "true", "yes"}:
if not (os.getenv("SUPER_ADMIN_EMAIL") or "").strip(): if not (os.getenv("SUPER_ADMIN_EMAIL") or "").strip():
raise RuntimeError("SUPER_ADMIN_EMAIL must be configured when bootstrap is enabled") raise RuntimeError("SUPER_ADMIN_EMAIL must be configured when bootstrap is enabled")

View File

@ -36,6 +36,7 @@ pydantic==2.12.5
pydantic_core==2.41.5 pydantic_core==2.41.5
pytest==8.3.5 pytest==8.3.5
python-dateutil==2.9.0.post0 python-dateutil==2.9.0.post0
python-dotenv==1.0.1
pyotp==2.9.0 pyotp==2.9.0
pytz==2025.2 pytz==2025.2
requests==2.32.5 requests==2.32.5