One Ledger interface (deposit, bet, confirm, reject, exclude, payout) with a simulated implementation chosen by LEDGER_BACKEND, refused on mainnet. Every operation is a single write-locked transaction with its audit row; the same request key is the same operation, a key reused for something else is an error. The server validates round, deadline, the round's own quota, limits and funds. The balance is derived from the ledger. Tests include six processes racing on one SQLite file; the idempotency tests were checked to fail when the replay is removed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
157 lines
5.9 KiB
Python
157 lines
5.9 KiB
Python
"""Django settings (ADR-54, ADR-55, WEB-07).
|
|
|
|
Everything environment-specific comes from environment variables, so the same image
|
|
serves `http://localhost` today and a real domain later with configuration only.
|
|
"""
|
|
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
|
|
def _env_list(name: str) -> list[str]:
|
|
return [item.strip() for item in os.environ.get(name, "").split(",") if item.strip()]
|
|
|
|
|
|
DEBUG = os.environ.get("DJANGO_DEBUG", "false").lower() == "true"
|
|
|
|
# Like ADR-11 for the old server: refuse to start with an inadequate secret instead of
|
|
# running with a guessable one. DEBUG (local development without Docker) is exempt.
|
|
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "")
|
|
if not DEBUG and len(SECRET_KEY) < 50:
|
|
raise ImproperlyConfigured(
|
|
"DJANGO_SECRET_KEY must be at least 50 characters. Generate one with: "
|
|
"python -c \"import secrets; print(secrets.token_urlsafe(64))\""
|
|
)
|
|
if DEBUG and not SECRET_KEY:
|
|
SECRET_KEY = "insecure-development-key-" + "x" * 40
|
|
|
|
# WEB-07: `localhost` works out of the box; a domain is added by configuration only.
|
|
SITE_ADDRESS = os.environ.get("SITE_ADDRESS", "localhost")
|
|
ALLOWED_HOSTS = sorted({"localhost", "127.0.0.1", "[::1]", "web", SITE_ADDRESS, *_env_list("DJANGO_ALLOWED_HOSTS")})
|
|
CSRF_TRUSTED_ORIGINS = sorted(
|
|
{f"https://{SITE_ADDRESS}", *_env_list("DJANGO_CSRF_TRUSTED_ORIGINS")}
|
|
)
|
|
|
|
INSTALLED_APPS = [
|
|
"django.contrib.admin",
|
|
"django.contrib.auth",
|
|
"django.contrib.contenttypes",
|
|
"django.contrib.sessions",
|
|
"django.contrib.messages",
|
|
"django.contrib.staticfiles",
|
|
"apps.accounts",
|
|
"apps.lottery",
|
|
"apps.web",
|
|
"apps.ops",
|
|
]
|
|
|
|
MIDDLEWARE = [
|
|
"django.middleware.security.SecurityMiddleware",
|
|
"whitenoise.middleware.WhiteNoiseMiddleware",
|
|
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
"django.middleware.common.CommonMiddleware",
|
|
"django.middleware.csrf.CsrfViewMiddleware",
|
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
|
"django.contrib.messages.middleware.MessageMiddleware",
|
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
|
]
|
|
|
|
ROOT_URLCONF = "config.urls"
|
|
WSGI_APPLICATION = "config.wsgi.application"
|
|
|
|
TEMPLATES = [
|
|
{
|
|
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
|
"DIRS": [],
|
|
"APP_DIRS": True,
|
|
"OPTIONS": {
|
|
"context_processors": [
|
|
"django.template.context_processors.request",
|
|
"django.contrib.auth.context_processors.auth",
|
|
"django.contrib.messages.context_processors.messages",
|
|
],
|
|
},
|
|
},
|
|
]
|
|
|
|
# ADR-55: one SQLite file in WAL mode shared by the web and the worker processes. Every write
|
|
# transaction takes the write lock up front (`BEGIN IMMEDIATE`), so two processes never deadlock
|
|
# upgrading a read lock, and durability matches the old server (`synchronous=FULL`).
|
|
DATABASES = {
|
|
"default": {
|
|
"ENGINE": "django.db.backends.sqlite3",
|
|
"NAME": os.environ.get("DJANGO_DB_PATH", str(BASE_DIR / "data" / "db" / "site.sqlite3")),
|
|
"OPTIONS": {
|
|
"transaction_mode": "IMMEDIATE",
|
|
"timeout": 20,
|
|
"init_command": "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;",
|
|
},
|
|
}
|
|
}
|
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
|
|
|
# The model is defined before the first migration (ADR-54): changing it later is painful.
|
|
AUTH_USER_MODEL = "accounts.User"
|
|
|
|
# Argon2 first, as in ADR-36; the others only keep Django's own tooling working.
|
|
PASSWORD_HASHERS = [
|
|
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
|
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
|
]
|
|
AUTH_PASSWORD_VALIDATORS = [
|
|
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 8}},
|
|
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
|
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
|
]
|
|
|
|
# ADR-60: Italian only for the pilot; gettext is on so other languages can be added later.
|
|
LANGUAGE_CODE = "it"
|
|
TIME_ZONE = "UTC"
|
|
USE_I18N = True
|
|
USE_TZ = True
|
|
|
|
STATIC_URL = "/static/"
|
|
STATIC_ROOT = BASE_DIR / "staticfiles"
|
|
STORAGES = {
|
|
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
|
|
"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
|
|
}
|
|
|
|
# Caddy terminates TLS (even for localhost) and tells us so (WEB-02, WEB-07). Secure cookies
|
|
# apply wherever there is HTTPS: that is every Docker run, and not `runserver` in DEBUG.
|
|
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
|
SESSION_COOKIE_SECURE = not DEBUG
|
|
CSRF_COOKIE_SECURE = not DEBUG
|
|
SESSION_COOKIE_HTTPONLY = True
|
|
SESSION_COOKIE_SAMESITE = "Lax"
|
|
CSRF_COOKIE_SAMESITE = "Lax"
|
|
SECURE_CONTENT_TYPE_NOSNIFF = True
|
|
X_FRAME_OPTIONS = "DENY"
|
|
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
|
|
|
|
LOGIN_URL = "/accedi/"
|
|
LOGIN_REDIRECT_URL = "/app/"
|
|
LOGOUT_REDIRECT_URL = "/"
|
|
|
|
LOGGING = {
|
|
"version": 1,
|
|
"disable_existing_loggers": False,
|
|
"handlers": {"console": {"class": "logging.StreamHandler"}},
|
|
"root": {"handlers": ["console"], "level": os.environ.get("LOG_LEVEL", "INFO")},
|
|
}
|
|
|
|
# ADR-58, ADR-59: the network profile and how money moves. The alpha runs on regtest with a
|
|
# simulated ledger; the simulated ledger can never run on mainnet (B2 adds the full profile).
|
|
PLM_NETWORK = os.environ.get("PLM_NETWORK", "regtest")
|
|
if PLM_NETWORK not in ("regtest", "mainnet"):
|
|
raise ImproperlyConfigured(f"PLM_NETWORK must be 'regtest' or 'mainnet', not {PLM_NETWORK!r}")
|
|
LEDGER_BACKEND = os.environ.get("LEDGER_BACKEND", "simulated")
|
|
if LEDGER_BACKEND not in ("simulated", "chain"):
|
|
raise ImproperlyConfigured(f"LEDGER_BACKEND must be 'simulated' or 'chain', not {LEDGER_BACKEND!r}")
|
|
if LEDGER_BACKEND == "simulated" and PLM_NETWORK == "mainnet":
|
|
raise ImproperlyConfigured("the simulated ledger cannot run on mainnet (ADR-59)")
|