• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla / fx-private-relay / b3ea0a1f-ce49-45e3-921e-cbe6e2070cd7

08 Jan 2025 04:56PM CUT coverage: 85.084% (-0.008%) from 85.092%
b3ea0a1f-ce49-45e3-921e-cbe6e2070cd7

push

circleci

web-flow
Merge pull request #5296 from mozilla/dependabot/npm_and_yarn/typescript-5.7.2

Bump typescript from 5.4.5 to 5.7.2

2433 of 3561 branches covered (68.32%)

Branch coverage included in aggregate %.

16995 of 19273 relevant lines covered (88.18%)

9.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.03
/privaterelay/settings.py
1
"""
2
Django settings for privaterelay project.
3

4
Generated by 'django-admin startproject' using Django 2.2.2.
5

6
For more information on this file, see
7
https://docs.djangoproject.com/en/2.2/topics/settings/
8

9
For the full list of settings and their values, see
10
https://docs.djangoproject.com/en/2.2/ref/settings/
11
"""
12

13
from __future__ import annotations
1✔
14

15
import base64
1✔
16
import ipaddress
1✔
17
import os
1✔
18
import sys
1✔
19
from hashlib import sha256
1✔
20
from pathlib import Path
1✔
21
from typing import TYPE_CHECKING, Any, cast, get_args
1✔
22

23
from django.conf.global_settings import LANGUAGES as DEFAULT_LANGUAGES
1✔
24

25
import dj_database_url
1✔
26
import django_stubs_ext
1✔
27
import markus
1✔
28
import sentry_sdk
1✔
29
from csp.constants import NONCE, NONE, SELF, UNSAFE_INLINE
1✔
30
from decouple import Choices, Csv, config
1✔
31
from sentry_sdk.integrations.django import DjangoIntegration
1✔
32
from sentry_sdk.integrations.logging import ignore_logger
1✔
33

34
from .types import CONTENT_SECURITY_POLICY_T, RELAY_CHANNEL_NAME
1✔
35

36
if TYPE_CHECKING:
37
    import wsgiref.headers
38

39
try:
1✔
40
    # Silk is a live profiling and inspection tool for the Django framework
41
    # https://github.com/jazzband/django-silk
42
    import silk  # noqa: F401
1✔
43

44
    HAS_SILK = True
×
45
except ImportError:
1✔
46
    HAS_SILK = False
1✔
47

48
try:
1✔
49
    from privaterelay.glean.server_events import GLEAN_EVENT_MOZLOG_TYPE
1✔
50
except ImportError:
×
51
    # File may not be generated yet. Will be checked at initialization
52
    GLEAN_EVENT_MOZLOG_TYPE = "glean-server-event"
×
53

54
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
55
BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1✔
56
TMP_DIR = os.path.join(BASE_DIR, "tmp")
1✔
57
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
1✔
58

59
# Quick-start development settings - unsuitable for production
60
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
61

62
# defaulting to blank to be production-broken by default
63
SECRET_KEY = config("SECRET_KEY", None)
1✔
64
SECRET_KEY_FALLBACKS = config("SECRET_KEY_FALLBACKS", "", cast=Csv())
1✔
65
SITE_ORIGIN: str | None = config("SITE_ORIGIN", None)
1✔
66

67
ORIGIN_CHANNEL_MAP: dict[str, RELAY_CHANNEL_NAME] = {
1✔
68
    "http://127.0.0.1:8000": "local",
69
    "https://dev.fxprivaterelay.nonprod.cloudops.mozgcp.net": "dev",
70
    "https://stage.fxprivaterelay.nonprod.cloudops.mozgcp.net": "stage",
71
    "https://relay.firefox.com": "prod",
72
}
73
RELAY_CHANNEL: RELAY_CHANNEL_NAME = cast(
1✔
74
    RELAY_CHANNEL_NAME,
75
    config(
76
        "RELAY_CHANNEL",
77
        default=ORIGIN_CHANNEL_MAP.get(SITE_ORIGIN or "", "local"),
78
        cast=Choices(get_args(RELAY_CHANNEL_NAME), cast=str),
79
    ),
80
)
81

82
DEBUG = config("DEBUG", False, cast=bool)
1✔
83
if DEBUG:
1!
84
    INTERNAL_IPS = config("DJANGO_INTERNAL_IPS", default="", cast=Csv())
1✔
85
IN_PYTEST: bool = "pytest" in sys.modules
1✔
86
USE_SILK = DEBUG and HAS_SILK and not IN_PYTEST
1✔
87
DEFAULT_EXCEPTION_REPORTER_FILTER = (
1✔
88
    "privaterelay.debug.RelaySaferExceptionReporterFilter"
89
)
90

91
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
92
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
1✔
93
SECURE_SSL_HOST = config("DJANGO_SECURE_SSL_HOST", None)
1✔
94
SECURE_SSL_REDIRECT = config("DJANGO_SECURE_SSL_REDIRECT", False, cast=bool)
1✔
95
SECURE_REDIRECT_EXEMPT = [
1✔
96
    r"^__version__",
97
    r"^__heartbeat__",
98
    r"^__lbheartbeat__",
99
]
100
SECURE_HSTS_INCLUDE_SUBDOMAINS = config(
1✔
101
    "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", False, cast=bool
102
)
103
SECURE_HSTS_PRELOAD = config("DJANGO_SECURE_HSTS_PRELOAD", False, cast=bool)
1✔
104
SECURE_HSTS_SECONDS = config("DJANGO_SECURE_HSTS_SECONDS", None)
1✔
105
SECURE_BROWSER_XSS_FILTER = config("DJANGO_SECURE_BROWSER_XSS_FILTER", True)
1✔
106
SESSION_COOKIE_SECURE = config("DJANGO_SESSION_COOKIE_SECURE", False, cast=bool)
1✔
107
CSRF_COOKIE_SECURE = config("DJANGO_CSRF_COOKIE_SECURE", False, cast=bool)
1✔
108

109
#
110
# Setup CSP
111
#
112

