From 933e7b378a4e8fe827e02d879ec881d781a2b46a Mon Sep 17 00:00:00 2001 From: catborise Date: Fri, 25 Sep 2026 10:28:49 +0300 Subject: [PATCH] fix(security): resolve CSRF 403 on DEBUG=False and improve reverse proxy headers - Add local ports and env var fallback for CSRF_TRUSTED_ORIGINS in settings.py.template - Configure SECURE_PROXY_SSL_HEADER for reverse proxy / HTTPS environments - Update Nginx proxy headers to use $http_host and $scheme to prevent port mismatch --- conf/nginx/webvirtcloud.conf | 7 +++---- webvirtcloud/settings.py.template | 8 +++++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/conf/nginx/webvirtcloud.conf b/conf/nginx/webvirtcloud.conf index ae2edf8..d2ca4cc 100644 --- a/conf/nginx/webvirtcloud.conf +++ b/conf/nginx/webvirtcloud.conf @@ -12,10 +12,9 @@ server { location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for; - proxy_set_header Host $host:$server_port; - proxy_set_header X-Forwarded-Proto http; - proxy_set_header X-Forwarded-Ssl off; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Host $http_host; + proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 1800; proxy_read_timeout 1800; proxy_send_timeout 1800; diff --git a/webvirtcloud/settings.py.template b/webvirtcloud/settings.py.template index f753fe9..5c2257a 100644 --- a/webvirtcloud/settings.py.template +++ b/webvirtcloud/settings.py.template @@ -3,6 +3,7 @@ Django settings for webvirtcloud project. """ +import os import subprocess try: import ldap @@ -24,7 +25,12 @@ MAC_OUI = '52:54:10' ALLOWED_HOSTS = ["*"] -CSRF_TRUSTED_ORIGINS = ['http://localhost',] +CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://127.0.0.1", "http://localhost:8000", "http://127.0.0.1:8000"] +if extra_origins := os.getenv("CSRF_TRUSTED_ORIGINS"): + CSRF_TRUSTED_ORIGINS.extend([origin.strip() for origin in extra_origins.split(",") if origin.strip()]) + +# Honor X-Forwarded-Proto header for request.is_secure() when behind a reverse proxy (Nginx, Traefik, etc.) +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # Application definition INSTALLED_APPS = [