Coverage for benefits/settings.py: 91%

127 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-10-21 19:31 +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 

179DATABASE_DIR = os.environ.get("DJANGO_DB_DIR", BASE_DIR) 

180DATABASES = { 

181 "default": { 

182 "ENGINE": "django.db.backends.sqlite3", 

183 "NAME": os.path.join(DATABASE_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 "staticfiles": { 

238 "BACKEND": os.environ.get( 

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

240 ) 

241 } 

242} 

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

244 

245# Logging configuration 

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

247LOGGING = { 

248 "version": 1, 

249 "disable_existing_loggers": False, 

250 "formatters": { 

251 "default": { 

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

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

254 "style": "{", 

255 }, 

256 }, 

257 "handlers": { 

258 "console": { 

259 "class": "logging.StreamHandler", 

260 "formatter": "default", 

261 }, 

262 }, 

263 "root": { 

264 "handlers": ["console"], 

265 "level": LOG_LEVEL, 

266 }, 

267 "loggers": { 

268 "django": { 

269 "handlers": ["console"], 

270 "propagate": False, 

271 }, 

272 }, 

273} 

274 

275sentry.configure() 

276 

277# Analytics configuration 

278 

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

280 

281# reCAPTCHA configuration 

282 

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

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

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

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

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

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

289 

290# Content Security Policy 

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

292 

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

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

295 

296CSP_BASE_URI = ["'none'"] 

297 

298CSP_DEFAULT_SRC = ["'self'"] 

299 

300CSP_CONNECT_SRC = ["'self'", "https://api.amplitude.com/"] 

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

302CSP_CONNECT_SRC.extend(env_connect_src) 

303 

304CSP_FONT_SRC = ["'self'", "https://california.azureedge.net/", "https://fonts.gstatic.com/"] 

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

306CSP_FONT_SRC.extend(env_font_src) 

307 

308CSP_FRAME_ANCESTORS = ["'none'"] 

309 

310CSP_FRAME_SRC = ["*.littlepay.com"] 

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

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

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

314if len(env_frame_src) > 0: 314 ↛ 315line 314 didn't jump to line 315 because the condition on line 314 was never true

315 CSP_FRAME_SRC.extend(env_frame_src) 

316 

317CSP_IMG_SRC = [ 

318 "'self'", 

319 "data:", 

320 "*.googleusercontent.com", 

321] 

322 

323# Configuring strict Content Security Policy 

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

325CSP_INCLUDE_NONCE_IN = ["script-src"] 

326 

327CSP_OBJECT_SRC = ["'none'"] 

328 

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

330 CSP_REPORT_URI = [sentry.SENTRY_CSP_REPORT_URI] 

331 

332CSP_SCRIPT_SRC = [ 

333 "'self'", 

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

335 "https://cdn.jsdelivr.net/", 

336 "*.littlepay.com", 

337 "https://code.jquery.com/jquery-3.6.0.min.js", 

338] 

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

340CSP_SCRIPT_SRC.extend(env_script_src) 

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

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

343 

344CSP_STYLE_SRC = [ 

345 "'self'", 

346 "'unsafe-inline'", 

347 "https://california.azureedge.net/", 

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

349 "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/", 

350] 

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

352CSP_STYLE_SRC.extend(env_style_src) 

353 

354# Configuration for requests 

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

356 

357try: 

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

359except Exception: 

360 REQUESTS_CONNECT_TIMEOUT = 3 

361 

362try: 

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

364except Exception: 

365 REQUESTS_READ_TIMEOUT = 20 

366 

367REQUESTS_TIMEOUT = (REQUESTS_CONNECT_TIMEOUT, REQUESTS_READ_TIMEOUT)