113
BASKET_ORIGIN = config("BASKET_ORIGIN", "https://basket.mozilla.org")
1✔
114

115
# maps FxA / Mozilla account profile hosts to respective hosts for CSP
116
FXA_BASE_ORIGIN: str = config("FXA_BASE_ORIGIN", "https://accounts.firefox.com")
1✔
117
if FXA_BASE_ORIGIN == "https://accounts.firefox.com":
1!
118
    _AVATAR_IMG_SRC = [
×
119
        "firefoxusercontent.com",
120
        "https://profile.accounts.firefox.com",
121
    ]
122
    _ACCOUNT_CONNECT_SRC = [FXA_BASE_ORIGIN]
×
123
else:
124
    if not FXA_BASE_ORIGIN == "https://accounts.stage.mozaws.net":
1!
125
        raise ValueError(
×
126
            "FXA_BASE_ORIGIN must be either https://accounts.firefox.com or https://accounts.stage.mozaws.net"
127
        )
128
    _AVATAR_IMG_SRC = [
1✔
129
        "mozillausercontent.com",
130
        "https://profile.stage.mozaws.net",
131
    ]
132
    _ACCOUNT_CONNECT_SRC = [
1✔
133
        FXA_BASE_ORIGIN,
134
        # fxaFlowTracker.ts will try this if runtimeData is slow
135
        "https://accounts.firefox.com",
136
    ]
137

138
API_DOCS_ENABLED = config("API_DOCS_ENABLED", False, cast=bool) or DEBUG
1✔
139
_CSP_SCRIPT_INLINE = USE_SILK
1✔
140

141
# When running locally, styles might get refreshed while the server is running, so their
142
# hashes would get oudated. Hence, we just allow all of them.
143
_CSP_STYLE_INLINE = API_DOCS_ENABLED or RELAY_CHANNEL == "local"
1✔
144

145
if API_DOCS_ENABLED:
1!
146
    _API_DOCS_CSP_IMG_SRC = ["data:", "https://cdn.redoc.ly"]
1✔
147
    _API_DOCS_CSP_STYLE_SRC = ["https://fonts.googleapis.com"]
1✔
148
    _API_DOCS_CSP_FONT_SRC = ["https://fonts.gstatic.com"]
1✔
149
    _API_DOCS_CSP_WORKER_SRC = ["blob:"]
1✔
150
else:
151
    _API_DOCS_CSP_IMG_SRC = []
×
152
    _API_DOCS_CSP_STYLE_SRC = []
×
153
    _API_DOCS_CSP_FONT_SRC = []
×
154
    _API_DOCS_CSP_WORKER_SRC = []
×
155

156
# Next.js dynamically inserts the relevant styles when switching pages,
157
# by injecting them as inline styles. We need to explicitly allow those styles
158
# in our Content Security Policy.
159
_CSP_STYLE_HASHES: list[str] = []
1✔
160
if _CSP_STYLE_INLINE:
1!
161
    # 'unsafe-inline' is not compatible with hash sources
162
    _CSP_STYLE_HASHES = []
1✔
163
else:
164
    # When running in production, we want to disallow inline styles that are
165
    # not set by us, so we use an explicit allowlist with the hashes of the
166
    # styles generated by Next.js.
167
    _next_css_path = Path(STATIC_ROOT) / "_next" / "static" / "css"
×
168
    for path in _next_css_path.glob("*.css"):
×
169
        # Use sha256 hashes, to keep in sync with Chrome.
170
        # When CSP rules fail in Chrome, it provides the sha256 hash that would
171
        # have matched, useful for debugging.
172
        content = open(path, "rb").read()
×
173
        the_hash = base64.b64encode(sha256(content).digest()).decode()
×
174
        _CSP_STYLE_HASHES.append(f"'sha256-{the_hash}'")
×
175
    _CSP_STYLE_HASHES.sort()
×
176

177
    # Add the hash for an empty string (sha256-47DEQp...)
178
    # next,js injects an empty style element and then adds the content.
179
    # This hash avoids a spurious CSP error.
180
    empty_hash = base64.b64encode(sha256().digest()).decode()
×
181
    _CSP_STYLE_HASHES.append(f"'sha256-{empty_hash}'")
×
182

183
CONTENT_SECURITY_POLICY: CONTENT_SECURITY_POLICY_T = {
1✔
184
    "DIRECTIVES": {
185
        "default-src": [SELF],
186
        "connect-src": [
187
            SELF,
188
            "https://*.google-analytics.com",
189
            "https://*.analytics.google.com",
190
            "https://*.googletagmanager.com",
191
            "https://location.services.mozilla.com",
192
            "https://api.stripe.com",
193
            BASKET_ORIGIN,
194
        ],
195
        "font-src": [SELF, "https://relay.firefox.com/"],
196
        "frame-src": ["https://js.stripe.com", "https://hooks.stripe.com"],
197
        "img-src": [
198
            SELF,
199
            "https://*.google-analytics.com",
200
            "https://*.googletagmanager.com",
201
        ],
202
        "object-src": [NONE],
203
        "script-src": [
204
            SELF,
205
            NONCE,
206
            "https://www.google-analytics.com/",
207
            "https://*.googletagmanager.com",
208
            "https://js.stripe.com/",
209
        ],
210
        "style-src": [SELF],
211
        "worker-src": [SELF, "blob:"],  # TODO: remove blob: temporary fix for GA4
212
    }
213
}
214
CONTENT_SECURITY_POLICY["DIRECTIVES"]["connect-src"].extend(_ACCOUNT_CONNECT_SRC)
1✔
215
CONTENT_SECURITY_POLICY["DIRECTIVES"]["font-src"].extend(_API_DOCS_CSP_FONT_SRC)
1✔
216
CONTENT_SECURITY_POLICY["DIRECTIVES"]["img-src"].extend(_AVATAR_IMG_SRC)
1✔
217
CONTENT_SECURITY_POLICY["DIRECTIVES"]["img-src"].extend(_API_DOCS_CSP_IMG_SRC)
1✔
218
CONTENT_SECURITY_POLICY["DIRECTIVES"]["style-src"].extend(_API_DOCS_CSP_STYLE_SRC)
1✔
219
CONTENT_SECURITY_POLICY["DIRECTIVES"]["style-src"].extend(_CSP_STYLE_HASHES)
1✔
220
if _CSP_SCRIPT_INLINE:
1!
221
    CONTENT_SECURITY_POLICY["DIRECTIVES"]["script-src"].append(UNSAFE_INLINE)
