Coverage for benefits/settings.py: 90%
131 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-14 01:41 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-14 01:41 +0000
1"""
2Django settings for benefits project.
3"""
5import os
7from django.conf import settings
9from benefits import sentry
12def _filter_empty(ls):
13 return [s for s in ls if s]
16# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
17BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19# SECURITY WARNING: keep the secret key used in production secret!
20SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "secret")
22# SECURITY WARNING: don't run with debug turned on in production!
23DEBUG = os.environ.get("DJANGO_DEBUG", "False").lower() == "true"
25ALLOWED_HOSTS = _filter_empty(os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost").split(","))
28class RUNTIME_ENVS:
29 LOCAL = "local"
30 DEV = "dev"
31 TEST = "test"
32 PROD = "prod"
35def RUNTIME_ENVIRONMENT():
36 """Helper calculates the current runtime environment from ALLOWED_HOSTS."""
38 # usage of django.conf.settings.ALLOWED_HOSTS here (rather than the module variable directly)
39 # is to ensure dynamic calculation, e.g. for unit tests and elsewhere this setting is needed
40 env = RUNTIME_ENVS.LOCAL
41 if "dev-benefits.calitp.org" in settings.ALLOWED_HOSTS:
42 env = RUNTIME_ENVS.DEV
43 elif "test-benefits.calitp.org" in settings.ALLOWED_HOSTS:
44 env = RUNTIME_ENVS.TEST
45 elif "benefits.calitp.org" in settings.ALLOWED_HOSTS:
46 env = RUNTIME_ENVS.PROD
47 return env
50# Application definition
52INSTALLED_APPS = [
53 "benefits.apps.BenefitsAdminConfig",
54 "django.contrib.auth",
55 "django.contrib.contenttypes",
56 "django.contrib.messages",
57 "django.contrib.sessions",
58 "django.contrib.staticfiles",
59 "adminsortable2",
60 "cdt_identity",
61 "django_google_sso",
62 "benefits.core",
63 "benefits.enrollment",
64 "benefits.enrollment_littlepay",
65 "benefits.enrollment_switchio",
66 "benefits.eligibility",
67 "benefits.oauth",
68 "benefits.in_person",
69]
71GOOGLE_SSO_CLIENT_ID = os.environ.get("GOOGLE_SSO_CLIENT_ID", "secret")
72GOOGLE_SSO_PROJECT_ID = os.environ.get("GOOGLE_SSO_PROJECT_ID", "benefits-admin")
73GOOGLE_SSO_CLIENT_SECRET = os.environ.get("GOOGLE_SSO_CLIENT_SECRET", "secret")
74GOOGLE_SSO_ALLOWABLE_DOMAINS = _filter_empty(os.environ.get("GOOGLE_SSO_ALLOWABLE_DOMAINS", "compiler.la").split(","))
75GOOGLE_SSO_STAFF_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_STAFF_LIST", "").split(","))
76GOOGLE_SSO_SUPERUSER_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_SUPERUSER_LIST", "").split(","))
77GOOGLE_SSO_LOGO_URL = "/static/img/icon/google_sso_logo.svg"
78GOOGLE_SSO_TEXT = "Log in with Google"
79GOOGLE_SSO_SAVE_ACCESS_TOKEN = True
80GOOGLE_SSO_PRE_LOGIN_CALLBACK = "benefits.core.admin.pre_login_user"
81GOOGLE_SSO_SCOPES = [
82 "openid",
83 "https://www.googleapis.com/auth/userinfo.email",
84 "https://www.googleapis.com/auth/userinfo.profile",
85]
86SSO_SHOW_FORM_ON_ADMIN_PAGE = os.environ.get("SSO_SHOW_FORM_ON_ADMIN_PAGE", "False").lower() == "true"
87STAFF_GROUP_NAME = "Cal-ITP"
89MIDDLEWARE = [
90 "django.middleware.security.SecurityMiddleware",
91 "django.contrib.sessions.middleware.SessionMiddleware",
92 "django.contrib.messages.middleware.MessageMiddleware",
93 "django.middleware.locale.LocaleMiddleware",
94 "benefits.core.middleware.Healthcheck",
95 "benefits.core.middleware.HealthcheckUserAgents",
96 "django.middleware.common.CommonMiddleware",
97 "django.middleware.csrf.CsrfViewMiddleware",
98 "django.middleware.clickjacking.XFrameOptionsMiddleware",
99 "csp.middleware.CSPMiddleware",
100 "benefits.core.middleware.ChangedLanguageEvent",
101 "django.contrib.auth.middleware.AuthenticationMiddleware",
102 "django.contrib.messages.middleware.MessageMiddleware",
103]
105if DEBUG: 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true
106 MIDDLEWARE.append("benefits.core.middleware.DebugSession")
108HEALTHCHECK_USER_AGENTS = _filter_empty(os.environ.get("HEALTHCHECK_USER_AGENTS", "").split(","))
110CSRF_COOKIE_AGE = None
111CSRF_COOKIE_SAMESITE = "Strict"
112CSRF_COOKIE_HTTPONLY = True
113CSRF_TRUSTED_ORIGINS = _filter_empty(os.environ.get("DJANGO_TRUSTED_ORIGINS", "http://localhost,http://127.0.0.1").split(","))
115# With `Strict`, the user loses their Django session between leaving our app to
116# sign in with OAuth, and coming back into our app from the OAuth redirect.
117# This is because `Strict` disallows our cookie being sent from an external
118# domain and so the session cookie is lost.
119#
120# `Lax` allows the cookie to travel with the user and be sent back to us by the
121# OAuth server, as long as the request is "safe" i.e. GET
122SESSION_COOKIE_SAMESITE = "Lax"
123SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
124SESSION_EXPIRE_AT_BROWSER_CLOSE = True
125SESSION_COOKIE_NAME = "_benefitssessionid"
127if not DEBUG: 127 ↛ 132line 127 didn't jump to line 132 because the condition on line 127 was always true
128 CSRF_COOKIE_SECURE = True
129 CSRF_FAILURE_VIEW = "benefits.core.views.csrf_failure"
130 SESSION_COOKIE_SECURE = True
132SECURE_BROWSER_XSS_FILTER = True
134# required so that cross-origin pop-ups (like the enrollment overlay) have access to parent window context
135# https://github.com/cal-itp/benefits/pull/793
136SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups"
138# the NGINX reverse proxy sits in front of the application in deployed environments
139# SSL terminates before getting to Django, and NGINX adds this header to indicate
140# if the original request was secure or not
141#
142# See https://docs.djangoproject.com/en/5.0/ref/settings/#secure-proxy-ssl-header
143if not DEBUG: 143 ↛ 146line 143 didn't jump to line 146 because the condition on line 143 was always true
144 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
146ROOT_URLCONF = "benefits.urls"
148template_ctx_processors = [
149 "django.template.context_processors.request",
150 "django.contrib.auth.context_processors.auth",
151 "django.contrib.messages.context_processors.messages",
152 "benefits.core.context_processors.agency",
153 "benefits.core.context_processors.active_agencies",
154 "benefits.core.context_processors.analytics",
155 "benefits.core.context_processors.authentication",
156 "benefits.core.context_processors.enrollment",
157 "benefits.core.context_processors.origin",
158 "benefits.core.context_processors.routes",
159]
161if DEBUG: 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true
162 template_ctx_processors.extend(
163 [
164 "django.template.context_processors.debug",
165 "benefits.core.context_processors.debug",
166 ]
167 )
169TEMPLATES = [
170 {
171 "BACKEND": "django.template.backends.django.DjangoTemplates",
172 "DIRS": [os.path.join(BASE_DIR, "benefits", "templates")],
173 "APP_DIRS": True,
174 "OPTIONS": {
175 "context_processors": template_ctx_processors,
176 },
177 },
178]
180WSGI_APPLICATION = "benefits.wsgi.application"
182STORAGE_DIR = os.environ.get("DJANGO_STORAGE_DIR", BASE_DIR)
183DATABASES = {
184 "default": {
185 "ENGINE": "django.db.backends.sqlite3",
186 "NAME": os.path.join(STORAGE_DIR, os.environ.get("DJANGO_DB_FILE", "django.db")),
187 }
188}
190# Password validation
192AUTH_PASSWORD_VALIDATORS = [
193 {
194 "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
195 },
196 {
197 "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
198 },
199 {
200 "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
201 },
202 {
203 "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
204 },
205]
208# Internationalization
210LANGUAGE_CODE = "en"
212LANGUAGE_COOKIE_HTTPONLY = True
213LANGUAGE_COOKIE_SAMESITE = "Strict"
214LANGUAGE_COOKIE_SECURE = True
216LANGUAGES = [("en", "English"), ("es", "Español")]
218LOCALE_PATHS = [os.path.join(BASE_DIR, "benefits", "locale")]
220USE_I18N = True
222# See https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-TIME_ZONE
223# > Note that this isn’t necessarily the time zone of the server.
224# > When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates
225# > and to interpret datetimes entered in forms.
226TIME_ZONE = "America/Los_Angeles"
227USE_TZ = True
229# https://docs.djangoproject.com/en/5.0/topics/i18n/formatting/#creating-custom-format-files
230FORMAT_MODULE_PATH = [
231 "benefits.locale",
232]
234# Static files (CSS, JavaScript, Images)
236STATIC_URL = "/static/"
237STATICFILES_DIRS = [os.path.join(BASE_DIR, "benefits", "static")]
238# use Manifest Static Files Storage by default
239STORAGES = {
240 "default": {
241 "BACKEND": "django.core.files.storage.FileSystemStorage",
242 },
243 "staticfiles": {
244 "BACKEND": os.environ.get(
245 "DJANGO_STATICFILES_STORAGE", "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
246 )
247 },
248}
249STATIC_ROOT = os.path.join(BASE_DIR, "static")
251# User-uploaded files
253MEDIA_ROOT = os.path.join(STORAGE_DIR, "uploads/")
255MEDIA_URL = "/media/"
257# Logging configuration
258LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "DEBUG" if DEBUG else "WARNING")
259LOGGING = {
260 "version": 1,
261 "disable_existing_loggers": False,
262 "formatters": {
263 "default": {
264 "format": "[{asctime}] {levelname} {name}:{lineno} {message}",
265 "datefmt": "%d/%b/%Y %H:%M:%S",
266 "style": "{",
267 },
268 },
269 "handlers": {
270 "console": {
271 "class": "logging.StreamHandler",
272 "formatter": "default",
273 },
274 },
275 "root": {
276 "handlers": ["console"],
277 "level": LOG_LEVEL,
278 },
279 "loggers": {
280 "django": {
281 "handlers": ["console"],
282 "propagate": False,
283 },
284 },
285}
287sentry.configure()
289# Analytics configuration
291ANALYTICS_KEY = os.environ.get("ANALYTICS_KEY")
293# reCAPTCHA configuration
295RECAPTCHA_API_URL = os.environ.get("DJANGO_RECAPTCHA_API_URL", "https://www.google.com/recaptcha/api.js")
296RECAPTCHA_SITE_KEY = os.environ.get("DJANGO_RECAPTCHA_SITE_KEY")
297RECAPTCHA_API_KEY_URL = f"{RECAPTCHA_API_URL}?render={RECAPTCHA_SITE_KEY}"
298RECAPTCHA_SECRET_KEY = os.environ.get("DJANGO_RECAPTCHA_SECRET_KEY")
299RECAPTCHA_VERIFY_URL = os.environ.get("DJANGO_RECAPTCHA_VERIFY_URL", "https://www.google.com/recaptcha/api/siteverify")
300RECAPTCHA_ENABLED = all((RECAPTCHA_API_URL, RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY, RECAPTCHA_VERIFY_URL))
302# Content Security Policy
303# Configuration docs at https://django-csp.readthedocs.io/en/latest/configuration.html
305# In particular, note that the inner single-quotes are required!
306# https://django-csp.readthedocs.io/en/latest/configuration.html#policy-settings
308CSP_BASE_URI = ["'none'"]
310CSP_DEFAULT_SRC = ["'self'"]
312CSP_CONNECT_SRC = ["'self'", "https://api.amplitude.com/"]
313env_connect_src = _filter_empty(os.environ.get("DJANGO_CSP_CONNECT_SRC", "").split(","))
314if RECAPTCHA_ENABLED: 314 ↛ 315line 314 didn't jump to line 315 because the condition on line 314 was never true
315 env_connect_src.append("https://www.google.com/recaptcha/")
316CSP_CONNECT_SRC.extend(env_connect_src)
318CSP_FONT_SRC = ["'self'", "https://fonts.gstatic.com/"]
319env_font_src = _filter_empty(os.environ.get("DJANGO_CSP_FONT_SRC", "").split(","))
320CSP_FONT_SRC.extend(env_font_src)
322CSP_FRAME_ANCESTORS = ["'none'"]
324CSP_FRAME_SRC = ["*.littlepay.com"]
325env_frame_src = _filter_empty(os.environ.get("DJANGO_CSP_FRAME_SRC", "").split(","))
326if RECAPTCHA_ENABLED: 326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true
327 env_frame_src.append("https://www.google.com")
328if len(env_frame_src) > 0: 328 ↛ 329line 328 didn't jump to line 329 because the condition on line 328 was never true
329 CSP_FRAME_SRC.extend(env_frame_src)
331CSP_IMG_SRC = [
332 "'self'",
333 "data:",
334 "*.googleusercontent.com",
335]
337# Configuring strict Content Security Policy
338# https://django-csp.readthedocs.io/en/latest/nonce.html
339CSP_INCLUDE_NONCE_IN = ["script-src"]
341CSP_OBJECT_SRC = ["'none'"]
343if sentry.SENTRY_CSP_REPORT_URI: 343 ↛ 344line 343 didn't jump to line 344 because the condition on line 343 was never true
344 CSP_REPORT_URI = [sentry.SENTRY_CSP_REPORT_URI]
346CSP_SCRIPT_SRC = [
347 "'self'",
348 "https://cdn.amplitude.com/libs/",
349 "https://cdn.jsdelivr.net/",
350 "*.littlepay.com",
351 "https://code.jquery.com/jquery-3.6.0.min.js",
352]
353env_script_src = _filter_empty(os.environ.get("DJANGO_CSP_SCRIPT_SRC", "").split(","))
354CSP_SCRIPT_SRC.extend(env_script_src)
355if RECAPTCHA_ENABLED: 355 ↛ 356line 355 didn't jump to line 356 because the condition on line 355 was never true
356 CSP_SCRIPT_SRC.extend(["https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/releases/"])
358CSP_STYLE_SRC = [
359 "'self'",
360 "'unsafe-inline'",
361 "https://fonts.googleapis.com/css",
362 "https://fonts.googleapis.com/css2",
363 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/",
364]
365env_style_src = _filter_empty(os.environ.get("DJANGO_CSP_STYLE_SRC", "").split(","))
366CSP_STYLE_SRC.extend(env_style_src)
368# Configuration for requests
369# https://requests.readthedocs.io/en/latest/user/advanced/#timeouts
371try:
372 REQUESTS_CONNECT_TIMEOUT = int(os.environ.get("REQUESTS_CONNECT_TIMEOUT"))
373except Exception:
374 REQUESTS_CONNECT_TIMEOUT = 3
376try:
377 REQUESTS_READ_TIMEOUT = int(os.environ.get("REQUESTS_READ_TIMEOUT"))
378except Exception:
379 REQUESTS_READ_TIMEOUT = 20
381REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)