Coverage for benefits/settings.py: 91%

129 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2024-11-22 18:00 +0000

1""" 

2Django settings for benefits project. 

3""" 

4 

5import os 

6 

7from django.conf import settings 

8 

9from benefits import sentry 

10 

11 

12def _filter_empty(ls): 

13 return [s for s in ls if s] 

14 

15 

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

18 

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

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

21 

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

23DEBUG = os.environ.get("DJANGO_DEBUG", "False").lower() == "true" 

24 

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

26 

27 

28class RUNTIME_ENVS: 

29 LOCAL = "local" 

30 DEV = "dev" 

31 TEST = "test" 

32 PROD = "prod" 

33 

34 

35def RUNTIME_ENVIRONMENT(): 

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

37 

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 

48 

49 

50# Application definition 

51 

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] 

67 

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" 

85 

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] 

101 

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

104 

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

106 

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(",")) 

111 

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" 

123 

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 

128 

129SECURE_BROWSER_XSS_FILTER = True 

130 

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" 

134 

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

142 

143ROOT_URLCONF = "benefits.urls" 

144 

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] 

157 

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 ) 

165 

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] 

176 

177WSGI_APPLICATION = "benefits.wsgi.application" 

178 

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} 

186 

187# Password validation 

188 

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] 

203 

204 

205# Internationalization 

206 

207LANGUAGE_CODE = "en" 

208 

209LANGUAGE_COOKIE_HTTPONLY = True 

210LANGUAGE_COOKIE_SAMESITE = "Strict" 

211LANGUAGE_COOKIE_SECURE = True 

212 

213LANGUAGES = [("en", "English"), ("es", "Español")] 

214 

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

216 

217USE_I18N = True 

218 

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 

225 

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

227FORMAT_MODULE_PATH = [ 

228 "benefits.locale", 

229] 

230 

231# Static files (CSS, JavaScript, Images) 

232 

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

247 

248# User-uploaded files 

249 

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

251 

252MEDIA_URL = "/media/" 

253 

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} 

283 

284sentry.configure() 

285 

286# Analytics configuration 

287 

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

289 

290# reCAPTCHA configuration 

291 

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

298 

299# Content Security Policy 

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

301 

302# In particular, note that the inner single-quotes are required! 

303# https://django-csp.readthedocs.io/en/latest/configuration.html#policy-settings 

304 

305CSP_BASE_URI = ["'none'"] 

306 

307CSP_DEFAULT_SRC = ["'self'"] 

308 

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) 

312 

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) 

316 

317CSP_FRAME_ANCESTORS = ["'none'"] 

318 

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) 

325 

326CSP_IMG_SRC = [ 

327 "'self'", 

328 "data:", 

329 "*.googleusercontent.com", 

330] 

331 

332# Configuring strict Content Security Policy 

333# https://django-csp.readthedocs.io/en/latest/nonce.html 

334CSP_INCLUDE_NONCE_IN = ["script-src"] 

335 

336CSP_OBJECT_SRC = ["'none'"] 

337 

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] 

340 

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/"]) 

352 

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) 

362 

363# Configuration for requests 

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

365 

366try: 

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

368except Exception: 

369 REQUESTS_CONNECT_TIMEOUT = 3 

370 

371try: 

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

373except Exception: 

374 REQUESTS_READ_TIMEOUT = 20 

375 

376REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)