×
222
if _CSP_STYLE_INLINE:
1!
223
    CONTENT_SECURITY_POLICY["DIRECTIVES"]["style-src"].append(UNSAFE_INLINE)
1✔
224
if _API_DOCS_CSP_WORKER_SRC:
1!
225
    CONTENT_SECURITY_POLICY["DIRECTIVES"]["worker-src"].extend(_API_DOCS_CSP_WORKER_SRC)
1✔
226
if _CSP_REPORT_URI := config("CSP_REPORT_URI", ""):
1!
227
    CONTENT_SECURITY_POLICY["DIRECTIVES"]["report-uri"] = _CSP_REPORT_URI
×
228

229
REFERRER_POLICY = "strict-origin-when-cross-origin"
1✔
230

231
ALLOWED_HOSTS: list[str] = []
1✔
232
DJANGO_ALLOWED_HOSTS = config("DJANGO_ALLOWED_HOST", "", cast=Csv())
1✔
233
if DJANGO_ALLOWED_HOSTS:
1!
234
    ALLOWED_HOSTS += DJANGO_ALLOWED_HOSTS
×
235
DJANGO_ALLOWED_SUBNET = config("DJANGO_ALLOWED_SUBNET", None)
1✔
236
if DJANGO_ALLOWED_SUBNET:
1!
237
    ALLOWED_HOSTS += [str(ip) for ip in ipaddress.IPv4Network(DJANGO_ALLOWED_SUBNET)]
×
238

239

240
# Get our backing resource configs to check if we should install the app
241
ADMIN_ENABLED = config("ADMIN_ENABLED", False, cast=bool)
1✔
242

243

244
AWS_REGION: str | None = config("AWS_REGION", None)
1✔
245
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID", None)
1✔
246
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", None)
1✔
247
AWS_SNS_TOPIC = set(config("AWS_SNS_TOPIC", "", cast=Csv()))
1✔
248
AWS_SNS_KEY_CACHE = config("AWS_SNS_KEY_CACHE", "default")
1✔
249
AWS_SES_CONFIGSET: str | None = config("AWS_SES_CONFIGSET", None)
1✔
250
AWS_SQS_EMAIL_QUEUE_URL = config("AWS_SQS_EMAIL_QUEUE_URL", None)
1✔
251
AWS_SQS_EMAIL_DLQ_URL = config("AWS_SQS_EMAIL_DLQ_URL", None)
1✔
252

253
# Dead-Letter Queue (DLQ) for SNS push subscription
254
AWS_SQS_QUEUE_URL = config("AWS_SQS_QUEUE_URL", None)
1✔
255

256
RELAY_FROM_ADDRESS: str = config("RELAY_FROM_ADDRESS", "")
1✔
257
GOOGLE_ANALYTICS_ID = config("GOOGLE_ANALYTICS_ID", None)
1✔
258
GA4_MEASUREMENT_ID = config("GA4_MEASUREMENT_ID", None)
1✔
259
GOOGLE_APPLICATION_CREDENTIALS: str = config("GOOGLE_APPLICATION_CREDENTIALS", "")
1✔
260
GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64: str = config(
1✔
261
    "GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64", ""
262
)
263
INCLUDE_VPN_BANNER = config("INCLUDE_VPN_BANNER", False, cast=bool)
1✔
264
RECRUITMENT_BANNER_LINK = config("RECRUITMENT_BANNER_LINK", None)
1✔
265
RECRUITMENT_BANNER_TEXT = config("RECRUITMENT_BANNER_TEXT", None)
1✔
266
RECRUITMENT_EMAIL_BANNER_TEXT = config("RECRUITMENT_EMAIL_BANNER_TEXT", None)
1✔
267
RECRUITMENT_EMAIL_BANNER_LINK = config("RECRUITMENT_EMAIL_BANNER_LINK", None)
1✔
268

