fix: configure CSRF trusted origins and proxy SSL headers

This commit is contained in:
Flatlogic Bot 2026-01-31 06:51:16 +00:00
parent ad76a12150
commit 4b1f09a2a5

View File

@ -23,18 +23,29 @@ DEBUG = os.getenv("DJANGO_DEBUG", "true").lower() == "true"
# Allow all hosts to avoid 404/400 errors during initial deployment # Allow all hosts to avoid 404/400 errors during initial deployment
ALLOWED_HOSTS = ["*"] ALLOWED_HOSTS = ["*"]
CSRF_TRUSTED_ORIGINS = [ # CSRF & Proxy Settings
origin for origin in [ # ------------------------------------------------------------------------------
os.getenv("HOST_FQDN", ""), # Trust the 'X-Forwarded-Proto' header from the proxy (Traefik/Nginx)
os.getenv("CSRF_TRUSTED_ORIGIN", "") # This is required for Django to know it's running over HTTPS.
] if origin SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
]
CSRF_TRUSTED_ORIGINS = [ # Parse comma-separated trusted origins from env
f"https://{host}" if not host.startswith(("http://", "https://")) else host _csrf_env_list = (
for host in CSRF_TRUSTED_ORIGINS os.getenv("HOST_FQDN", "") + "," + os.getenv("CSRF_TRUSTED_ORIGINS", "")
] ).split(",")
# Add the current sslip domain if known, or rely on wildcard matching (Django 4.0+ requires explicit trusted origins for CSRF)
# For now, we rely on the user setting HOST_FQDN correctly. CSRF_TRUSTED_ORIGINS = []
for origin in _csrf_env_list:
origin = origin.strip()
if origin:
if not origin.startswith(("http://", "https://")):
CSRF_TRUSTED_ORIGINS.append(f"https://{origin}")
else:
CSRF_TRUSTED_ORIGINS.append(origin)
# Remove duplicates
CSRF_TRUSTED_ORIGINS = list(set(CSRF_TRUSTED_ORIGINS))
# Cookies must always be HTTPS-only; SameSite=Lax keeps CSRF working behind the proxy. # Cookies must always be HTTPS-only; SameSite=Lax keeps CSRF working behind the proxy.
SESSION_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True