Coverage for benefits/settings.py: 87%

139 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-23 20:53 +0000

1""" 

2Django settings for benefits project. 

3""" 

4 

5import os 

6 

7from csp.constants import NONCE, NONE, SELF 

8from django.conf import settings 

9 

10from benefits import sentry 

11 

12 

13def _filter_empty(ls): 

14 return [s for s in ls if s] 

15 

16 

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__))) 

19 

20# SECURITY WARNING: keep the secret key used in production secret! 

21SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "secret") 

22 

23# SECURITY WARNING: don't run with debug turned on in production! 

24DEBUG = os.environ.get("DJANGO_DEBUG", "false").lower() == "true" 

25 

26ALLOWED_HOSTS = _filter_empty(os.environ.get("DJANGO_ALLOWED_HOSTS", "localhost").split(",")) 

27 

28 

29class RUNTIME_ENVS: 

30 LOCAL = "local" 

31 DEV = "dev" 

32 TEST = "test" 

33 PROD = "prod" 

34 

35 

36def RUNTIME_ENVIRONMENT(): 

37 """Helper calculates the current runtime environment from ALLOWED_HOSTS.""" 

38 

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 

49 

50 

51# Application definition 

52 

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 "modeltranslation", 

65 "benefits.core", 

66 "benefits.enrollment", 

67 "benefits.enrollment_init", 

68 "benefits.enrollment_littlepay", 

69 "benefits.enrollment_switchio", 

70 "benefits.eligibility", 

71 "benefits.oauth", 

72 "benefits.in_person", 

73 "benefits.metro_mobility_wallet", 

74] 

75 

76GOOGLE_SSO_CLIENT_ID = os.environ.get("GOOGLE_SSO_CLIENT_ID", "secret") 

77GOOGLE_SSO_PROJECT_ID = os.environ.get("GOOGLE_SSO_PROJECT_ID", "benefits-admin") 

78GOOGLE_SSO_CLIENT_SECRET = os.environ.get("GOOGLE_SSO_CLIENT_SECRET", "secret") 

79GOOGLE_SSO_ALLOWABLE_DOMAINS = _filter_empty(os.environ.get("GOOGLE_SSO_ALLOWABLE_DOMAINS", "compiler.la").split(",")) 

80GOOGLE_SSO_STAFF_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_STAFF_LIST", "").split(",")) 

81GOOGLE_SSO_SUPERUSER_LIST = _filter_empty(os.environ.get("GOOGLE_SSO_SUPERUSER_LIST", "").split(",")) 

82GOOGLE_SSO_LOGO_URL = "/static/img/icon/google_sso_logo.svg" 

83GOOGLE_SSO_TEXT = "Log in with Google" 

84GOOGLE_SSO_SAVE_ACCESS_TOKEN = True 

85GOOGLE_SSO_PRE_LOGIN_CALLBACK = "benefits.core.admin.pre_login_user" 

86GOOGLE_SSO_SCOPES = [ 

87 "openid", 

88 "https://www.googleapis.com/auth/userinfo.email", 

89 "https://www.googleapis.com/auth/userinfo.profile", 

90] 

91SSO_SHOW_FORM_ON_ADMIN_PAGE = os.environ.get("SSO_SHOW_FORM_ON_ADMIN_PAGE", "false").lower() == "true" 

92STAFF_GROUP_NAME = "Cal-ITP" 

93 

94MIDDLEWARE = [ 

95 "django.middleware.security.SecurityMiddleware", 

96 "django.contrib.sessions.middleware.SessionMiddleware", 

97 "django.contrib.messages.middleware.MessageMiddleware", 

98 "django.middleware.locale.LocaleMiddleware", 

99 "benefits.core.middleware.ResetUnsupportedLanguage", 

100 "benefits.core.middleware.Healthcheck", 

101 "benefits.core.middleware.HealthcheckUserAgents", 

102 "django.middleware.common.CommonMiddleware", 

103 "django.middleware.csrf.CsrfViewMiddleware", 

104 "django.middleware.clickjacking.XFrameOptionsMiddleware", 

105 "csp.middleware.CSPMiddleware", 

106 "benefits.core.middleware.ChangedLanguageEvent", 

107 "django.contrib.auth.middleware.AuthenticationMiddleware", 

108 "django.contrib.messages.middleware.MessageMiddleware", 

109] 

