204 lines
8.8 KiB
Python
204 lines
8.8 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
|
|
from plm_engine.network import get_profile as network_profile
|
|
|
|
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.locale.LocaleMiddleware",
|
|
"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",
|
|
]
|
|
# SEC-17: 8 to 256 characters, nothing more — the same thresholds as the old server.
|
|
AUTH_PASSWORD_VALIDATORS = [
|
|
{"NAME": "apps.accounts.validators.MinimumLengthValidator"},
|
|
{"NAME": "apps.accounts.validators.MaximumLengthValidator"},
|
|
]
|
|
AUTHENTICATION_BACKENDS = ["apps.accounts.backends.CaseInsensitiveBackend"]
|
|
|
|
# ADR-60: Italian only for the pilot; gettext is on so other languages can be added later.
|
|
LANGUAGE_CODE = "it"
|
|
LANGUAGES = [("it", "Italiano")] # one language: the middleware activates it, so Django's own messages are Italian too
|
|
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_AGE = 24 * 3600 # a session lasts a day, like the old token (ADR-36)
|
|
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 = "/"
|
|
CSRF_FAILURE_VIEW = "apps.web.views.csrf_failure"
|
|
|
|
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)")
|
|
# ADR-58: mainnet is forbidden until the checks of phase C are closed; starting on it takes an explicit,
|
|
# separate confirmation, so a copied or mistyped PLM_NETWORK alone can never put real funds at stake.
|
|
if PLM_NETWORK == "mainnet" and os.environ.get("PLM_MAINNET_CONFIRMED", "") != "yes":
|
|
raise ImproperlyConfigured("PLM_NETWORK=mainnet needs PLM_MAINNET_CONFIRMED=yes (ADR-58): real funds are at stake")
|
|
PLM_PROFILE = network_profile(PLM_NETWORK)
|
|
|
|
# ARC-78: the web process knows only the public account key; the signing key is the worker's alone.
|
|
PROCESS_ROLE = os.environ.get("PROCESS_ROLE", "web")
|
|
PLM_ACCOUNT_XPUB = os.environ.get("PLM_ACCOUNT_XPUB", "")
|
|
|
|
# ELC-31: the Electrum servers of a real ledger, first = preferred. Rotation and quorum need at least three;
|
|
# ELECTRUM_ALLOW_NO_QUORUM relaxes that for development only, never on mainnet.
|
|
ELECTRUM_SERVERS = os.environ.get("ELECTRUM_SERVERS", "")
|
|
ELECTRUM_ALLOW_NO_QUORUM = os.environ.get("ELECTRUM_ALLOW_NO_QUORUM", "").lower() == "true"
|
|
if ELECTRUM_ALLOW_NO_QUORUM and PLM_NETWORK == "mainnet":
|
|
raise ImproperlyConfigured("ELECTRUM_ALLOW_NO_QUORUM is for development: it cannot be set on mainnet (ELC-31)")
|
|
if LEDGER_BACKEND == "chain":
|
|
from plm_engine.electrum.client import parse_server_list
|
|
|
|
try:
|
|
ELECTRUM_ENDPOINTS = parse_server_list(ELECTRUM_SERVERS)
|
|
except ValueError as error:
|
|
raise ImproperlyConfigured(f"ELECTRUM_SERVERS: {error}") from error
|
|
if not ELECTRUM_ENDPOINTS:
|
|
raise ImproperlyConfigured("LEDGER_BACKEND=chain needs ELECTRUM_SERVERS (ELC-31)")
|
|
if len(ELECTRUM_ENDPOINTS) < 3 and not ELECTRUM_ALLOW_NO_QUORUM:
|
|
raise ImproperlyConfigured(
|
|
"ELECTRUM_SERVERS needs at least three servers for a quorum (ELC-31); ELECTRUM_ALLOW_NO_QUORUM=true is development only"
|
|
)
|
|
else:
|
|
ELECTRUM_ENDPOINTS = []
|
|
PLM_MASTER_KEY_FILE = os.environ.get("PLM_MASTER_KEY_FILE", "")
|
|
PLM_KEY_ENCRYPTION_KEY_FILE = os.environ.get("PLM_KEY_ENCRYPTION_KEY_FILE", "")
|
|
|
|
# The simulated chain (ADR-59): a block every N seconds and a confirmation after M, so a whole round
|
|
# runs in a few minutes on localhost. Real chains ignore both.
|
|
SIMULATED_BLOCK_SECONDS = int(os.environ.get("SIMULATED_BLOCK_SECONDS", "20"))
|
|
SIMULATED_CONFIRM_SECONDS = int(os.environ.get("SIMULATED_CONFIRM_SECONDS", "5"))
|
|
|
|
# Where a transaction can be looked up (WEB-24). Empty = no link. `{txid}` is replaced; e.g. https://explorer.example/tx/{txid}
|
|
EXPLORER_TX_URL = os.environ.get("EXPLORER_TX_URL", "")
|