269
PHONES_ENABLED: bool = config("PHONES_ENABLED", False, cast=bool)
1✔
270
PHONES_NO_CLIENT_CALLS_IN_TEST = False  # Override in tests that do not test clients
1✔
271
TWILIO_ACCOUNT_SID: str | None = config("TWILIO_ACCOUNT_SID", None)
1✔
272
TWILIO_AUTH_TOKEN: str | None = config("TWILIO_AUTH_TOKEN", None)
1✔
273
TWILIO_MAIN_NUMBER: str | None = config("TWILIO_MAIN_NUMBER", None)
1✔
274
TWILIO_SMS_APPLICATION_SID: str | None = config("TWILIO_SMS_APPLICATION_SID", None)
1✔
275
TWILIO_MESSAGING_SERVICE_SID: list[str] = config(
1✔
276
    "TWILIO_MESSAGING_SERVICE_SID", "", cast=Csv()
277
)
278
TWILIO_TEST_ACCOUNT_SID: str | None = config("TWILIO_TEST_ACCOUNT_SID", None)
1✔
279
TWILIO_TEST_AUTH_TOKEN: str | None = config("TWILIO_TEST_AUTH_TOKEN", None)
1✔
280
TWILIO_ALLOWED_COUNTRY_CODES = {
1✔
281
    code.upper()
282
    for code in config("TWILIO_ALLOWED_COUNTRY_CODES", "US,CA,PR", cast=Csv())
283
}
284
TWILIO_NEEDS_10DLC_CAMPAIGN = {
1✔
285
    code.upper() for code in config("TWILIO_NEEDS_10DLC_CAMPAIGN", "US,PR", cast=Csv())
286
}
287
MAX_MINUTES_TO_VERIFY_REAL_PHONE: int = config(
1✔
288
    "MAX_MINUTES_TO_VERIFY_REAL_PHONE", 5, cast=int
289
)
290
MAX_TEXTS_PER_BILLING_CYCLE: int = config("MAX_TEXTS_PER_BILLING_CYCLE", 75, cast=int)
1✔
291
MAX_MINUTES_PER_BILLING_CYCLE: int = config(
1✔
292
    "MAX_MINUTES_PER_BILLING_CYCLE", 50, cast=int
293
)
294
DAYS_PER_BILLING_CYCLE = config("DAYS_PER_BILLING_CYCLE", 30, cast=int)
1✔
295
MAX_DAYS_IN_MONTH = 31
1✔
296
IQ_ENABLED = config("IQ_ENABLED", False, cast=bool)
1✔
297
IQ_FOR_VERIFICATION: bool = config("IQ_FOR_VERIFICATION", False, cast=bool)
1✔
298
IQ_FOR_NEW_NUMBERS = config("IQ_FOR_NEW_NUMBERS", False, cast=bool)
1✔
299
IQ_MAIN_NUMBER: str = config("IQ_MAIN_NUMBER", "")
1✔
300
IQ_OUTBOUND_API_KEY: str = config("IQ_OUTBOUND_API_KEY", "")
1✔
301
IQ_INBOUND_API_KEY = config("IQ_INBOUND_API_KEY", "")
1✔
302
IQ_MESSAGE_API_ORIGIN = config(
1✔
303
    "IQ_MESSAGE_API_ORIGIN", "https://messagebroker.inteliquent.com"
304
)
305
IQ_MESSAGE_PATH = "/msgbroker/rest/publishMessages"
1✔
306
IQ_PUBLISH_MESSAGE_URL: str = f"{IQ_MESSAGE_API_ORIGIN}{IQ_MESSAGE_PATH}"
1✔
307

308
DJANGO_STATSD_ENABLED = config("DJANGO_STATSD_ENABLED", False, cast=bool)
1✔
309
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)
1✔
310
STATSD_ENABLED: bool = DJANGO_STATSD_ENABLED or STATSD_DEBUG
1✔
311
STATSD_HOST = config("DJANGO_STATSD_HOST", "127.0.0.1")
1✔
312
STATSD_PORT = config("DJANGO_STATSD_PORT", "8125")
1✔
313
STATSD_PREFIX = config("DJANGO_STATSD_PREFIX", "fx.private.relay")
1✔
314

315
SERVE_ADDON = config("SERVE_ADDON", None)
1✔
316

317
# Application definition
318
INSTALLED_APPS = [
1✔
319
    "whitenoise.runserver_nostatic",
320
    "django.contrib.staticfiles",
321
    "django.contrib.auth",
322
    "django.contrib.contenttypes",
323
    "django.contrib.sessions",
324
    "django.contrib.messages",
325
    "django.contrib.sites",
326
    "django_filters",
327
    "django_ftl.apps.DjangoFtlConfig",
328
    "dockerflow.django",
329
    "allauth",
330
    "allauth.account",
331
    "allauth.socialaccount",
332
    "allauth.socialaccount.providers.fxa",
333
    "rest_framework",
334
    "rest_framework.authtoken",
335
    "corsheaders",
336
    "csp",
337
    "waffle",
338
    "privaterelay.apps.PrivateRelayConfig",
339
    "api.apps.ApiConfig",
340
]
341

342
if API_DOCS_ENABLED:
1!
343
    INSTALLED_APPS += [
1✔
344
        "drf_spectacular",
345
        "drf_spectacular_sidecar",
346
    ]
347

348
if DEBUG:
1!
349
    INSTALLED_APPS += [
1✔
350
        "debug_toolbar",
351
    ]
352

353
if USE_SILK:
1!
354
    INSTALLED_APPS.append("silk")
×
355

356
if ADMIN_ENABLED:
1!
357
    INSTALLED_APPS += [
×
358
        "django.contrib.admin",
359
    ]
360

361
if AWS_SES_CONFIGSET and AWS_SNS_TOPIC:
1!
362
    INSTALLED_APPS += [
1✔
363
        "emails.apps.EmailsConfig",
364
    ]
365

366
if PHONES_ENABLED:
1!
367
    INSTALLED_APPS += [
1✔
368
        "phones.apps.PhonesConfig",
369
    ]
370

371

372
MIDDLEWARE = ["privaterelay.middleware.ResponseMetrics"]
1✔
373

374
if USE_SILK:
1!
375
    MIDDLEWARE.append("silk.middleware.SilkyMiddleware")
×
376
if DEBUG:
1!
377
    MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
1✔
378

379
MIDDLEWARE += [
1✔
380
    "django.middleware.security.SecurityMiddleware",
381
    "privaterelay.middleware.EagerNonceCSPMiddleware",
382
    "privaterelay.middleware.RedirectRootIfLoggedIn",
383
    "privaterelay.middleware.RelayStaticFilesMiddleware",
384
    "django.contrib.sessions.middleware.SessionMiddleware",
385
    "corsheaders.middleware.CorsMiddleware",
386
    "django.middleware.common.CommonMiddleware",
387
    "django.middleware.csrf.CsrfViewMiddleware",
388
    "django.contrib.auth.middleware.AuthenticationMiddleware",
389
    "django.contrib.messages.middleware.MessageMiddleware",
390
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
391
    "django.middleware.locale.LocaleMiddleware",
392
    "allauth.account.middleware.AccountMiddleware",
393
    "django_ftl.middleware.activate_from_request_language_code",
394
    "django_referrer_policy.middleware.ReferrerPolicyMiddleware",
395
    "dockerflow.django.middleware.DockerflowMiddleware",
396
    "waffle.middleware.WaffleMiddleware",
397
    "privaterelay.middleware.AddDetectedCountryToRequestAndResponseHeaders",
398
    "privaterelay.middleware.StoreFirstVisit",
399
]
400

401
ROOT_URLCONF = "privaterelay.urls"
1✔
402

