Coverage for benefits / settings.py: 89%
129 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
1"""
2Django settings for benefits project.
3"""
5import os
7from csp.constants import NONCE, NONE, SELF
8from django.conf import settings
10from benefits import sentry
13def _filter_empty(ls):
14 return [s for s in ls if s]
17# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
18BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20# SECURITY WARNING: keep the secret key used in production secret!
21SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "secret")
23# SECURITY WARNING: don't run with debug turned on in production!
24DEBUG = os.environ.get("DJANGO_DEBUG", "False").lower() == "true"
26ALLOWED_HOSTS = _filter_empty(os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost").split(","))
29class RUNTIME_ENVS:
30 LOCAL = "local"
31 DEV = "dev"
32 TEST = "test"
33 PROD = "prod"
36def RUNTIME_ENVIRONMENT():
37 """Helper calculates the current runtime environment from ALLOWED_HOSTS."""
39 # usage of django.conf.settings.ALLOWED_HOSTS here (rather than the module variable directly)
40 # is to ensure dynamic calculation, e.g. for unit tests and elsewhere this setting is needed
41 env = RUNTIME_ENVS.LOCAL
42 if "dev-benefits.calitp.org" in settings.ALLOWED_HOSTS:
43 env = RUNTIME_ENVS.DEV
44 elif "test-benefits.calitp.org" in settings.ALLOWED_HOSTS:
45 env = RUNTIME_ENVS.TEST
46 elif "benefits.calitp.org" in settings.ALLOWED_HOSTS:
47 env = RUNTIME_ENVS.PROD
48 return env
51# Application definition
53INSTALLED_APPS = [
54 "benefits.apps.BenefitsAdminConfig",
55 "django.contrib.auth",
56 "django.contrib.contenttypes",
57 "django.contrib.messages",
58 "django.contrib.sessions",
59 "django.contrib.staticfiles",
60 "csp",
61 "adminsortable2",
62 "cdt_identity",
63 "django_google_sso",
64 "benefits.core",
65 "benefits.enrollment",
66 "benefits.enrollment_littlepay",
67 "benefits.enrollment_switchio",
68 "benefits.eligibility",
69 "benefits.oauth",
70 "benefits.in_person",
71]
73GOOGLE_SSO_CLIENT_ID = os.environ.get("GOOGLE_SSO_CLIENT_ID", "secret")
74GOOGLE_SSO_PROJECT_ID = os.environ.get("GOOGLE_SSO_PROJECT_ID", "benefits-admin")
75GOOGLE_SSO_CLIENT_SECRET = os.environ.get("GOOGLE_SSO_CLIENT_SECRET", "secret")
76GOOGLE_SSO_ALLOWABLE_DOMAINS = _filter_empty(os.environ.get("GOOGLE_SSO_ALLOWABLE_DOMAINS", "compiler.la").split(","))
77GOOGLE_SSO_STAFF_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_STAFF_LIST", "").split(","))
78GOOGLE_SSO_SUPERUSER_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_SUPERUSER_LIST", "").split(","))
79GOOGLE_SSO_LOGO_URL = "/static/img/icon/google_sso_logo.svg"
80GOOGLE_SSO_TEXT = "Log in with Google"
81GOOGLE_SSO_SAVE_ACCESS_TOKEN = True
82GOOGLE_SSO_PRE_LOGIN_CALLBACK = "benefits.core.admin.pre_login_user"
83GOOGLE_SSO_SCOPES = [
84 "openid",
85 "https://www.googleapis.com/auth/userinfo.email",
86 "https://www.googleapis.com/auth/userinfo.profile",
87]
88SSO_SHOW_FORM_ON_ADMIN_PAGE = os.environ.get("SSO_SHOW_FORM_ON_ADMIN_PAGE", "False").lower() == "true"
89STAFF_GROUP_NAME = "Cal-ITP"
91MIDDLEWARE = [
92 "django.middleware.security.SecurityMiddleware",
93 "django.contrib.sessions.middleware.SessionMiddleware",
94 "django.contrib.messages.middleware.MessageMiddleware",
95 "django.middleware.locale.LocaleMiddleware",
96 "benefits.core.middleware.Healthcheck",
97 "benefits.core.middleware.HealthcheckUserAgents",
98 "django.middleware.common.CommonMiddleware",
99 "django.middleware.csrf.CsrfViewMiddleware",
100 "django.middleware.clickjacking.XFrameOptionsMiddleware",
101 "csp.middleware.CSPMiddleware",
102 "benefits.core.middleware.ChangedLanguageEvent",
103 "django.contrib.auth.middleware.AuthenticationMiddleware",
104 "django.contrib.messages.middleware.MessageMiddleware",
105]
107if DEBUG: 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true
108 MIDDLEWARE.append("benefits.core.middleware.DebugSession")
110HEALTHCHECK_USER_AGENTS = _filter_empty(os.environ.get("HEALTHCHECK_USER_AGENTS", "").split(","))
112CSRF_COOKIE_AGE = None
113CSRF_COOKIE_SAMESITE = "Strict"
114CSRF_COOKIE_HTTPONLY = True
115CSRF_TRUSTED_ORIGINS = _filter_empty(os.environ.get("DJANGO_TRUSTED_ORIGINS", "http://localhost,http://127.0.0.1").split(","))
117# With `Strict`, the user loses their Django session between leaving our app to
118# sign in with OAuth, and coming back into our app from the OAuth redirect.
119# This is because `Strict` disallows our cookie being sent from an external
120# domain and so the session cookie is lost.
121#
122# `Lax` allows the cookie to travel with the user and be sent back to us by the
123# OAuth server, as long as the request is "safe" i.e. GET
124SESSION_COOKIE_SAMESITE = "Lax"
125SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
126SESSION_EXPIRE_AT_BROWSER_CLOSE = True
127SESSION_COOKIE_NAME = "_benefitssessionid"
129if not DEBUG: 129 ↛ 134line 129 didn't jump to line 134 because the condition on line 129 was always true
130 CSRF_COOKIE_SECURE = True
131 CSRF_FAILURE_VIEW = "benefits.views.csrf_failure_handler"
132 SESSION_COOKIE_SECURE = True
134SECURE_BROWSER_XSS_FILTER = True
136# required so that cross-origin pop-ups (like the enrollment overlay) have access to parent window context
137# https://github.com/cal-itp/benefits/pull/793
138SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups"
140# the NGINX reverse proxy sits in front of the application in deployed environments
141# SSL terminates before getting to Django, and NGINX adds this header to indicate
142# if the original request was secure or not
143#
144# See https://docs.djangoproject.com/en/5.0/ref/settings/#secure-proxy-ssl-header
145if not DEBUG: 145 ↛ 148line 145 didn't jump to line 148 because the condition on line 145 was always true
146 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
148ROOT_URLCONF = "benefits.urls"
150template_ctx_processors = [
151 "django.template.context_processors.request",
152 "django.contrib.auth.context_processors.auth",
153 "django.contrib.messages.context_processors.messages",
154 "benefits.core.context_processors.agency",
155 "benefits.core.context_processors.active_agencies",
156 "benefits.core.context_processors.analytics",
157 "benefits.core.context_processors.authentication",
158 "benefits.core.context_processors.enrollment",
159 "benefits.core.context_processors.origin",
160 "benefits.core.context_processors.routes",
161 "benefits.core.context_processors.feature_flags",
162]
164if DEBUG: 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true
165 template_ctx_processors.extend(
166 [
167 "django.template.context_processors.debug",
168 "benefits.core.context_processors.debug",
169 ]
170 )
172TEMPLATES = [
173 {
174 "BACKEND": "django.template.backends.django.DjangoTemplates",
175 "DIRS": [os.path.join(BASE_DIR, "benefits", "templates")],
176 "APP_DIRS": True,
177 "OPTIONS": {
178 "context_processors": template_ctx_processors,
179 },
180 },
181]
183WSGI_APPLICATION = "benefits.wsgi.application"
185STORAGE_DIR = os.environ.get("DJANGO_STORAGE_DIR", BASE_DIR)
186DATABASES = {
187 "default": {
188 "ENGINE": "django.db.backends.sqlite3",
189 "NAME": os.path.join(STORAGE_DIR, os.environ.get("DJANGO_DB_FILE", "django.db")),
190 }
191}
193# Password handling
195AUTH_PASSWORD_VALIDATORS = [
196 {
197 "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
198 },
199 {
200 "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
201 },
202 {
203 "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
204 },
205 {
206 "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
207 },
208]
209PASSWORD_RESET_TIMEOUT = 86400 # 24 hours, in seconds
212# Internationalization
214LANGUAGE_CODE = "en"
216LANGUAGE_COOKIE_HTTPONLY = True
217# `Lax` allows the cookie to travel with the user and be sent back to Benefits
218# during redirection e.g. through IdG/Login.gov or a Transit Processor portal
219# ensuring the app is displayed in the same language
220LANGUAGE_COOKIE_SAMESITE = "Lax"
221LANGUAGE_COOKIE_SECURE = True
223LANGUAGES = [("en", "English"), ("es", "Español")]
225LOCALE_PATHS = [os.path.join(BASE_DIR, "benefits", "locale")]
227USE_I18N = True
229# See https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-TIME_ZONE
230# > Note that this isn’t necessarily the time zone of the server.
231# > When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates
232# > and to interpret datetimes entered in forms.
233TIME_ZONE = "America/Los_Angeles"
234USE_TZ = True
236# https://docs.djangoproject.com/en/5.0/topics/i18n/formatting/#creating-custom-format-files
237FORMAT_MODULE_PATH = [
238 "benefits.locale",
239]
241# Static files (CSS, JavaScript, Images)
243STATIC_URL = "/static/"
244STATICFILES_DIRS = [os.path.join(BASE_DIR, "benefits", "static")]
245# use Manifest Static Files Storage by default
246STORAGES = {
247 "default": {
248 "BACKEND": "django.core.files.storage.FileSystemStorage",
249 },
250 "staticfiles": {
251 "BACKEND": os.environ.get(
252 "DJANGO_STATICFILES_STORAGE", "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
253 )
254 },
255}
256STATIC_ROOT = os.path.join(BASE_DIR, "static")
258# User-uploaded files
260MEDIA_ROOT = os.path.join(STORAGE_DIR, "uploads/")
262MEDIA_URL = "/media/"
264# Logging configuration
265LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "DEBUG" if DEBUG else "WARNING")
266LOGGING = {
267 "version": 1,
268 "disable_existing_loggers": False,
269 "formatters": {
270 "default": {
271 "format": "[{asctime}] {levelname} {name}:{lineno} {message}",
272 "datefmt": "%d/%b/%Y %H:%M:%S",
273 "style": "{",
274 },
275 },
276 "handlers": {
277 "console": {
278 "class": "logging.StreamHandler",
279 "formatter": "default",
280 },
281 },
282 "root": {
283 "handlers": ["console"],
284 "level": LOG_LEVEL,
285 },
286 "loggers": {
287 "django": {
288 "handlers": ["console"],
289 "propagate": False,
290 },
291 },
292}
294sentry.configure()
296# Analytics configuration
298ANALYTICS_KEY = os.environ.get("ANALYTICS_KEY")
300# reCAPTCHA configuration
302RECAPTCHA_API_URL = os.environ.get("DJANGO_RECAPTCHA_API_URL", "https://www.google.com/recaptcha/api.js")
303RECAPTCHA_SITE_KEY = os.environ.get("DJANGO_RECAPTCHA_SITE_KEY")
304RECAPTCHA_API_KEY_URL = f"{RECAPTCHA_API_URL}?render={RECAPTCHA_SITE_KEY}"
305RECAPTCHA_SECRET_KEY = os.environ.get("DJANGO_RECAPTCHA_SECRET_KEY")
306RECAPTCHA_VERIFY_URL = os.environ.get("DJANGO_RECAPTCHA_VERIFY_URL", "https://www.google.com/recaptcha/api/siteverify")
307RECAPTCHA_ENABLED = all((RECAPTCHA_API_URL, RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY, RECAPTCHA_VERIFY_URL))
309# Content Security Policy
310# Configuration docs at https://django-csp.readthedocs.io/en/latest/configuration.html+
312CONTENT_SECURITY_POLICY = {
313 "DIRECTIVES": {
314 "base-uri": [NONE],
315 "connect-src": [
316 SELF,
317 "https://api.amplitude.com/",
318 "https://cdn.jsdelivr.net/npm/@switchio",
319 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/",
320 "https://cdn.jsdelivr.net/npm/jquery",
321 ],
322 "default-src": [SELF],
323 "font-src": [SELF, "https://fonts.gstatic.com/"],
324 "frame-ancestors": [NONE],
325 "frame-src": ["*.littlepay.com"],
326 "img-src": [SELF, "data:", "*.googleusercontent.com"],
327 "object-src": [NONE],
328 "script-src": [
329 SELF,
330 "https://cdn.amplitude.com/libs/",
331 "https://cdn.jsdelivr.net/npm/@switchio",
332 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/",
333 "https://cdn.jsdelivr.net/npm/jquery",
334 "*.littlepay.com",
335 NONCE, # https://django-csp.readthedocs.io/en/latest/nonce.html
336 ],
337 "style-src": [
338 SELF,
339 "https://fonts.googleapis.com/css",
340 "https://fonts.googleapis.com/css2",
341 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/",
342 ],
343 }
344}
346# connect-src additions
347env_connect_src = _filter_empty(os.environ.get("DJANGO_CSP_CONNECT_SRC", "").split(","))
348if RECAPTCHA_ENABLED: 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true
349 env_connect_src.append("https://www.google.com/recaptcha/")
350CONTENT_SECURITY_POLICY["DIRECTIVES"]["connect-src"].extend(env_connect_src)
352# font-src additions
353env_font_src = _filter_empty(os.environ.get("DJANGO_CSP_FONT_SRC", "").split(","))
354CONTENT_SECURITY_POLICY["DIRECTIVES"]["font-src"].extend(env_font_src)
356# frame-src additions
357env_frame_src = _filter_empty(os.environ.get("DJANGO_CSP_FRAME_SRC", "").split(","))
358if RECAPTCHA_ENABLED: 358 ↛ 359line 358 didn't jump to line 359 because the condition on line 358 was never true
359 env_frame_src.append("https://www.google.com")
360CONTENT_SECURITY_POLICY["DIRECTIVES"]["frame-src"].extend(env_frame_src)
362# script-src additions
363env_script_src = _filter_empty(os.environ.get("DJANGO_CSP_SCRIPT_SRC", "").split(","))
364if RECAPTCHA_ENABLED: 364 ↛ 365line 364 didn't jump to line 365 because the condition on line 364 was never true
365 env_script_src.extend(["https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/releases/"])
366CONTENT_SECURITY_POLICY["DIRECTIVES"]["script-src"].extend(env_script_src)
368# style-src additions
369env_style_src = _filter_empty(os.environ.get("DJANGO_CSP_STYLE_SRC", "").split(","))
370CONTENT_SECURITY_POLICY["DIRECTIVES"]["style-src"].extend(env_style_src)
372# adjust report-uri when using Sentry
373if sentry.SENTRY_CSP_REPORT_URI: 373 ↛ 374line 373 didn't jump to line 374 because the condition on line 373 was never true
374 CONTENT_SECURITY_POLICY["DIRECTIVES"]["report-uri"] = sentry.SENTRY_CSP_REPORT_URI
377# Configuration for requests
378# https://requests.readthedocs.io/en/latest/user/advanced/#timeouts
380try:
381 REQUESTS_CONNECT_TIMEOUT = int(os.environ.get("REQUESTS_CONNECT_TIMEOUT"))
382except Exception:
383 REQUESTS_CONNECT_TIMEOUT = 3
385try:
386 REQUESTS_READ_TIMEOUT = int(os.environ.get("REQUESTS_READ_TIMEOUT"))
387except Exception:
388 REQUESTS_READ_TIMEOUT = 20
390REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)
392# Email
393# https://docs.djangoproject.com/en/5.2/ref/settings/#email-backend
394# https://github.com/retech-us/django-azure-communication-email
395AZURE_COMMUNICATION_CONNECTION_STRING = os.environ.get("AZURE_COMMUNICATION_CONNECTION_STRING")
397if AZURE_COMMUNICATION_CONNECTION_STRING: 397 ↛ 398line 397 didn't jump to line 398 because the condition on line 397 was never true
398 EMAIL_BACKEND = "django_azure_communication_email.EmailBackend"
399 EMAIL_USE_TLS = True
400else:
401 EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
402 EMAIL_FILE_PATH = os.path.join(STORAGE_DIR, ".sent_emails")
404# https://docs.djangoproject.com/en/5.2/ref/settings/#default-from-email
405DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "noreply@example.calitp.org")