110 

111if DEBUG: 111 ↛ 112line 111 didn't jump to line 112 because the condition on line 111 was never true

112 MIDDLEWARE.append("benefits.core.middleware.DebugSession") 

113 

114# The Django Debug Toolbar can be toggled on/off but in both cases the application has to be in debug mode 

115DEBUG_TOOLBAR = DEBUG and os.environ.get("DJANGO_DEBUG_TOOLBAR", "false").lower() == "true" 

116if DEBUG_TOOLBAR: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 INSTALLED_APPS.append("debug_toolbar") 

118 MIDDLEWARE.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware") 

119 # Show the toolbar when in local development mode and with debug on 

120 DEBUG_TOOLBAR_CONFIG = { 

121 "SHOW_TOOLBAR_CALLBACK": lambda request: settings.DEBUG_TOOLBAR, 

122 } 

123 

124 

125HEALTHCHECK_USER_AGENTS = _filter_empty(os.environ.get("HEALTHCHECK_USER_AGENTS", "").split(",")) 

126 

127CSRF_COOKIE_AGE = None 

128CSRF_COOKIE_SAMESITE = "Strict" 

129CSRF_COOKIE_HTTPONLY = True 

130CSRF_TRUSTED_ORIGINS = _filter_empty(os.environ.get("DJANGO_TRUSTED_ORIGINS", "http://localhost,http://127.0.0.1").split(",")) 

131 

132# With `Strict`, the user loses their Django session between leaving our app to 

133# sign in with OAuth, and coming back into our app from the OAuth redirect. 

134# This is because `Strict` disallows our cookie being sent from an external 

135# domain and so the session cookie is lost. 

136# 

137# `Lax` allows the cookie to travel with the user and be sent back to us by the 

138# OAuth server, as long as the request is "safe" i.e. GET 

139SESSION_COOKIE_SAMESITE = "Lax" 

140SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" 

141SESSION_EXPIRE_AT_BROWSER_CLOSE = True 

142SESSION_COOKIE_NAME = "_benefitssessionid" 

143 

144if not DEBUG: 144 ↛ 149line 144 didn't jump to line 149 because the condition on line 144 was always true

145 CSRF_COOKIE_SECURE = True 

146 CSRF_FAILURE_VIEW = "benefits.views.csrf_failure_handler" 

147 SESSION_COOKIE_SECURE = True 

148 

149SECURE_BROWSER_XSS_FILTER = True 

150 

151# required so that cross-origin pop-ups (like the enrollment overlay) have access to parent window context 

152# https://github.com/cal-itp/benefits/pull/793 

153SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups" 

154 

155# the NGINX reverse proxy sits in front of the application in deployed environments 

156# SSL terminates before getting to Django, and NGINX adds this header to indicate 

157# if the original request was secure or not 

158# 

159# See https://docs.djangoproject.com/en/stable/ref/settings/#secure-proxy-ssl-header 

160if not DEBUG: 160 ↛ 163line 160 didn't jump to line 163 because the condition on line 160 was always true

161 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") 

162 

163ROOT_URLCONF = "benefits.urls" 

164 

165template_ctx_processors = [ 

166 "django.template.context_processors.request", 

167 "django.contrib.auth.context_processors.auth", 

168 "django.contrib.messages.context_processors.messages", 

169 "benefits.core.context_processors.agency", 

170 "benefits.core.context_processors.active_agencies", 

171 "benefits.core.context_processors.analytics", 

172 "benefits.core.context_processors.authentication", 

173 "benefits.core.context_processors.enrollment", 

174 "benefits.core.context_processors.flow", 

175 "benefits.core.context_processors.is_prod", 

176 "benefits.core.context_processors.origin", 

177 "benefits.core.context_processors.routes", 

178 "benefits.core.context_processors.runtime_env", 

179 "benefits.core.context_processors.feature_flags", 

180] 

181 

182if DEBUG: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true

183 template_ctx_processors.extend( 

184 [ 

185 "django.template.context_processors.debug", 

186 "benefits.core.context_processors.debug", 

187 ] 

188 ) 

189 

