feat: add Django project scaffold, configuration and container
Environment-variable configuration that fails fast, database-only health check, JSON request logs with a request id, security headers with a strict CSP, and a multi-stage non-root Docker image with compose file. Ticket 1.1. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Sk72AxLwQnYttF6VFSxQLt
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
24de5878ed
commit
f8b0584687
@@ -0,0 +1,10 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_env(tmp_path):
|
||||
return {
|
||||
"SECRET_KEY": "x" * 48,
|
||||
"ALLOWED_HOSTS": "testserver",
|
||||
"DATA_DIR": str(tmp_path),
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from portal.config.env import ConfigError, load_config
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_valid_environment_uses_safe_defaults(valid_env):
|
||||
config = load_config(valid_env)
|
||||
assert config.debug is False
|
||||
assert config.log_level == "INFO"
|
||||
assert config.default_timezone == "Europe/Berlin"
|
||||
assert config.trusted_proxies == []
|
||||
assert config.allowed_hosts == ["testserver"]
|
||||
|
||||
|
||||
def test_every_problem_is_listed_and_no_value_leaks(valid_env):
|
||||
secret = "short-secret"
|
||||
env = {
|
||||
**valid_env,
|
||||
"SECRET_KEY": secret,
|
||||
"LOG_LEVEL": "loud",
|
||||
"DEBUG": "maybe",
|
||||
"TRUSTED_PROXIES": "not-an-ip",
|
||||
"DEFAULT_TIMEZONE": "Nowhere/Land",
|
||||
}
|
||||
del env["ALLOWED_HOSTS"]
|
||||
with pytest.raises(ConfigError) as info:
|
||||
load_config(env)
|
||||
message = str(info.value)
|
||||
for name in (
|
||||
"SECRET_KEY",
|
||||
"ALLOWED_HOSTS",
|
||||
"LOG_LEVEL",
|
||||
"DEBUG",
|
||||
"TRUSTED_PROXIES",
|
||||
"DEFAULT_TIMEZONE",
|
||||
):
|
||||
assert name in message
|
||||
assert secret not in message
|
||||
|
||||
|
||||
def test_missing_data_dir_is_reported(valid_env, tmp_path):
|
||||
with pytest.raises(ConfigError, match="DATA_DIR"):
|
||||
load_config({**valid_env, "DATA_DIR": str(tmp_path / "missing")})
|
||||
|
||||
|
||||
def test_process_exits_nonzero_naming_both_variables(tmp_path):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("SECRET_KEY", "LOG_LEVEL")}
|
||||
env.update(
|
||||
ALLOWED_HOSTS="testserver",
|
||||
DATA_DIR=str(tmp_path),
|
||||
LOG_LEVEL="loud",
|
||||
DJANGO_SETTINGS_MODULE="portal.config.settings",
|
||||
)
|
||||
result = subprocess.run( # noqa: S603
|
||||
[sys.executable, "manage.py", "check"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "SECRET_KEY" in result.stderr
|
||||
assert "LOG_LEVEL" in result.stderr
|
||||
assert "Traceback" not in result.stderr
|
||||
@@ -0,0 +1,39 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_security_headers_present(client):
|
||||
response = client.get("/healthz")
|
||||
csp = response["Content-Security-Policy"]
|
||||
assert "script-src 'self'" in csp
|
||||
assert "default-src 'self'" in csp
|
||||
assert "frame-ancestors 'none'" in csp
|
||||
assert "unsafe-inline" not in csp
|
||||
assert "http" not in csp
|
||||
assert response["X-Content-Type-Options"] == "nosniff"
|
||||
assert response["X-Frame-Options"] == "DENY"
|
||||
assert response["Referrer-Policy"] == "same-origin"
|
||||
assert response["X-Request-ID"]
|
||||
|
||||
|
||||
def test_headers_also_on_error_responses(client):
|
||||
response = client.get("/missing")
|
||||
assert response.status_code == 404
|
||||
assert "Content-Security-Policy" in response
|
||||
assert response["X-Request-ID"]
|
||||
|
||||
|
||||
def test_valid_incoming_request_id_is_kept(client):
|
||||
response = client.get("/missing", headers={"X-Request-ID": "abc12345-req"})
|
||||
assert response["X-Request-ID"] == "abc12345-req"
|
||||
|
||||
|
||||
def test_invalid_incoming_request_id_is_replaced(client):
|
||||
response = client.get("/missing", headers={"X-Request-ID": "bad id\twith junk"})
|
||||
assert response["X-Request-ID"] != "bad id\twith junk"
|
||||
|
||||
|
||||
def test_csp_on_bad_host_response(client):
|
||||
response = client.get("/healthz", HTTP_HOST="unlisted.example")
|
||||
assert response.status_code == 400
|
||||
assert "script-src 'self'" in response["Content-Security-Policy"]
|
||||
@@ -0,0 +1,20 @@
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from django.db.utils import OperationalError
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_health_ok(client):
|
||||
response = client.get("/healthz")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_health_down_when_database_unreachable(client, caplog):
|
||||
with mock.patch("portal.config.health.connection") as connection:
|
||||
connection.cursor.side_effect = OperationalError("unable to open database file")
|
||||
response = client.get("/healthz")
|
||||
assert response.status_code == 503
|
||||
assert response.json() == {"status": "unavailable"}
|
||||
assert "unable to open" not in caplog.text
|
||||
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from portal.config.logging import JsonFormatter
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_request_log_has_id_and_no_query(client, caplog):
|
||||
with caplog.at_level(logging.INFO, logger="portal.request"):
|
||||
response = client.get("/healthz?token=supersecret")
|
||||
records = [r for r in caplog.records if r.name == "portal.request"]
|
||||
assert len(records) == 1
|
||||
record = records[0]
|
||||
assert record.request_id == response["X-Request-ID"]
|
||||
assert (record.method, record.path, record.status) == ("GET", "/healthz", 200)
|
||||
assert "supersecret" not in caplog.text
|
||||
|
||||
|
||||
def test_json_formatter_emits_json_with_extras():
|
||||
record = logging.LogRecord("x", logging.INFO, __file__, 1, "hello %s", ("world",), None)
|
||||
record.request_id = "rid-1"
|
||||
record.status = 200
|
||||
data = json.loads(JsonFormatter().format(record))
|
||||
assert data["message"] == "hello world"
|
||||
assert data["request_id"] == "rid-1"
|
||||
assert data["status"] == 200
|
||||
assert data["level"] == "INFO"
|
||||
|
||||
|
||||
def test_404_with_query_writes_one_line_without_query(client, caplog):
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
client.get("/missing?token=supersecret")
|
||||
assert len(caplog.records) == 1
|
||||
output = JsonFormatter().format(caplog.records[0])
|
||||
assert "supersecret" not in output
|
||||
assert json.loads(output)["path"] == "/missing"
|
||||
Reference in New Issue
Block a user