Coverage for benefits/settings.py: 91%
129 statements
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 18:00 +0000
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-22 18:00 +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 "django_google_sso",
61 "benefits.core",
62 "benefits.enrollment",
63 "benefits.eligibility",
64 "benefits.oauth",
65 "benefits.in_person",
66]
68GOOGLE_SSO_CLIENT_ID = os.environ.get("GOOGLE_SSO_CLIENT_ID", "secret")
69GOOGLE_SSO_PROJECT_ID = os.environ.get("GOOGLE_SSO_PROJECT_ID", "benefits-admin")
70GOOGLE_SSO_CLIENT_SECRET = os.environ.get("GOOGLE_SSO_CLIENT_SECRET", "secret")
71GOOGLE_SSO_ALLOWABLE_DOMAINS = _filter_empty(os.environ.get("GOOGLE_SSO_ALLOWABLE_DOMAINS", "compiler.la").split(","))
72GOOGLE_SSO_STAFF_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_STAFF_LIST", "").split(","))
73GOOGLE_SSO_SUPERUSER_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_SUPERUSER_LIST", "").split(","))
74GOOGLE_SSO_LOGO_URL = "/static/img/icon/google_sso_logo.svg"
75GOOGLE_SSO_TEXT = "Log in with Google"
76GOOGLE_SSO_SAVE_ACCESS_TOKEN = True
77GOOGLE_SSO_PRE_LOGIN_CALLBACK = "benefits.core.admin.pre_login_user"
78GOOGLE_SSO_SCOPES = [
79 "openid",
80 "https://www.googleapis.com/auth/userinfo.email",
81 "https://www.googleapis.com/auth/userinfo.profile",
82]
83SSO_SHOW_FORM_ON_ADMIN_PAGE = os.environ.get("SSO_SHOW_FORM_ON_ADMIN_PAGE", "False").lower() == "true"
84STAFF_GROUP_NAME = "Cal-ITP"
86MIDDLEWARE = [
87 "django.middleware.security.SecurityMiddleware",
88 "django.contrib.sessions.middleware.SessionMiddleware",
89 "django.contrib.messages.middleware.MessageMiddleware",
90 "django.middleware.locale.LocaleMiddleware",
91 "benefits.core.middleware.Healthcheck",
92 "benefits.core.middleware.HealthcheckUserAgents",
93 "django.middleware.common.CommonMiddleware",
94 "django.middleware.csrf.CsrfViewMiddleware",
95 "django.middleware.clickjacking.XFrameOptionsMiddleware",
96 "csp.middleware.CSPMiddleware",
97 "benefits.core.middleware.ChangedLanguageEvent",
98 "django.contrib.auth.middleware.AuthenticationMiddleware",
99 "django.contrib.messages.middleware.MessageMiddleware",
100]
102if DEBUG: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 MIDDLEWARE.append("benefits.core.middleware.DebugSession")
105HEALTHCHECK_USER_AGENTS = _filter_empty(os.environ.get("HEALTHCHECK_USER_AGENTS", "").split(","))
107CSRF_COOKIE_AGE = None
108CSRF_COOKIE_SAMESITE = "Strict"
109CSRF_COOKIE_HTTPONLY = True
110CSRF_TRUSTED_ORIGINS = _filter_empty(os.environ.get("DJANGO_TRUSTED_ORIGINS", "http://localhost,http://127.0.0.1").split(","))
112# With `Strict`, the user loses their Django session between leaving our app to
113# sign in with OAuth, and coming back into our app from the OAuth redirect.
114# This is because `Strict` disallows our cookie being sent from an external
115# domain and so the session cookie is lost.
116#
117# `Lax` allows the cookie to travel with the user and be sent back to us by the
118# OAuth server, as long as the request is "safe" i.e. GET
119SESSION_COOKIE_SAMESITE = "Lax"
120SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
121SESSION_EXPIRE_AT_BROWSER_CLOSE = True
122SESSION_COOKIE_NAME = "_benefitssessionid"
124if not DEBUG: 124 ↛ 129line 124 didn't jump to line 129 because the condition on line 124 was always true
125 CSRF_COOKIE_SECURE = True
126 CSRF_FAILURE_VIEW = "benefits.core.views.csrf_failure"
127 SESSION_COOKIE_SECURE = True
129SECURE_BROWSER_XSS_FILTER = True
131# required so that cross-origin pop-ups (like the enrollment overlay) have access to parent window context
132# https://github.com/cal-itp/benefits/pull/793
133SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups"
135# the NGINX reverse proxy sits in front of the application in deployed environments
136# SSL terminates before getting to Django, and NGINX adds this header to indicate
137# if the original request was secure or not
138#
139# See https://docs.djangoproject.com/en/5.0/ref/settings/#secure-proxy-ssl-header
140if not DEBUG: 140 ↛ 143line 140 didn't jump to line 143 because the condition on line 140 was always true
141 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
143ROOT_URLCONF = "benefits.urls"
145template_ctx_processors = [
146 "django.template.context_processors.request",
147 "django.contrib.auth.context_processors.auth",
148 "django.contrib.messages.context_processors.messages",
149 "benefits.core.context_processors.agency",
150 "benefits.core.context_processors.active_agencies",
151 "benefits.core.context_processors.analytics",
152 "benefits.core.context_processors.authentication",
153 "benefits.core.context_processors.enrollment",
154 "benefits.core.context_processors.origin",
155 "benefits.core.context_processors.routes",
156]
158if DEBUG: 158 ↛ 159line 158 didn't jump to line 159 because the condition on line 158 was never true
159 template_ctx_processors.extend(
160 [
161 "django.template.context_processors.debug",
162 "benefits.core.context_processors.debug",
163 ]
164 )
166TEMPLATES = [
167 {
168 "BACKEND": "django.template.backends.django.DjangoTemplates",
169 "DIRS": [os.path.join(BASE_DIR, "benefits", "templates")],
170 "APP_DIRS": True,
171 "OPTIONS": {
172 "context_processors": template_ctx_processors,
173 },
174 },
175]
177WSGI_APPLICATION = "benefits.wsgi.application"
179STORAGE_DIR = os.environ.get("DJANGO_STORAGE_DIR", BASE_DIR)
180DATABASES = {
181 "default": {
182 "ENGINE": "django.db.backends.sqlite3",
183 "NAME": os.path.join(STORAGE_DIR, os.environ.get("DJANGO_DB_FILE", "django.db")),
184 }
185}
187# Password validation
189AUTH_PASSWORD_VALIDATORS = [
190 {
191 "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
192 },
193 {
194 "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
195 },
196 {
197 "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
198 },
199 {
200 "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
201 },
202]
205# Internationalization
207LANGUAGE_CODE = "en"
209LANGUAGE_COOKIE_HTTPONLY = True
210LANGUAGE_COOKIE_SAMESITE = "Strict"
211LANGUAGE_COOKIE_SECURE = True
213LANGUAGES = [("en", "English"), ("es", "Español")]
215LOCALE_PATHS = [os.path.join(BASE_DIR, "benefits", "locale")]
217USE_I18N = True
219# See https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-TIME_ZONE
220# > Note that this isn’t necessarily the time zone of the server.
221# > When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates
222# > and to interpret datetimes entered in forms.
223TIME_ZONE = "America/Los_Angeles"
224USE_TZ = True
226# https://docs.djangoproject.com/en/5.0/topics/i18n/formatting/#creating-custom-format-files
227FORMAT_MODULE_PATH = [
228 "benefits.locale",
229]
231# Static files (CSS, JavaScript, Images)
233STATIC_URL = "/static/"
234STATICFILES_DIRS = [os.path.join(BASE_DIR, "benefits", "static")]
235# use Manifest Static Files Storage by default
236STORAGES = {
237 "default": {
238 "BACKEND": "django.core.files.storage.FileSystemStorage",
239 },
240 "staticfiles": {
241 "BACKEND": os.environ.get(
242 "DJANGO_STATICFILES_STORAGE", "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
243 )
244 },
245}
246STATIC_ROOT = os.path.join(BASE_DIR, "static")
248# User-uploaded files
250MEDIA_ROOT = os.path.join(STORAGE_DIR, "uploads/")
252MEDIA_URL = "/media/"
254# Logging configuration
255LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "DEBUG" if DEBUG else "WARNING")
256LOGGING = {
257 "version": 1,
258 "disable_existing_loggers": False,
259 "formatters": {
260 "default": {
261 "format": "[{asctime}] {levelname} {name}:{lineno} {message}",
262 "datefmt": "%d/%b/%Y %H:%M:%S",
263 "style": "{",
264 },
265 },
266 "handlers": {
267 "console": {
268 "class": "logging.StreamHandler",
269 "formatter": "default",
270 },
271 },
272 "root": {
273 "handlers": ["console"],
274 "level": LOG_LEVEL,
275 },
276 "loggers": {
277 "django": {
278 "handlers": ["console"],
279 "propagate": False,
280 },
281 },
282}
284sentry.configure()
286# Analytics configuration
288ANALYTICS_KEY = os.environ.get("ANALYTICS_KEY")
290# reCAPTCHA configuration
292RECAPTCHA_API_URL = os.environ.get("DJANGO_RECAPTCHA_API_URL", "https://www.google.com/recaptcha/api.js")
293RECAPTCHA_SITE_KEY = os.environ.get("DJANGO_RECAPTCHA_SITE_KEY")
294RECAPTCHA_API_KEY_URL = f"{RECAPTCHA_API_URL}?render={RECAPTCHA_SITE_KEY}"
295RECAPTCHA_SECRET_KEY = os.environ.get("DJANGO_RECAPTCHA_SECRET_KEY")
296RECAPTCHA_VERIFY_URL = os.environ.get("DJANGO_RECAPTCHA_VERIFY_URL", "https://www.google.com/recaptcha/api/siteverify")
297RECAPTCHA_ENABLED = all((RECAPTCHA_API_URL, RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY, RECAPTCHA_VERIFY_URL))
299# Content Security Policy
300# Configuration docs at https://django-csp.readthedocs.io/en/latest/configuration.html
302# In particular, note that the inner single-quotes are required!
303# https://django-csp.readthedocs.io/en/latest/configuration.html#policy-settings
305CSP_BASE_URI = ["'none'"]
307CSP_DEFAULT_SRC = ["'self'"]
309CSP_CONNECT_SRC = ["'self'", "https://api.amplitude.com/"]
310env_connect_src = _filter_empty(os.environ.get("DJANGO_CSP_CONNECT_SRC", "").split(","))
311CSP_CONNECT_SRC.extend(env_connect_src)
313CSP_FONT_SRC = ["'self'", "https://california.azureedge.net/", "https://fonts.gstatic.com/"]
314env_font_src = _filter_empty(os.environ.get("DJANGO_CSP_FONT_SRC", "").split(","))
315CSP_FONT_SRC.extend(env_font_src)
317CSP_FRAME_ANCESTORS = ["'none'"]
319CSP_FRAME_SRC = ["*.littlepay.com"]
320env_frame_src = _filter_empty(os.environ.get("DJANGO_CSP_FRAME_SRC", "").split(","))
321if RECAPTCHA_ENABLED: 321 ↛ 322line 321 didn't jump to line 322 because the condition on line 321 was never true
322 env_frame_src.append("https://www.google.com")
323if len(env_frame_src) > 0: 323 ↛ 324line 323 didn't jump to line 324 because the condition on line 323 was never true
324 CSP_FRAME_SRC.extend(env_frame_src)
326CSP_IMG_SRC = [
327 "'self'",
328 "data:",
329 "*.googleusercontent.com",
330]
332# Configuring strict Content Security Policy
333# https://django-csp.readthedocs.io/en/latest/nonce.html
334CSP_INCLUDE_NONCE_IN = ["script-src"]
336CSP_OBJECT_SRC = ["'none'"]
338if sentry.SENTRY_CSP_REPORT_URI: 338 ↛ 339line 338 didn't jump to line 339 because the condition on line 338 was never true
339 CSP_REPORT_URI = [sentry.SENTRY_CSP_REPORT_URI]
341CSP_SCRIPT_SRC = [
342 "'self'",
343 "https://cdn.amplitude.com/libs/",
344 "https://cdn.jsdelivr.net/",
345 "*.littlepay.com",
346 "https://code.jquery.com/jquery-3.6.0.min.js",
347]
348env_script_src = _filter_empty(os.environ.get("DJANGO_CSP_SCRIPT_SRC", "").split(","))
349CSP_SCRIPT_SRC.extend(env_script_src)
350if RECAPTCHA_ENABLED: 350 ↛ 351line 350 didn't jump to line 351 because the condition on line 350 was never true
351 CSP_SCRIPT_SRC.extend(["https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/releases/"])
353CSP_STYLE_SRC = [
354 "'self'",
355 "'unsafe-inline'",
356 "https://california.azureedge.net/",
357 "https://fonts.googleapis.com/css",
358 "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/",
359]
360env_style_src = _filter_empty(os.environ.get("DJANGO_CSP_STYLE_SRC", "").split(","))
361CSP_STYLE_SRC.extend(env_style_src)
363# Configuration for requests
364# https://requests.readthedocs.io/en/latest/user/advanced/#timeouts
366try:
367 REQUESTS_CONNECT_TIMEOUT = int(os.environ.get("REQUESTS_CONNECT_TIMEOUT"))
368except Exception:
369 REQUESTS_CONNECT_TIMEOUT = 3
371try:
372 REQUESTS_READ_TIMEOUT = int(os.environ.get("REQUESTS_READ_TIMEOUT"))
373except Exception:
374 REQUESTS_READ_TIMEOUT = 20
376REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)