Codebase hardening: 102 fixes across 35+ files

Deep audit identified 106 findings; 102 fixed, 4 deferred. Covers 8 areas:

- Settings & deploy: env-gated DEBUG/SECRET_KEY, HTTPS headers, gunicorn, celery worker
- Auth (registered_user): password write_only, request.data fixes, transaction safety, proper HTTP status codes
- Workout app: IDOR protection, get_object_or_404, prefetch_related N+1 fixes, transaction.atomic
- Video/scripts: path traversal sanitization, HLS trigger guard, auth on cache wipe
- Models (exercise/equipment/muscle/superset): null-safe __str__, stable IDs, prefetch support
- Generator views: helper for registered_user lookup, logger.exception, bulk_update, transaction wrapping
- Generator core (rules/selector/generator): push-pull ratio, type affinity normalization, modality checks, side-pair exact match, word-boundary regex, equipment cache clearing
- Generator services (plan_builder/analyzer/normalizer): transaction.atomic, muscle cache, bulk_update, glutes classification fix

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-02-27 22:29:14 -06:00
parent 63b57a83ab
commit c80c66c2e5
58 changed files with 3363 additions and 1049 deletions

View File

@@ -9,13 +9,18 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = os.environ.get("DEBUG", "").lower() == "true"
ALLOWED_HOSTS = []
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
if not DEBUG and (not SECRET_KEY or SECRET_KEY == "secret"):
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("SECRET_KEY environment variable is required in production (and must not be 'secret')")
if not SECRET_KEY:
SECRET_KEY = "insecure-dev-secret-key-change-in-production"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split(",")
# Application definition
@@ -28,7 +33,6 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'rest_framework',
'rest_framework.authtoken',
'import_export',
@@ -53,24 +57,17 @@ MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'werkout_api.urls'
if DEBUG:
INSTALLED_APPS += ['debug_toolbar']
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://redis:6379/",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
}
}
ROOT_URLCONF = 'werkout_api.urls'
TEMPLATES = [
{
@@ -94,6 +91,64 @@ WSGI_APPLICATION = 'werkout_api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
if os.environ.get("DATABASE_URL"):
CSRF_TRUSTED_ORIGINS = ['https://*.werkout.fitness', 'https://*.treytartt.com']
# Parse the DATABASE_URL env var.
USER, PASSWORD, HOST, PORT, NAME = re.match("^postgres://(?P<username>.*?)\:(?P<password>.*?)\@(?P<host>.*?)\:(?P<port>\d+)\/(?P<db>.*?)$", os.environ.get("DATABASE_URL", "")).groups()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': NAME,
'USER': USER,
'PASSWORD': PASSWORD,
'HOST': HOST,
'PORT': int(PORT),
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
}
}
CELERY_BROKER_URL = os.environ.get("REDIS_URL", "") + "/1"
CELERY_RESULT_BACKEND = os.environ.get("REDIS_URL", "") + "/1"
INTERNAL_IPS = [
"127.0.0.1",
]
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME', 'werkout'),
'USER': os.environ.get('DB_USER', 'werkout'),
'PASSWORD': os.environ.get('DB_PASSWORD', 'werkout'),
'HOST': os.environ.get('DB_HOST', 'db'),
'PORT': os.environ.get('DB_PORT', '5432'),
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
}
}
CELERY_BROKER_URL = "redis://redis:6379"
CELERY_RESULT_BACKEND = "redis://redis:6379"
INTERNAL_IPS = [
"127.0.0.1",
]
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
@@ -135,97 +190,23 @@ STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
if os.environ.get("DATABASE_URL"):
ALLOWED_HOSTS = ['*']
# if os.environ.get("IS_DEV"):
# DEBUG = True
# PUSH_NOTIFICATIONS_SETTINGS = {
# "APNS_CERTIFICATE": "certs/dev/prod_aps.pem",
# "APNS_TOPIC": "io.brodkast.ios-Dev",
# "APNS_TEAM_ID": "JCU65VV9D9",
# "APNS_USE_SANDBOX": False
# }
# else:
# DEBUG = False
# PUSH_NOTIFICATIONS_SETTINGS = {
# "APNS_CERTIFICATE": "certs/prod/prod_aps.pem",
# "APNS_TOPIC": "io.brodkast.ios",
# "APNS_TEAM_ID": "JCU65VV9D9",
# "APNS_USE_SANDBOX": False
# }
CSRF_TRUSTED_ORIGINS = ['https://*.werkout.fitness', 'https://*.treytartt.com']
SECRET_KEY = os.environ.get("SECRET_KEY", 'secret')
# Parse the DATABASE_URL env var.
USER, PASSWORD, HOST, PORT, NAME = re.match("^postgres://(?P<username>.*?)\:(?P<password>.*?)\@(?P<host>.*?)\:(?P<port>\d+)\/(?P<db>.*?)$", os.environ.get("DATABASE_URL", "")).groups()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': NAME,
'USER': USER,
'PASSWORD': PASSWORD,
'HOST': HOST,
'PORT': int(PORT),
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
}
}
CELERY_BROKER_URL = os.environ.get("REDIS_URL", "") + "/1"
CELERY_RESULT_BACKEND = os.environ.get("REDIS_URL", "") + "/1"
INTERNAL_IPS = [
"127.0.0.1",
]
else:
DEBUG = True
ALLOWED_HOSTS = ['*']
SECRET_KEY = 'django-insecure-o_0sbr3lxcy#_r#imo4tl0cw*%@*__2a48dcd6hbp&u9b5dx=1'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
}
}
CELERY_BROKER_URL = "redis://redis:6379"
CELERY_RESULT_BACKEND = "redis://redis:6379"
INTERNAL_IPS = [
"127.0.0.1",
]
# PUSH_NOTIFICATIONS_SETTINGS = {
# "APNS_CERTIFICATE": "certs/dev/dev_aps.pem",
# "APNS_TOPIC": "io.brodkast.ios-Dev",
# "APNS_TEAM_ID": "JCU65VV9D9",
# "APNS_USE_SANDBOX": True
# }
# CORS settings
CORS_ALLOW_ALL_ORIGINS = True if DEBUG else False
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000',
'http://127.0.0.1:3000',
]
CORS_ALLOW_CREDENTIALS = True
if DEBUG:
CORS_ALLOW_ALL_ORIGINS = True
else:
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",") if os.environ.get("CORS_ALLOWED_ORIGINS") else [
'http://localhost:3000',
'http://127.0.0.1:3000',
]
CORS_ALLOW_CREDENTIALS = True
# HTTPS security settings for production
if not DEBUG:
SECURE_SSL_REDIRECT = os.environ.get("SECURE_SSL_REDIRECT", "true").lower() == "true"
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")