190TEMPLATES = [ 

191 { 

192 "BACKEND": "django.template.backends.django.DjangoTemplates", 

193 "DIRS": [os.path.join(BASE_DIR, "benefits", "templates")], 

194 "APP_DIRS": True, 

195 "OPTIONS": { 

196 "context_processors": template_ctx_processors, 

197 }, 

198 }, 

199] 

200 

201WSGI_APPLICATION = "benefits.wsgi.application" 

202 

203STORAGE_DIR = os.environ.get("DJANGO_STORAGE_DIR", BASE_DIR) 

204 

205sslmode = os.environ.get("POSTGRES_SSLMODE", "verify-full") 

206sslrootcert = "/etc/ssl/certs/ca-certificates.crt" if sslmode == "verify-full" else None 

207 

208DATABASES = { 

209 "default": { 

210 "ENGINE": "django.db.backends.postgresql", 

211 "NAME": os.environ.get("DJANGO_DB_NAME", "django"), 

212 "USER": os.environ.get("DJANGO_DB_USER", "django"), 

213 "PASSWORD": os.environ.get("DJANGO_DB_PASSWORD"), 

214 "HOST": os.environ.get("POSTGRES_HOSTNAME", "postgres"), 

215 "PORT": os.environ.get("POSTGRES_PORT", "5432"), 

216 "OPTIONS": { 

217 "sslmode": sslmode, 

218 "sslrootcert": sslrootcert, 

219 # add these lines to enable TCP keepalives -- 

220 # tiny network packets that keep the connection active and prevent 

221 # network hardware or the database server from thinking it's idle 

222 "keepalives": 1, 

223 "keepalives_idle": 60, 

224 "keepalives_interval": 10, 

225 "keepalives_count": 5, 

226 }, 

227 } 

228} 

229 

230 

231# Password handling 

232 

233AUTH_PASSWORD_VALIDATORS = [ 

234 { 

235 "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", 

236 }, 

237 { 

238 "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", 

239 }, 

240 { 

241 "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", 

242 }, 

243 { 

244 "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", 

245 }, 

246] 

247PASSWORD_RESET_TIMEOUT = 86400 # 24 hours, in seconds 

248 

249 

250# Internationalization 

251 

252LANGUAGE_CODE = "en" 

253 

254LANGUAGE_COOKIE_HTTPONLY = True 

255# `Lax` allows the cookie to travel with the user and be sent back to Benefits 

256# during redirection e.g. through IdG/Login.gov or a Transit Processor portal 

257# ensuring the app is displayed in the same language 

258LANGUAGE_COOKIE_SAMESITE = "Lax" 

259LANGUAGE_COOKIE_SECURE = True 

260 

261LANGUAGES_CORE = [("en", "English"), ("es", "Español")] 

262LANGUAGES_METRO = [ 

263 ("zh-hans", "Chinese simplified"), 

264 ("zh-hant", "Chinese traditional"), 

265 ("ko", "Korean"), 

266 ("ja", "Japanese"), 

267 ("vi", "Vietnamese"), 

268 ("th", "Thai"), 

269 ("ru", "Russian"), 

270 ("hy", "Armenian"), 

271] 

272 

273LANGUAGES = LANGUAGES_CORE + LANGUAGES_METRO 

274 

275LOCALE_PATHS = [os.path.join(BASE_DIR, "benefits", "locale")] 

276 

277USE_I18N = True 

278 

279# See https://docs.djangoproject.com/en/stable/ref/settings/#std-setting-TIME_ZONE 

280# > Note that this isn’t necessarily the time zone of the server. 

281# > When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates 

282# > and to interpret datetimes entered in forms. 

283TIME_ZONE = "America/Los_Angeles" 

284USE_TZ = True 

285 

286# https://docs.djangoproject.com/en/stable/topics/i18n/formatting/#creating-custom-format-files 

287FORMAT_MODULE_PATH = [ 

288 "benefits.locale", 

289] 

290 

291# Static files (CSS, JavaScript, Images) 

292 

293STATIC_URL = "/static/" 

294STATICFILES_DIRS = [os.path.join(BASE_DIR, "benefits", "static")] 

295# use Manifest Static Files Storage by default 

