security: add SECRET_KEY validation

- Prevent server startup if SECRET_KEY is not set in production
- Raise RuntimeError with helpful message if using default value
- Allow debug mode for local development

This ensures the application never runs with an insecure session
secret in production environments.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-02-06 08:09:45 +01:00
parent e062a1e836
commit 630595bce9

View File

@@ -36,8 +36,21 @@ URL_PREFIX = os.environ.get("URL_PREFIX", "").strip().rstrip("/")
STATIC_URL_PATH = f"{URL_PREFIX}/static" if URL_PREFIX else "/static"
app = Flask(__name__, static_url_path=STATIC_URL_PATH)
# SessionSecret für LoginCookies (in Produktion unbedingt setzen).
app.secret_key = os.environ.get("SECRET_KEY", "change-me")
SECRET_KEY = os.environ.get("SECRET_KEY", "change-me")
# Validierung: SECRET_KEY muss in Produktion gesetzt sein
if SECRET_KEY == "change-me":
import sys
if not app.debug and "pytest" not in sys.modules:
raise RuntimeError(
"SECURITY ERROR: SECRET_KEY ist nicht gesetzt!\n"
"Setze die Umgebungsvariable SECRET_KEY mit einem sicheren Wert.\n"
"Beispiel: export SECRET_KEY=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"
)
app.secret_key = SECRET_KEY
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = os.environ.get("COOKIE_SECURE", "1") == "1"
app.config["SESSION_COOKIE_HTTPONLY"] = True