Files
KeepItGoingServer/config/settings/selfhosted.py
T
Keith SmithandClaude Sonnet 4.5 de57befe3a Restore Django security headers for defense-in-depth
Re-added SECURE_CONTENT_TYPE_NOSNIFF and SECURE_BROWSER_XSS_FILTER
to Django settings. These don't conflict with NPM's "Block Common
Exploits" feature - they provide defense-in-depth by ensuring headers
are set even if the request bypasses NPM.

Security header strategy:
- NPM (primary): CSP, HSTS, Referrer-Policy, Permissions-Policy,
  X-Content-Type-Options, X-XSS-Protection via "Block Common Exploits"
- Django (backup): X-Frame-Options, X-Content-Type-Options,
  X-XSS-Protection for defense-in-depth

This follows security best practice of setting headers at multiple
layers rather than relying on a single point of control.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 18:17:34 -07:00

180 lines
6.2 KiB
Python

"""
Self-hosted settings for KeepItGoing.
Use this for users running their own instance.
"""
import os
import sys
import dj_database_url
from .base import *
# Security
SECRET_KEY = os.environ.get('SECRET_KEY')
if not SECRET_KEY:
raise ValueError(
"SECRET_KEY environment variable is required for self-hosted deployment. "
"Generate one with: python -c \"from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())\""
)
# Validate SECRET_KEY strength
if len(SECRET_KEY) < 50:
print("WARNING: SECRET_KEY is too short. Use at least 50 characters for security.", file=sys.stderr)
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
# Force DEBUG to False in self-hosted mode for security
if DEBUG:
print("WARNING: DEBUG=True in self-hosted mode is a security risk!", file=sys.stderr)
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
# Database - Support both PostgreSQL and MariaDB/MySQL via DATABASE_URL
# DATABASE_URL format examples:
# PostgreSQL: postgresql://user:password@host:5432/dbname
# MariaDB/MySQL: mysql://user:password@host:3306/dbname
database_url = os.environ.get('DATABASE_URL')
if database_url:
# Use DATABASE_URL for flexible database backend (PostgreSQL, MariaDB, MySQL, etc.)
DATABASES = {
'default': dj_database_url.config(
default=database_url,
conn_max_age=600,
conn_health_checks=True,
)
}
# Add MariaDB/MySQL specific options if using MySQL backend
if 'mysql' in database_url.lower():
DATABASES['default']['OPTIONS'] = {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
}
else:
# Fallback to manual configuration (backwards compatibility)
# Supports both PostgreSQL and MariaDB/MySQL
db_engine = os.environ.get('DB_ENGINE', 'django.db.backends.postgresql')
DATABASES = {
'default': {
'ENGINE': db_engine,
'NAME': os.environ.get('DB_NAME', os.environ.get('POSTGRES_DB', 'keepitgoing')),
'USER': os.environ.get('DB_USER', os.environ.get('POSTGRES_USER', 'keepitgoing')),
'PASSWORD': os.environ.get('DB_PASSWORD', os.environ.get('POSTGRES_PASSWORD', 'keepitgoing')),
'HOST': os.environ.get('DB_HOST', os.environ.get('POSTGRES_HOST', 'db')),
'PORT': os.environ.get('DB_PORT', os.environ.get('POSTGRES_PORT', '5432')),
}
}
# Add MariaDB/MySQL specific options if using MySQL backend
if 'mysql' in db_engine:
DATABASES['default']['OPTIONS'] = {
'charset': 'utf8mb4',
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
}
# Redis/Celery
REDIS_URL = os.environ.get('REDIS_URL', 'redis://redis:6379/0')
CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL
# Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': REDIS_URL,
}
}
# CORS - configurable for self-hosted
CORS_ALLOWED_ORIGINS = os.environ.get(
'CORS_ALLOWED_ORIGINS',
'http://localhost:8000'
).split(',')
# CSRF - configurable for self-hosted
# Must include the exact URL (with protocol and port) you're accessing the site from
CSRF_TRUSTED_ORIGINS = os.environ.get(
'CSRF_TRUSTED_ORIGINS',
'http://localhost:8000'
).split(',')
# ===================================================================
# Security Settings
# ===================================================================
# SSL/HTTPS Security
# Note: SSL termination, HTTP→HTTPS redirect, and HSTS are handled by Nginx Proxy Manager
# NPM is configured with: Force SSL = On, HSTS Enabled = On
SECURE_SSL_REDIRECT = False # NPM handles HTTP→HTTPS redirect
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Trust NPM's X-Forwarded-Proto header
# HSTS - Disabled in Django since NPM sends HSTS headers
# NPM is configured to send: Strict-Transport-Security: max-age=31536000
# Enabling here would create duplicate headers
SECURE_HSTS_SECONDS = 0 # Disabled - NPM handles HSTS
# Silence Django security warnings for settings handled by Nginx Proxy Manager
# W004: HSTS - NPM sends Strict-Transport-Security headers
# W008: SSL Redirect - NPM redirects HTTP to HTTPS
SILENCED_SYSTEM_CHECKS = [
'security.W004', # HSTS handled by NPM
'security.W008', # SSL redirect handled by NPM
]
# Cookie Security
# These are still needed even though NPM handles SSL
SESSION_COOKIE_SECURE = True # Only send session cookies over HTTPS
CSRF_COOKIE_SECURE = True # Only send CSRF cookies over HTTPS
CSRF_COOKIE_HTTPONLY = True # Prevent JavaScript access to CSRF cookie
SESSION_COOKIE_HTTPONLY = True # Prevent JavaScript access to session cookie
# Additional Security Headers
# These are also set by NPM's "Block Common Exploits" feature for defense-in-depth
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY' # Prevent clickjacking
# Note: Content Security Policy (CSP) is configured in Nginx Proxy Manager
# NPM also handles: HSTS, Referrer-Policy, Permissions-Policy
# Static files
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Email - configurable
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.environ.get('EMAIL_HOST', '')
EMAIL_PORT = int(os.environ.get('EMAIL_PORT', 587))
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')
EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS', 'True').lower() == 'true'
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'noreply@localhost')
# Self-hosted mode - no billing
SAAS_MODE = False
BILLING_ENABLED = False
USAGE_LIMITS_ENABLED = False
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}