296STORAGES = { 

297 "default": { 

298 "BACKEND": "django.core.files.storage.FileSystemStorage", 

299 }, 

300 "staticfiles": { 

301 "BACKEND": os.environ.get( 

302 "DJANGO_STATICFILES_STORAGE", "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" 

303 ) 

304 }, 

305} 

306STATIC_ROOT = os.path.join(BASE_DIR, "static") 

307 

308# User-uploaded files 

309 

310MEDIA_ROOT = os.path.join(STORAGE_DIR, "uploads/") 

311 

312MEDIA_URL = "/media/" 

313 

314# Prevent Django from attempting to use os.chmod() when saving agency logos since it causes permission errors 

315# on the Container App's Azure File Share 

316FILE_UPLOAD_PERMISSIONS = None 

317 

318# Logging configuration 

319LOG_LEVEL = os.environ.get("DJANGO_LOG_LEVEL", "DEBUG" if DEBUG else "WARNING") 

320LOGGING = { 

321 "version": 1, 

322 "disable_existing_loggers": False, 

323 "formatters": { 

324 "default": { 

325 "format": "[{asctime}] {levelname} {name}:{lineno} {message}", 

326 "datefmt": "%d/%b/%Y %H:%M:%S", 

327 "style": "{", 

328 }, 

329 }, 

330 "handlers": { 

331 "console": { 

332 "class": "logging.StreamHandler", 

333 "formatter": "default", 

334 }, 

335 }, 

336 "root": { 

337 "handlers": ["console"], 

338 "level": LOG_LEVEL, 

339 }, 

340 "loggers": { 

341 "django": { 

342 "handlers": ["console"], 

343 "propagate": False, 

344 }, 

345 }, 

346} 

347 

348sentry.configure(RUNTIME_ENVIRONMENT()) 

349 

350# Analytics configuration 

351 

352ANALYTICS_KEY = os.environ.get("ANALYTICS_KEY") 

353 

354# reCAPTCHA configuration 

355 

356RECAPTCHA_API_URL = os.environ.get("DJANGO_RECAPTCHA_API_URL", "https://www.google.com/recaptcha/api.js") 

357RECAPTCHA_SITE_KEY = os.environ.get("DJANGO_RECAPTCHA_SITE_KEY") 

358RECAPTCHA_API_KEY_URL = f"{RECAPTCHA_API_URL}?render={RECAPTCHA_SITE_KEY}" 

359RECAPTCHA_SECRET_KEY = os.environ.get("DJANGO_RECAPTCHA_SECRET_KEY") 

360RECAPTCHA_VERIFY_URL = os.environ.get("DJANGO_RECAPTCHA_VERIFY_URL", "https://www.google.com/recaptcha/api/siteverify") 

361RECAPTCHA_ENABLED = all((RECAPTCHA_API_URL, RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY, RECAPTCHA_VERIFY_URL)) 

362 

363# Content Security Policy 

364# Configuration docs at https://django-csp.readthedocs.io/en/latest/configuration.html+ 

365 

366CONTENT_SECURITY_POLICY = { 

367 "DIRECTIVES": { 

368 "base-uri": [NONE], 

369 "connect-src": [ 

370 SELF, 

371 "https://api.amplitude.com/", 

372 "https://cdn.jsdelivr.net/sm/", # centralized sourcemap hosting 

373 "https://cdn.jsdelivr.net/npm/@switchio", 

374 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/", 

375 "https://cdn.jsdelivr.net/npm/jquery", 

376 "https://secure.nmi.com", 

377 ], 

378 "default-src": [SELF], 

379 "font-src": [SELF, "https://fonts.gstatic.com/"], 

380 "frame-ancestors": [NONE], 

381 "frame-src": ["*.littlepay.com", "https://secure.nmi.com"], 

382 "img-src": [SELF, "data:", "*.googleusercontent.com", "https://secure.nmi.com"], 

383 "object-src": [NONE], 

384 "script-src": [ 

385 SELF, 

386 "https://cdn.amplitude.com/libs/", 

387 "https://cdn.jsdelivr.net/npm/@switchio", 

388 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/", 

389 "https://cdn.jsdelivr.net/npm/jquery", 

390 "*.littlepay.com", 

391 "https://secure.nmi.com", 

392 NONCE, # https://django-csp.readthedocs.io/en/latest/nonce.html 

393 ], 

394 "style-src": [ 

395 SELF, 

396 "https://fonts.googleapis.com/css", 

397 "https://fonts.googleapis.com/css2", 

398 "https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/", 

399 "https://secure.nmi.com", 

400 NONCE, 

401 ], 

402 } 

403} 

