From 34389e5e7c102a350ec0206e72c9bcf9aa3af823 Mon Sep 17 00:00:00 2001 From: Nick Sweeting Date: Fri, 23 Aug 2024 02:01:40 -0700 Subject: [PATCH] improve CSRF_TRUSTED_ORIGINS loading logic --- archivebox/config.py | 2 +- archivebox/core/settings.py | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/archivebox/config.py b/archivebox/config.py index ba83b7df..eb6611fa 100644 --- a/archivebox/config.py +++ b/archivebox/config.py @@ -97,7 +97,7 @@ CONFIG_SCHEMA: Dict[str, ConfigDefaultDict] = { 'SECRET_KEY': {'type': str, 'default': None}, 'BIND_ADDR': {'type': str, 'default': lambda c: ['127.0.0.1:8000', '0.0.0.0:8000'][c['IN_DOCKER']]}, 'ALLOWED_HOSTS': {'type': str, 'default': '*'}, # e.g. archivebox.example.com,archivebox2.example.com - 'CSRF_TRUSTED_ORIGINS': {'type': str, 'default': ''}, # e.g. https://archivebox.example.com,https://archivebox2.example.com:8080 + 'CSRF_TRUSTED_ORIGINS': {'type': str, 'default': lambda c: 'http://localhost:8000,http://127.0.0.1:8000,http://0.0.0.0:8000,http://{}'.format(c['BIND_ADDR'])}, # e.g. https://archivebox.example.com,https://archivebox2.example.com:8080 'DEBUG': {'type': bool, 'default': False}, 'PUBLIC_INDEX': {'type': bool, 'default': True}, 'PUBLIC_SNAPSHOTS': {'type': bool, 'default': True}, diff --git a/archivebox/core/settings.py b/archivebox/core/settings.py index 1321bd52..755e0be6 100644 --- a/archivebox/core/settings.py +++ b/archivebox/core/settings.py @@ -5,6 +5,7 @@ import sys import re import logging import tempfile +from typing import Any, Dict from pathlib import Path from django.utils.crypto import get_random_string @@ -317,13 +318,15 @@ STORAGES = { SECRET_KEY = CONFIG.SECRET_KEY or get_random_string(50, 'abcdefghijklmnopqrstuvwxyz0123456789_') ALLOWED_HOSTS = CONFIG.ALLOWED_HOSTS.split(',') -CSRF_TRUSTED_ORIGINS = CONFIG.CSRF_TRUSTED_ORIGINS.split(',') +CSRF_TRUSTED_ORIGINS = list(set(CONFIG.CSRF_TRUSTED_ORIGINS.split(','))) # automatically fix case when user sets ALLOWED_HOSTS (e.g. to archivebox.example.com) # but forgets to add https://archivebox.example.com to CSRF_TRUSTED_ORIGINS -if CONFIG.ALLOWED_HOSTS != '*' and (not CSRF_TRUSTED_ORIGINS): - for hostname in ALLOWED_HOSTS: - CSRF_TRUSTED_ORIGINS.append(f'https://{hostname}') +for hostname in ALLOWED_HOSTS: + https_endpoint = f'https://{hostname}' + if hostname != '*' and https_endpoint not in CSRF_TRUSTED_ORIGINS: + print(f'[!] WARNING: {https_endpoint} from ALLOWED_HOSTS should be added to CSRF_TRUSTED_ORIGINS') + CSRF_TRUSTED_ORIGINS.append(https_endpoint) SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True