403
TEMPLATES = [
1✔
404
    {
405
        "BACKEND": "django.template.backends.django.DjangoTemplates",
406
        "DIRS": [
407
            os.path.join(BASE_DIR, "privaterelay", "templates"),
408
        ],
409
        "APP_DIRS": True,
410
        "OPTIONS": {
411
            "context_processors": [
412
                "django.template.context_processors.debug",
413
                "django.template.context_processors.request",
414
                "django.contrib.auth.context_processors.auth",
415
                "django.contrib.messages.context_processors.messages",
416
            ],
417
        },
418
    },
419
]
420

421
RELAY_FIREFOX_DOMAIN: str = config("RELAY_FIREFOX_DOMAIN", "relay.firefox.com")
1✔
422
MOZMAIL_DOMAIN: str = config("MOZMAIL_DOMAIN", "mozmail.com")
1✔
423
MAX_NUM_FREE_ALIASES: int = config("MAX_NUM_FREE_ALIASES", 5, cast=int)
1✔
424
PERIODICAL_PREMIUM_PROD_ID: str = config("PERIODICAL_PREMIUM_PROD_ID", "")
1✔
425
PREMIUM_PLAN_ID_US_MONTHLY: str = config(
1✔
426
    "PREMIUM_PLAN_ID_US_MONTHLY", "price_1LXUcnJNcmPzuWtRpbNOajYS"
427
)
428
PREMIUM_PLAN_ID_US_YEARLY: str = config(
1✔
429
    "PREMIUM_PLAN_ID_US_YEARLY", "price_1LXUdlJNcmPzuWtRKTYg7mpZ"
430
)
431
PHONE_PROD_ID = config("PHONE_PROD_ID", "")
1✔
432
PHONE_PLAN_ID_US_MONTHLY: str = config(
1✔
433
    "PHONE_PLAN_ID_US_MONTHLY", "price_1Li0w8JNcmPzuWtR2rGU80P3"
434
)
435
PHONE_PLAN_ID_US_YEARLY: str = config(
1✔
436
    "PHONE_PLAN_ID_US_YEARLY", "price_1Li15WJNcmPzuWtRIh0F4VwP"
437
)
438
BUNDLE_PROD_ID = config("BUNDLE_PROD_ID", "")
1✔
439
BUNDLE_PLAN_ID_US: str = config("BUNDLE_PLAN_ID_US", "price_1LwoSDJNcmPzuWtR6wPJZeoh")
1✔
440

441
SUBSCRIPTIONS_WITH_UNLIMITED: list[str] = config(
1✔
442
    "SUBSCRIPTIONS_WITH_UNLIMITED", default="", cast=Csv()
443
)
444
SUBSCRIPTIONS_WITH_PHONE: list[str] = config(
1✔
445
    "SUBSCRIPTIONS_WITH_PHONE", default="", cast=Csv()
446
)
447
SUBSCRIPTIONS_WITH_VPN: list[str] = config(
1✔
448
    "SUBSCRIPTIONS_WITH_VPN", default="", cast=Csv()
449
)
450

451
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
452
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
453

454
MAX_ADDRESS_CREATION_PER_DAY: int = config(
1✔
455
    "MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int
456
)
457
MAX_REPLIES_PER_DAY: int = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
458
MAX_FORWARDED_PER_DAY: int = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
459
MAX_FORWARDED_EMAIL_SIZE_PER_DAY: int = config(
1✔
460
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
461
)
462
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
463
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
464
)
465

466
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
467
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
468

469
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
470

471
# Database
472
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
473

474
DATABASE_URL = config(
1✔
475
    "DATABASE_URL", default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3"))
476
)
477
DATABASES = {"default": dj_database_url.parse(DATABASE_URL)}
1✔
478
# Optionally set a test database name.
479
# This is useful for forcing an on-disk database for SQLite.
480
TEST_DB_NAME = config("TEST_DB_NAME", "")
1✔
481
if TEST_DB_NAME:
1!
482
    DATABASES["default"]["TEST"] = {"NAME": TEST_DB_NAME}
×
483

484
REDIS_URL = config("REDIS_URL", "")
1✔
485
REDIS_SELF_SIGNED_CERT = config("REDIS_SELF_SIGNED_CERT", False, bool)
1✔
486
if REDIS_URL:
1!
487
    _redis_options: dict[str, Any] = {
×
488
        "CLIENT_CLASS": "django_redis.client.DefaultClient"
489
    }
490
    # Heroku mini uses self-signed certificates
491
    if REDIS_SELF_SIGNED_CERT:
×
492
        _redis_options["CONNECTION_POOL_KWARGS"] = {"ssl_cert_reqs": None}
×
493

494
    CACHES = {
×
495
        "default": {
496
            "BACKEND": "django_redis.cache.RedisCache",
497
            "LOCATION": REDIS_URL,
498
            "OPTIONS": _redis_options,
499
        }
500
    }
501
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
×
502
    SESSION_CACHE_ALIAS = "default"
×
503
elif RELAY_CHANNEL == "local":
1!
504
    CACHES = {
1✔
505
        "default": {
506
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
507
        }
508
    }
509

510
# Password validation
511
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
512
# only needed when admin UI is enabled
513
if ADMIN_ENABLED:
1!
514
    _DJANGO_PWD_VALIDATION = "django.contrib.auth.password_validation"  # noqa: E501, S105 (long line, possible password)
×
515
    AUTH_PASSWORD_VALIDATORS = [
×
516
        {"NAME": _DJANGO_PWD_VALIDATION + ".UserAttributeSimilarityValidator"},
517
        {"NAME": _DJANGO_PWD_VALIDATION + ".MinimumLengthValidator"},
518
        {"NAME": _DJANGO_PWD_VALIDATION + ".CommonPasswordValidator"},
519
        {"NAME": _DJANGO_PWD_VALIDATION + ".NumericPasswordValidator"},
520
    ]
521

522

523
# Internationalization
524
# https://docs.djangoproject.com/en/2.2/topics/i18n/
525

526
LANGUAGE_CODE = "en"
1✔
527