404 

405# connect-src additions 

406env_connect_src = _filter_empty(os.environ.get("DJANGO_CSP_CONNECT_SRC", "").split(",")) 

407if RECAPTCHA_ENABLED: 407 ↛ 408line 407 didn't jump to line 408 because the condition on line 407 was never true

408 env_connect_src.append("https://www.google.com/recaptcha/") 

409CONTENT_SECURITY_POLICY["DIRECTIVES"]["connect-src"].extend(env_connect_src) 

410 

411# font-src additions 

412env_font_src = _filter_empty(os.environ.get("DJANGO_CSP_FONT_SRC", "").split(",")) 

413CONTENT_SECURITY_POLICY["DIRECTIVES"]["font-src"].extend(env_font_src) 

414 

415# frame-src additions 

416env_frame_src = _filter_empty(os.environ.get("DJANGO_CSP_FRAME_SRC", "").split(",")) 

417if RECAPTCHA_ENABLED: 417 ↛ 418line 417 didn't jump to line 418 because the condition on line 417 was never true

418 env_frame_src.append("https://www.google.com") 

419CONTENT_SECURITY_POLICY["DIRECTIVES"]["frame-src"].extend(env_frame_src) 

420 

421# script-src additions 

422env_script_src = _filter_empty(os.environ.get("DJANGO_CSP_SCRIPT_SRC", "").split(",")) 

423if RECAPTCHA_ENABLED: 423 ↛ 424line 423 didn't jump to line 424 because the condition on line 423 was never true

424 env_script_src.extend(["https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/releases/"]) 

425CONTENT_SECURITY_POLICY["DIRECTIVES"]["script-src"].extend(env_script_src) 

426 

427# style-src additions 

428env_style_src = _filter_empty(os.environ.get("DJANGO_CSP_STYLE_SRC", "").split(",")) 

429CONTENT_SECURITY_POLICY["DIRECTIVES"]["style-src"].extend(env_style_src) 

430 

431# adjust report-uri when using Sentry 

432if sentry.SENTRY_CSP_REPORT_URI: 432 ↛ 433line 432 didn't jump to line 433 because the condition on line 432 was never true

433 CONTENT_SECURITY_POLICY["DIRECTIVES"]["report-uri"] = sentry.SENTRY_CSP_REPORT_URI 

434 

435 

436# Configuration for requests 

437# https://requests.readthedocs.io/en/latest/user/advanced/#timeouts 

438 

439try: 

440 REQUESTS_CONNECT_TIMEOUT = int(os.environ.get("REQUESTS_CONNECT_TIMEOUT")) 

441except Exception: 

442 REQUESTS_CONNECT_TIMEOUT = 3 

443 

444try: 

445 REQUESTS_READ_TIMEOUT = int(os.environ.get("REQUESTS_READ_TIMEOUT")) 

446except Exception: 

447 REQUESTS_READ_TIMEOUT = 20 

448 

449REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT) 

450 

451# Email 

452# https://docs.djangoproject.com/en/stable/ref/settings/#email-backend 

453# https://github.com/retech-us/django-azure-communication-email 

454AZURE_COMMUNICATION_CONNECTION_STRING = os.environ.get("AZURE_COMMUNICATION_CONNECTION_STRING") 

455 

456if AZURE_COMMUNICATION_CONNECTION_STRING: 456 ↛ 457line 456 didn't jump to line 457 because the condition on line 456 was never true

457 EMAIL_BACKEND = "django_azure_communication_email.EmailBackend" 

458 EMAIL_USE_TLS = True 

459else: 

460 EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" 

461 EMAIL_FILE_PATH = os.path.join(STORAGE_DIR, ".sent_emails") 

462 

463# https://docs.djangoproject.com/en/stable/ref/settings/#default-from-email 

464DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "noreply@example.calitp.org")