Harden production settings safety checks and docs
This commit is contained in:
68
tests/test_settings_safety.py
Normal file
68
tests/test_settings_safety.py
Normal file
@ -0,0 +1,68 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _import_settings_module(module: str, env_overrides: dict[str, str]) -> subprocess.CompletedProcess:
|
||||
env = os.environ.copy()
|
||||
env.update(env_overrides)
|
||||
command = [
|
||||
sys.executable,
|
||||
"-c",
|
||||
(
|
||||
"import importlib; "
|
||||
f"importlib.import_module('{module}'); "
|
||||
"print('import-ok')"
|
||||
),
|
||||
]
|
||||
return subprocess.run(command, capture_output=True, text=True, env=env, check=False)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_production_settings_reject_default_secret_key():
|
||||
result = _import_settings_module(
|
||||
"config.settings.production",
|
||||
{
|
||||
"DJANGO_ENV": "production",
|
||||
"DJANGO_DEBUG": "0",
|
||||
"DJANGO_SECRET_KEY": "change-me-in-production",
|
||||
"DJANGO_ALLOWED_HOSTS": "app.example.com",
|
||||
"DJANGO_CSRF_TRUSTED_ORIGINS": "https://app.example.com",
|
||||
},
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "DJANGO_SECRET_KEY is unsafe" in (result.stderr + result.stdout)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_production_settings_reject_localhost_csrf_origins():
|
||||
result = _import_settings_module(
|
||||
"config.settings.production",
|
||||
{
|
||||
"DJANGO_ENV": "production",
|
||||
"DJANGO_DEBUG": "0",
|
||||
"DJANGO_SECRET_KEY": "A-very-strong-secret-key-for-production-environment-12345",
|
||||
"DJANGO_ALLOWED_HOSTS": "app.example.com",
|
||||
"DJANGO_CSRF_TRUSTED_ORIGINS": "http://localhost,https://app.example.com",
|
||||
},
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "DJANGO_CSRF_TRUSTED_ORIGINS contains unsafe values" in (result.stderr + result.stdout)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_development_settings_allow_local_defaults():
|
||||
result = _import_settings_module(
|
||||
"config.settings.development",
|
||||
{
|
||||
"DJANGO_ENV": "development",
|
||||
"DJANGO_DEBUG": "1",
|
||||
"DJANGO_SECRET_KEY": "insecure-development-secret",
|
||||
"DJANGO_ALLOWED_HOSTS": "localhost,127.0.0.1",
|
||||
"DJANGO_CSRF_TRUSTED_ORIGINS": "http://localhost,http://127.0.0.1",
|
||||
},
|
||||
)
|
||||
assert result.returncode == 0
|
||||
assert "import-ok" in result.stdout
|
||||
Reference in New Issue
Block a user