528
# Mozilla l10n directories use lang-locale language codes,
529
# so we need to add those to LANGUAGES so Django's LocaleMiddleware
530
# can find them.
531
LANGUAGES = DEFAULT_LANGUAGES + [
1✔
532
    ("zh-tw", "Chinese"),
533
    ("zh-cn", "Chinese"),
534
    ("es-es", "Spanish"),
535
    ("pt-pt", "Portuguese"),
536
    ("skr", "Saraiki"),
537
]
538

539
TIME_ZONE = "UTC"
1✔
540

541
USE_I18N = True
1✔
542

543

544
USE_TZ = True
1✔
545

546
STATICFILES_DIRS = [
1✔
547
    os.path.join(BASE_DIR, "frontend/out"),
548
]
549
# Static files (the front-end in /frontend/)
550
# https://whitenoise.evans.io/en/stable/django.html#using-whitenoise-with-webpack-browserify-latest-js-thing
551
STATIC_URL = "/"
1✔
552
if DEBUG:
1!
553
    # In production, we run collectstatic to index all static files.
554
    # However, when running locally, we want to automatically pick up
555
    # all files spewed out by `npm run watch` in /frontend/out,
556
    # and we're fine with the performance impact of that.
557
    WHITENOISE_ROOT = os.path.join(BASE_DIR, "frontend/out")
1✔
558
STORAGES = {
1✔
559
    "default": {
560
        "BACKEND": "django.core.files.storage.FileSystemStorage",
561
    },
562
    "staticfiles": {
563
        "BACKEND": "privaterelay.storage.RelayStaticFilesStorage",
564
    },
565
}
566

567
# Relay does not support user-uploaded files
568
MEDIA_ROOT = None
1✔
569
MEDIA_URL = None
1✔
570

571
WHITENOISE_INDEX_FILE = True
1✔
572

573

574
# See
575
# https://whitenoise.evans.io/en/stable/django.html#WHITENOISE_ADD_HEADERS_FUNCTION
576
# Intended to ensure that the homepage does not get cached in our CDN,
577
# so that the `RedirectRootIfLoggedIn` middleware can kick in for logged-in
578
# users.
579
def set_index_cache_control_headers(
1✔
580
    headers: wsgiref.headers.Headers, path: str, url: str
581
) -> None:
582
    if DEBUG:
1!
583
        home_path = os.path.join(BASE_DIR, "frontend/out", "index.html")
1✔
584
    else:
585
        home_path = os.path.join(STATIC_ROOT, "index.html")
×
586
    if path == home_path:
1✔
587
        headers["Cache-Control"] = "no-cache, public"
1✔
588

589

590
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
591

592
SITE_ID = 1
1✔
593

594
AUTHENTICATION_BACKENDS = (
1✔
595
    "django.contrib.auth.backends.ModelBackend",
596
    "allauth.account.auth_backends.AuthenticationBackend",
597
)
598

599
SOCIALACCOUNT_PROVIDERS = {
1✔
600
    "fxa": {
601
        # Note: to request "profile" scope, must be a trusted Mozilla client
602
        "SCOPE": ["profile", "https://identity.mozilla.com/account/subscriptions"],
603
        "AUTH_PARAMS": {"access_type": "offline"},
604
        "OAUTH_ENDPOINT": config(
605
            "FXA_OAUTH_ENDPOINT", "https://oauth.accounts.firefox.com/v1"
606
        ),
607
        "PROFILE_ENDPOINT": config(
608
            "FXA_PROFILE_ENDPOINT", "https://profile.accounts.firefox.com/v1"
609
        ),
610
        "VERIFIED_EMAIL": True,  # Assume FxA primary email is verified
611
    }
612
}
613

614
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
615
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
616
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
617
SOCIALACCOUNT_STORE_TOKENS = True
1✔
618

619
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
620
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
621
ACCOUNT_USERNAME_REQUIRED = False
1✔
622

623
FXA_REQUESTS_TIMEOUT_SECONDS = config("FXA_REQUESTS_TIMEOUT_SECONDS", 1, cast=int)
1✔
624
FXA_SETTINGS_URL = config("FXA_SETTINGS_URL", f"{FXA_BASE_ORIGIN}/settings")
1✔
625
FXA_SUBSCRIPTIONS_URL = config(
1✔
626
    "FXA_SUBSCRIPTIONS_URL", f"{FXA_BASE_ORIGIN}/subscriptions"
627
)
628
# check https://mozilla.github.io/ecosystem-platform/api#tag/Subscriptions/operation/getOauthMozillasubscriptionsCustomerBillingandsubscriptions  # noqa: E501 (line too long)
629
FXA_ACCOUNTS_ENDPOINT = config(
1✔
630
    "FXA_ACCOUNTS_ENDPOINT",
631
    "https://api.accounts.firefox.com/v1",
632
)
633
FXA_SUPPORT_URL = config("FXA_SUPPORT_URL", f"{FXA_BASE_ORIGIN}/support/")
1✔
634

635
LOGGING = {
1✔
636
    "version": 1,
637
    "filters": {
638
        "request_id": {
639
            "()": "dockerflow.logging.RequestIdLogFilter",
640
        },
641
    },
642
    "formatters": {
643
        "json": {
644
            "()": "dockerflow.logging.JsonLogFormatter",
645
            "logger_name": "fx-private-relay",
646
        }
647
    },
648
    "handlers": {
649
        "console_out": {
650
            "level": "DEBUG",
651
            "class": "logging.StreamHandler",
652
            "stream": sys.stdout,
653
            "formatter": "json",
654
            "filters": ["request_id"],
655
        },
656
        "console_err": {
657
            "level": "DEBUG",
658
            "class": "logging.StreamHandler",
659
            "formatter": "json",
660
            "filters": ["request_id"],
661
        },
662
    },
663
    "loggers": {
664
        "root": {
665
            "handlers": ["console_err"],
666
            "level": "WARNING",
667
        },
668
        "request.summary": {
669
            "handlers": ["console_out"],
670
            "level": "DEBUG",
671
            # pytest's caplog fixture requires propagate=True
672
            # outside of pytest, use propagate=False to avoid double logs
673
            "propagate": IN_PYTEST,
674
        },
675
        "events": {
676
            "handlers": ["console_err"],
677
            "level": "WARNING",
678
            "propagate": IN_PYTEST,
679
        },
680
        "eventsinfo": {
681
            "handlers": ["console_out"],
682
            "level": "INFO",
683
            "propagate": IN_PYTEST,
684
        },
685
        "abusemetrics": {
686
            "handlers": ["console_out"],
687
            "level": "INFO",
688
            "propagate": IN_PYTEST,
689
        },
690
        "studymetrics": {
691
            "handlers": ["console_out"],
692
            "level": "INFO",
693
            "propagate": IN_PYTEST,
694
        },
695
        "markus": {
696
            "handlers": ["console_out"],
697
            "level": "DEBUG",
698
            "propagate": IN_PYTEST,
699
        },
700
        GLEAN_EVENT_MOZLOG_TYPE: {
701
            "handlers": ["console_out"],
702
            "level": "DEBUG",
703
            "propagate": IN_PYTEST,
704
        },
705
        "dockerflow": {
706
            "handlers": ["console_err"],
707
            "level": "WARNING",
708
            "propagate": IN_PYTEST,
709
        },
710
    },
711
}
712

713
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
714
if DEBUG and not IN_PYTEST:
1!
715
    DRF_RENDERERS += [
×
716
        "rest_framework.renderers.BrowsableAPIRenderer",
717
    ]
718

719
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
720
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
721
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
722

723
REST_FRAMEWORK = {
1✔
724
    "DEFAULT_AUTHENTICATION_CLASSES": [
725
        "api.authentication.FxaTokenAuthentication",
726
        "rest_framework.authentication.TokenAuthentication",
727
        "rest_framework.authentication.SessionAuthentication",
728
    ],
729
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
730
    "DEFAULT_RENDERER_CLASSES": DRF_RENDERERS,
731
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
732
    "EXCEPTION_HANDLER": "api.views.relay_exception_handler",
733
}
734
if API_DOCS_ENABLED:
1!
735
    REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"] = "drf_spectacular.openapi.AutoSchema"
1✔
736

737
SPECTACULAR_SETTINGS = {
1✔
738
    "SWAGGER_UI_DIST": "SIDECAR",
739
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
740
    "REDOC_DIST": "SIDECAR",
741
    "TITLE": "Firefox Relay API",
742
    "DESCRIPTION": (
743
        "Keep your email safe from hackers and trackers. This API is built with"
744
        " Django REST Framework and powers the Relay website UI, add-on,"
745
        " Firefox browser, and 3rd-party app integrations."
746
    ),
747
    "VERSION": "1.0",
748
    "SERVE_INCLUDE_SCHEMA": False,
749
    "PREPROCESSING_HOOKS": ["api.schema.preprocess_ignore_deprecated_paths"],
750
    "SORT_OPERATIONS": "api.schema.sort_by_tag",
751
}
752

753
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
754
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
755
else:
756
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
757
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
758

759
# Turn on logging out on GET in development.
760
# This allows `/mock/logout/` in the front-end to clear the
761
# session cookie. Without this, after switching accounts in dev mode,
762
# then logging out again, API requests continue succeeding even without
763
# an auth token:
764
ACCOUNT_LOGOUT_ON_GET = DEBUG
1✔
765

766
# TODO: introduce an environment variable to control CORS_ALLOWED_ORIGINS
767
# https://mozilla-hub.atlassian.net/browse/MPP-3468
768
CORS_URLS_REGEX = r"^/api/"
1✔
769
CORS_ALLOWED_ORIGINS = [
1✔
770
    "https://vault.bitwarden.com",
771
    "https://vault.bitwarden.eu",
772
]
773
if RELAY_CHANNEL in ["dev", "stage"]:
1!
774
    CORS_ALLOWED_ORIGINS += [
×
775
        "https://vault.qa.bitwarden.pw",
776
        "https://vault.euqa.bitwarden.pw",
777
    ]
778
# Allow origins for each environment to help debug cors headers
779
if RELAY_CHANNEL == "local":
1!
780
    # In local dev, next runs on localhost and makes requests to /accounts/
781
    CORS_ALLOWED_ORIGINS += [
1✔
782
        "http://localhost:3000",
783
        "http://0.0.0.0:3000",
784
        "http://127.0.0.1:8000",
785
    ]
786
    CORS_URLS_REGEX = r"^/(api|accounts)/"
1✔
787
if RELAY_CHANNEL == "dev":
1!
788
    CORS_ALLOWED_ORIGINS += [
×
789
        "https://dev.fxprivaterelay.nonprod.cloudops.mozgcp.net",
790
    ]
791
if RELAY_CHANNEL == "stage":
1!
792
    CORS_ALLOWED_ORIGINS += [
×
793
        "https://stage.fxprivaterelay.nonprod.cloudops.mozgcp.net",
794
    ]
795

796
CSRF_TRUSTED_ORIGINS = []
1✔
797
if RELAY_CHANNEL == "local":
1!
798
    # In local development, the React UI can be served up from a different server
799
    # that needs to be allowed to make requests.
800
    # In production, the frontend is served by Django, is therefore on the same
801
    # origin and thus has access to the same cookies.
802
    CORS_ALLOW_CREDENTIALS = True
1✔
803
    SESSION_COOKIE_SAMESITE = None
1✔
804
    CSRF_TRUSTED_ORIGINS += [
1✔
805
        "http://localhost:3000",
806
        "http://0.0.0.0:3000",
807
    ]
808

809
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
810
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
811
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
812
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
813

814
sentry_release: str | None = None
1✔
815
if SENTRY_RELEASE:
1!
816
    sentry_release = SENTRY_RELEASE
×
817
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
818
    sentry_release = CIRCLE_TAG
1✔
819
elif (
×
820
    CIRCLE_SHA1
821
    and CIRCLE_SHA1 != "unknown"
822
    and CIRCLE_BRANCH
823
    and CIRCLE_BRANCH != "unknown"
824
):
825
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
826

827
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
828

829
SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", RELAY_CHANNEL)
1✔
830
# Use "local" as default rather than "prod", to catch ngrok.io URLs
831
if SENTRY_ENVIRONMENT == "prod" and SITE_ORIGIN != "https://relay.firefox.com":
1!
832
    SENTRY_ENVIRONMENT = "local"
×
833

834
sentry_sdk.init(
1✔
835
    dsn=config("SENTRY_DSN", None),
836
    integrations=[DjangoIntegration(cache_spans=not DEBUG)],
837
    debug=SENTRY_DEBUG,
838
    include_local_variables=DEBUG,
839
    release=sentry_release,
840
    environment=SENTRY_ENVIRONMENT,
841
)
842
# Duplicates events for unhandled exceptions, but without useful tracebacks
843
ignore_logger("request.summary")
1✔
844
# Security scanner attempts, no action required
845
# Can be re-enabled when hostname allow list implemented at the load balancer
846
ignore_logger("django.security.DisallowedHost")
1✔
847
# Fluent errors, mostly when a translation is unavailable for the locale.
848
# It is more effective to process these from logs using BigQuery than to track
849
# as events in Sentry.
850
ignore_logger("django_ftl.message_errors")
1✔
851
# Security scanner attempts on Heroku dev, no action required
852
if RELAY_CHANNEL == "dev":
1!
853
    ignore_logger("django.security.SuspiciousFileOperation")
×
854

855

856
_MARKUS_BACKENDS: list[dict[str, Any]] = []
1✔
857
if DJANGO_STATSD_ENABLED:
1!
858
    _MARKUS_BACKENDS.append(
×
859
        {
860
            "class": "markus.backends.datadog.DatadogMetrics",
861
            "options": {
862
                "statsd_host": STATSD_HOST,
863
                "statsd_port": STATSD_PORT,
864
                "statsd_prefix": STATSD_PREFIX,
865
            },
866
        }
867
    )
868
if STATSD_DEBUG:
1!
869
    _MARKUS_BACKENDS.append(
×
870
        {
871
            "class": "markus.backends.logging.LoggingMetrics",
872
            "options": {
873
                "logger_name": "markus",
874
                "leader": "METRICS",
875
            },
876
        }
877
    )
878
markus.configure(backends=_MARKUS_BACKENDS)
1✔
879

880
if USE_SILK:
1!
881
    SILKY_PYTHON_PROFILER = True
×
882
    SILKY_PYTHON_PROFILER_BINARY = True
×
883
    SILKY_PYTHON_PROFILER_RESULT_PATH = ".silk-profiler"
×
884

885
# Settings for manage.py process_emails_from_sqs
886
PROCESS_EMAIL_BATCH_SIZE = config(
1✔
887
    "PROCESS_EMAIL_BATCH_SIZE", 10, cast=Choices(range(1, 11), cast=int)
888
)
889
PROCESS_EMAIL_DELETE_FAILED_MESSAGES = config(
1✔
890
    "PROCESS_EMAIL_DELETE_FAILED_MESSAGES", False, cast=bool
891
)
892
PROCESS_EMAIL_HEALTHCHECK_PATH = config(
1✔
893
    "PROCESS_EMAIL_HEALTHCHECK_PATH", os.path.join(TMP_DIR, "healthcheck.json")
894
)
895
PROCESS_EMAIL_MAX_SECONDS = config("PROCESS_EMAIL_MAX_SECONDS", 0, cast=int) or None
1✔
896
PROCESS_EMAIL_VERBOSITY = config(
1✔
897
    "PROCESS_EMAIL_VERBOSITY", 1, cast=Choices(range(0, 4), cast=int)
898
)
899
PROCESS_EMAIL_VISIBILITY_SECONDS = config(
1✔
900
    "PROCESS_EMAIL_VISIBILITY_SECONDS", 120, cast=int
901
)
902
PROCESS_EMAIL_WAIT_SECONDS = config("PROCESS_EMAIL_WAIT_SECONDS", 5, cast=int)
1✔
903
PROCESS_EMAIL_HEALTHCHECK_MAX_AGE = config(
1✔
904
    "PROCESS_EMAIL_HEALTHCHECK_MAX_AGE", 120, cast=int
905
)
906
PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE = config(
1✔
907
    "PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE",
908
    PROCESS_EMAIL_MAX_SECONDS or 120.0,
909
    cast=float,
910
)
911

912
# Django 3.2 switches default to BigAutoField
913
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
1✔
914

915
# python-dockerflow settings
916
DOCKERFLOW_VERSION_CALLBACK = "privaterelay.utils.get_version_info"
1✔
917
DOCKERFLOW_CHECKS = [
1✔
918
    "dockerflow.django.checks.check_database_connected",
919
    "dockerflow.django.checks.check_migrations_applied",
920
]
921
if REDIS_URL:
1!
922
    DOCKERFLOW_CHECKS.append("dockerflow.django.checks.check_redis_connected")
×
923
DOCKERFLOW_REQUEST_ID_HEADER_NAME = config("DOCKERFLOW_REQUEST_ID_HEADER_NAME", None)
1✔
924
SILENCED_SYSTEM_CHECKS = sorted(
1✔
925
    set(config("DJANGO_SILENCED_SYSTEM_CHECKS", default="", cast=Csv()))
926
    | {
927
        # (models.W040) SQLite does not support indexes with non-key columns.
928
        # RelayAddress index idx_ra_created_by_addon uses this for PostgreSQL.
929
        "models.W040",
930
    }
931
)
932

933
# django-ftl settings
934
AUTO_RELOAD_BUNDLES = False  # Requires pyinotify
1✔
935

936
# accounts that should not have abuse metrics
937
ALLOWED_ACCOUNTS = ["relay-team+e2e@mozilla.com"]
1✔
938

939
# Patching for django-types
940
django_stubs_ext.monkeypatch()
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc