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

mozilla / fx-private-relay / 3f809551-6712-425b-b278-bf1cf7d34ed4

19 Sep 2025 06:01PM UTC coverage: 88.138% (-0.7%) from 88.863%
3f809551-6712-425b-b278-bf1cf7d34ed4

Pull #5885

circleci

joeherm
fix(twilio): Add error handling for flaky Twilio calls
Pull Request #5885: fix(twilio): Add error handling for erroring Twilio calls

2925 of 3955 branches covered (73.96%)

Branch coverage included in aggregate %.

42 of 42 new or added lines in 2 files covered. (100.0%)

116 existing lines in 7 files now uncovered.

18199 of 20012 relevant lines covered (90.94%)

11.23 hits per line

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

77.91
/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 sentry_sdk
1✔
28
from csp.constants import NONCE, NONE, SELF, UNSAFE_INLINE
1✔
29
from decouple import Choices, Csv, config
1✔
30
from sentry_sdk.integrations.django import DjangoIntegration
1✔
31
from sentry_sdk.integrations.logging import ignore_logger
1✔
32

33
from .types import CONTENT_SECURITY_POLICY_T, RELAY_CHANNEL_NAME
1✔
34

35
if TYPE_CHECKING:
36
    import wsgiref.headers
37

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

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

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

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

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

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

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

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

92
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
93
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
1✔
94
SECURE_SSL_HOST = config("SECURE_SSL_HOST", None) or config(
1✔
95
    "DJANGO_SECURE_SSL_HOST", None
96
)
97
SECURE_SSL_REDIRECT = config("SECURE_SSL_REDIRECT", False, cast=bool) or config(
1✔
98
    "DJANGO_SECURE_SSL_REDIRECT", False, cast=bool
99
)
100
SECURE_REDIRECT_EXEMPT = [
1✔
101
    r"^__version__",
102
    r"^__heartbeat__",
103
    r"^__lbheartbeat__",
104
]
105
SECURE_HSTS_INCLUDE_SUBDOMAINS = config(
1✔
106
    "SECURE_HSTS_INCLUDE_SUBDOMAINS", False, cast=bool
107
) or config("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", False, cast=bool)
108
SECURE_HSTS_PRELOAD = config("SECURE_HSTS_PRELOAD", False, cast=bool) or config(
1✔
109
    "DJANGO_SECURE_HSTS_PRELOAD", False, cast=bool
110
)
111
SECURE_HSTS_SECONDS = config("SECURE_HSTS_SECONDS", None) or config(
1✔
112
    "DJANGO_SECURE_HSTS_SECONDS", None
113
)
114
# Default to "false" in first envvar check so that we fall back to the GCP v1 value
115
SECURE_BROWSER_XSS_FILTER = config("SECURE_BROWSER_XSS_FILTER", False) or config(
1✔
116
    "DJANGO_SECURE_BROWSER_XSS_FILTER", True
117
)
118
SESSION_COOKIE_SECURE = config("DJANGO_SESSION_COOKIE_SECURE", False, cast=bool)
1✔
119
CSRF_COOKIE_SECURE = config("DJANGO_CSRF_COOKIE_SECURE", False, cast=bool)
1✔
120

121
#
122
# Setup CSP
123
#
124

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

127
# maps FxA / Mozilla account profile hosts to respective hosts for CSP
128
FXA_BASE_ORIGIN: str = config("FXA_BASE_ORIGIN", "https://accounts.firefox.com")
1✔
129
if FXA_BASE_ORIGIN == "https://accounts.firefox.com":
1!
130
    _AVATAR_IMG_SRC = [
×
131
        "firefoxusercontent.com",
132
        "https://profile.accounts.firefox.com",
133
    ]
134
    _ACCOUNT_CONNECT_SRC = [FXA_BASE_ORIGIN]
×
135
else:
136
    if not FXA_BASE_ORIGIN == "https://accounts.stage.mozaws.net":
1!
137
        raise ValueError(
×
138
            "FXA_BASE_ORIGIN must be either https://accounts.firefox.com or https://accounts.stage.mozaws.net"
139
        )
140
    _AVATAR_IMG_SRC = [
1✔
141
        "mozillausercontent.com",
142
        "https://profile.stage.mozaws.net",
143
    ]
144
    _ACCOUNT_CONNECT_SRC = [
1✔
145
        FXA_BASE_ORIGIN,
146
        # fxaFlowTracker.ts will try this if runtimeData is slow
147
        "https://accounts.firefox.com",
148
    ]
149

150
API_DOCS_ENABLED = config("API_DOCS_ENABLED", False, cast=bool) or DEBUG
1✔
151
_CSP_SCRIPT_INLINE = USE_SILK
1✔
152

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

157
if API_DOCS_ENABLED:
1!
158
    _API_DOCS_CSP_IMG_SRC = ["data:", "https://cdn.redoc.ly"]
1✔
159
    _API_DOCS_CSP_STYLE_SRC = ["https://fonts.googleapis.com"]
1✔
160
    _API_DOCS_CSP_FONT_SRC = ["https://fonts.gstatic.com"]
1✔
161
    _API_DOCS_CSP_WORKER_SRC = ["blob:"]
1✔
162
else:
163
    _API_DOCS_CSP_IMG_SRC = []
×
164
    _API_DOCS_CSP_STYLE_SRC = []
×
165
    _API_DOCS_CSP_FONT_SRC = []
×
166
    _API_DOCS_CSP_WORKER_SRC = []
×
167

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

189
    # Add the hash for an empty string (sha256-47DEQp...)
190
    # next,js injects an empty style element and then adds the content.
191
    # This hash avoids a spurious CSP error.
192
    empty_hash = base64.b64encode(sha256().digest()).decode()
×
193
    _CSP_STYLE_HASHES.append(f"'sha256-{empty_hash}'")
×
194

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

241
REFERRER_POLICY = "strict-origin-when-cross-origin"
1✔
242

243
ALLOWED_HOSTS: list[str] = []
1✔
244
DJANGO_ALLOWED_HOSTS = config("ALLOWED_HOSTS", "", cast=Csv()) or config(
1✔
245
    "DJANGO_ALLOWED_HOST", "", cast=Csv()
246
)
247

248
if DJANGO_ALLOWED_HOSTS:
1!
249
    ALLOWED_HOSTS += DJANGO_ALLOWED_HOSTS
×
250
ALLOWED_SUBNET = config("ALLOWED_SUBNET", None) or config("DJANGO_ALLOWED_SUBNET", None)
1✔
251
if ALLOWED_SUBNET:
1!
252
    ALLOWED_HOSTS += [str(ip) for ip in ipaddress.IPv4Network(ALLOWED_SUBNET)]
×
253

254

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

258

259
AWS_REGION: str | None = config("AWS_REGION", None)
1✔
260
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID", None)
1✔
261
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", None)
1✔
262
AWS_SNS_TOPIC = set(config("AWS_SNS_TOPIC", "", cast=Csv()))
1✔
263
AWS_SNS_KEY_CACHE = config("AWS_SNS_KEY_CACHE", "default")
1✔
264
AWS_SES_CONFIGSET: str | None = config("AWS_SES_CONFIGSET", None)
1✔
265
AWS_SQS_EMAIL_QUEUE_URL = config("AWS_SQS_EMAIL_QUEUE_URL", None)
1✔
266
AWS_SQS_EMAIL_DLQ_URL = config("AWS_SQS_EMAIL_DLQ_URL", None)
1✔
267

268
RELAY_FROM_ADDRESS: str = config("RELAY_FROM_ADDRESS", "")
1✔
269
GOOGLE_ANALYTICS_ID = config("GOOGLE_ANALYTICS_ID", None)
1✔
270
GA4_MEASUREMENT_ID = config("GA4_MEASUREMENT_ID", None)
1✔
271
GOOGLE_APPLICATION_CREDENTIALS: str = config("GOOGLE_APPLICATION_CREDENTIALS", "")
1✔
272
GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64: str = config(
1✔
273
    "GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64", ""
274
)
275
RECRUITMENT_BANNER_LINK = config("RECRUITMENT_BANNER_LINK", None)
1✔
276
RECRUITMENT_BANNER_TEXT = config("RECRUITMENT_BANNER_TEXT", None)
1✔
277
RECRUITMENT_EMAIL_BANNER_TEXT = config("RECRUITMENT_EMAIL_BANNER_TEXT", None)
1✔
278
RECRUITMENT_EMAIL_BANNER_LINK = config("RECRUITMENT_EMAIL_BANNER_LINK", None)
1✔
279

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

319
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)
1✔
320
STATSD_ENABLED: bool = (
1✔
321
    config("STATSD_ENABLED", False, cast=bool)
322
    or config("DJANGO_STATSD_ENABLED", False, cast=bool)
323
    or STATSD_DEBUG
324
)
325
STATSD_HOST = config("STATSD_HOST", "") or config("DJANGO_STATSD_HOST", "127.0.0.1")
1✔
326

327
STATSD_PORT = config("STATSD_PORT", "") or config("DJANGO_STATSD_PORT", "8125")
1✔
328
STATSD_PREFIX = config("STATSD_PREFIX", "") or config(
1✔
329
    "DJANGO_STATSD_PREFIX", "firefox_relay"
330
)
331

332
SERVE_ADDON = config("SERVE_ADDON", None)
1✔
333

334
# Application definition
335
INSTALLED_APPS = [
1✔
336
    "whitenoise.runserver_nostatic",
337
    "django.contrib.staticfiles",
338
    "django.contrib.auth",
339
    "django.contrib.contenttypes",
340
    "django.contrib.sessions",
341
    "django.contrib.messages",
342
    "django.contrib.sites",
343
    "django_filters",
344
    "django_ftl.apps.DjangoFtlConfig",
345
    "dockerflow.django",
346
    "allauth",
347
    "allauth.account",
348
    "allauth.socialaccount",
349
    "allauth.socialaccount.providers.fxa",
350
    "rest_framework",
351
    "rest_framework.authtoken",
352
    "corsheaders",
353
    "csp",
354
    "waffle",
355
    "privaterelay.apps.PrivateRelayConfig",
356
    "api.apps.ApiConfig",
357
]
358

359
if API_DOCS_ENABLED:
1!
360
    INSTALLED_APPS += [
1✔
361
        "drf_spectacular",
362
        "drf_spectacular_sidecar",
363
    ]
364

365
if DEBUG:
1!
366
    INSTALLED_APPS += [
1✔
367
        "debug_toolbar",
368
    ]
369

370
if USE_SILK:
1!
UNCOV
371
    INSTALLED_APPS.append("silk")
×
372

373
if ADMIN_ENABLED:
1!
UNCOV
374
    INSTALLED_APPS += [
×
375
        "django.contrib.admin",
376
    ]
377

378
if AWS_SES_CONFIGSET and AWS_SNS_TOPIC:
1!
379
    INSTALLED_APPS += [
1✔
380
        "emails.apps.EmailsConfig",
381
    ]
382

383
if PHONES_ENABLED:
1!
384
    INSTALLED_APPS += [
1✔
385
        "phones.apps.PhonesConfig",
386
    ]
387

388

389
MIDDLEWARE = ["privaterelay.middleware.ResponseMetrics"]
1✔
390

391
if USE_SILK:
1!
UNCOV
392
    MIDDLEWARE.append("silk.middleware.SilkyMiddleware")
×
393
if DEBUG:
1!
394
    MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
1✔
395

396
MIDDLEWARE += [
1✔
397
    "django.middleware.security.SecurityMiddleware",
398
    "privaterelay.middleware.EagerNonceCSPMiddleware",
399
    "privaterelay.middleware.RedirectRootIfLoggedIn",
400
    "privaterelay.middleware.RelayStaticFilesMiddleware",
401
    "django.contrib.sessions.middleware.SessionMiddleware",
402
    "corsheaders.middleware.CorsMiddleware",
403
    "django.middleware.common.CommonMiddleware",
404
    "django.middleware.csrf.CsrfViewMiddleware",
405
    "django.contrib.auth.middleware.AuthenticationMiddleware",
406
    "django.contrib.messages.middleware.MessageMiddleware",
407
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
408
    "django.middleware.locale.LocaleMiddleware",
409
    "allauth.account.middleware.AccountMiddleware",
410
    "django_ftl.middleware.activate_from_request_language_code",
411
    "django_referrer_policy.middleware.ReferrerPolicyMiddleware",
412
    "dockerflow.django.middleware.DockerflowMiddleware",
413
    "waffle.middleware.WaffleMiddleware",
414
    "privaterelay.middleware.AddDetectedCountryToRequestAndResponseHeaders",
415
    "privaterelay.middleware.StoreFirstVisit",
416
    "privaterelay.middleware.GleanApiAccessMiddleware",
417
]
418

419
ROOT_URLCONF = "privaterelay.urls"
1✔
420

421
TEMPLATES = [
1✔
422
    {
423
        "BACKEND": "django.template.backends.django.DjangoTemplates",
424
        "DIRS": [
425
            os.path.join(BASE_DIR, "privaterelay", "templates"),
426
        ],
427
        "APP_DIRS": True,
428
        "OPTIONS": {
429
            "context_processors": [
430
                "django.template.context_processors.debug",
431
                "django.template.context_processors.request",
432
                "django.contrib.auth.context_processors.auth",
433
                "django.contrib.messages.context_processors.messages",
434
            ],
435
        },
436
    },
437
]
438

439
RELAY_FIREFOX_DOMAIN: str = config("RELAY_FIREFOX_DOMAIN", "relay.firefox.com")
1✔
440
MOZMAIL_DOMAIN: str = config("MOZMAIL_DOMAIN", "mozmail.com")
1✔
441
MAX_NUM_FREE_ALIASES: int = config("MAX_NUM_FREE_ALIASES", 5, cast=int)
1✔
442
PERIODICAL_PREMIUM_PROD_ID: str = config("PERIODICAL_PREMIUM_PROD_ID", "")
1✔
443
PREMIUM_PLAN_ID_US_MONTHLY: str = config(
1✔
444
    "PREMIUM_PLAN_ID_US_MONTHLY", "price_1LXUcnJNcmPzuWtRpbNOajYS"
445
)
446
PREMIUM_PLAN_ID_US_YEARLY: str = config(
1✔
447
    "PREMIUM_PLAN_ID_US_YEARLY", "price_1LXUdlJNcmPzuWtRKTYg7mpZ"
448
)
449
PHONE_PROD_ID = config("PHONE_PROD_ID", "")
1✔
450
PHONE_PLAN_ID_US_MONTHLY: str = config(
1✔
451
    "PHONE_PLAN_ID_US_MONTHLY", "price_1Li0w8JNcmPzuWtR2rGU80P3"
452
)
453
PHONE_PLAN_ID_US_YEARLY: str = config(
1✔
454
    "PHONE_PLAN_ID_US_YEARLY", "price_1Li15WJNcmPzuWtRIh0F4VwP"
455
)
456
BUNDLE_PROD_ID = config("BUNDLE_PROD_ID", "")
1✔
457
BUNDLE_PLAN_ID_US: str = config("BUNDLE_PLAN_ID_US", "price_1LwoSDJNcmPzuWtR6wPJZeoh")
1✔
458
MEGABUNDLE_PROD_ID = config("MEGABUNDLE_PROD_ID", "prod_SFb8iVuZIOPREe")
1✔
459
MEGABUNDLE_PLAN_ID_US: str = config(
1✔
460
    "MEGABUNDLE_PLAN_ID_US", "price_1RMAopKb9q6OnNsLSGe1vLtt"
461
)
462

463
SUBSCRIPTIONS_WITH_UNLIMITED: list[str] = config(
1✔
464
    "SUBSCRIPTIONS_WITH_UNLIMITED", default="", cast=Csv()
465
)
466
SUBSCRIPTIONS_WITH_PHONE: list[str] = config(
1✔
467
    "SUBSCRIPTIONS_WITH_PHONE", default="", cast=Csv()
468
)
469
SUBSCRIPTIONS_WITH_VPN: list[str] = config(
1✔
470
    "SUBSCRIPTIONS_WITH_VPN", default="", cast=Csv()
471
)
472

473
SUBSCRIPTIONS_THAT_MEGABUNDLE_PROVIDES: list[str] = config(
1✔
474
    "SUBSCRIPTIONS_THAT_MEGABUNDLE_PROVIDES", default="", cast=Csv()
475
)
476

477
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
478
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
479

480
MAX_ADDRESS_CREATION_PER_DAY: int = config(
1✔
481
    "MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int
482
)
483
MAX_REPLIES_PER_DAY: int = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
484
MAX_FORWARDED_PER_DAY: int = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
485
MAX_FORWARDED_EMAIL_SIZE_PER_DAY: int = config(
1✔
486
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
487
)
488
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
489
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
490
)
491

492
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
493
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
494

495
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
496

497
# Database
498
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
499

500
DATABASE_URL = config(
1✔
501
    "DATABASE_URL", default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3"))
502
)
503
DATABASES = {"default": dj_database_url.parse(DATABASE_URL)}
1✔
504
# Optionally set a test database name.
505
# This is useful for forcing an on-disk database for SQLite.
506
TEST_DB_NAME = config("TEST_DB_NAME", "")
1✔
507
if TEST_DB_NAME:
1!
UNCOV
508
    DATABASES["default"]["TEST"] = {"NAME": TEST_DB_NAME}
×
509

510
REDIS_URL = config("REDIS_URL", "")
1✔
511
REDIS_SELF_SIGNED_CERT = config("REDIS_SELF_SIGNED_CERT", False, bool)
1✔
512
if REDIS_URL:
1!
UNCOV
513
    _redis_options: dict[str, Any] = {
×
514
        "CLIENT_CLASS": "django_redis.client.DefaultClient"
515
    }
516
    # Heroku mini uses self-signed certificates
UNCOV
517
    if REDIS_SELF_SIGNED_CERT:
×
UNCOV
518
        _redis_options["CONNECTION_POOL_KWARGS"] = {
×
519
            "ssl_cert_reqs": None,
520
            "ssl_check_hostname": False,
521
        }
522

UNCOV
523
    CACHES = {
×
524
        "default": {
525
            "BACKEND": "django_redis.cache.RedisCache",
526
            "LOCATION": REDIS_URL,
527
            "OPTIONS": _redis_options,
528
        }
529
    }
UNCOV
530
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
×
UNCOV
531
    SESSION_CACHE_ALIAS = "default"
×
532
elif RELAY_CHANNEL == "local":
1!
533
    CACHES = {
1✔
534
        "default": {
535
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
536
        }
537
    }
538

539
# Password validation
540
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
541
# only needed when admin UI is enabled
542
if ADMIN_ENABLED:
1!
UNCOV
543
    _DJANGO_PWD_VALIDATION = "django.contrib.auth.password_validation"  # noqa: E501, S105 (long line, possible password)
×
UNCOV
544
    AUTH_PASSWORD_VALIDATORS = [
×
545
        {"NAME": _DJANGO_PWD_VALIDATION + ".UserAttributeSimilarityValidator"},
546
        {"NAME": _DJANGO_PWD_VALIDATION + ".MinimumLengthValidator"},
547
        {"NAME": _DJANGO_PWD_VALIDATION + ".CommonPasswordValidator"},
548
        {"NAME": _DJANGO_PWD_VALIDATION + ".NumericPasswordValidator"},
549
    ]
550

551

552
# Internationalization
553
# https://docs.djangoproject.com/en/2.2/topics/i18n/
554

555
LANGUAGE_CODE = "en"
1✔
556

557
# Mozilla l10n directories use lang-locale language codes,
558
# so we need to add those to LANGUAGES so Django's LocaleMiddleware
559
# can find them.
560
LANGUAGES = DEFAULT_LANGUAGES + [
1✔
561
    ("zh-tw", "Chinese"),
562
    ("zh-cn", "Chinese"),
563
    ("es-es", "Spanish"),
564
    ("pt-pt", "Portuguese"),
565
    ("skr", "Saraiki"),
566
]
567

568
TIME_ZONE = "UTC"
1✔
569

570
USE_I18N = True
1✔
571

572

573
USE_TZ = True
1✔
574

575
STATICFILES_DIRS = [
1✔
576
    os.path.join(BASE_DIR, "frontend/out"),
577
]
578
# Static files (the front-end in /frontend/)
579
# https://whitenoise.evans.io/en/stable/django.html#using-whitenoise-with-webpack-browserify-latest-js-thing
580
STATIC_URL = "/"
1✔
581
if DEBUG:
1!
582
    # In production, we run collectstatic to index all static files.
583
    # However, when running locally, we want to automatically pick up
584
    # all files spewed out by `npm run watch` in /frontend/out,
585
    # and we're fine with the performance impact of that.
586
    WHITENOISE_ROOT = os.path.join(BASE_DIR, "frontend/out")
1✔
587
STORAGES = {
1✔
588
    "default": {
589
        "BACKEND": "django.core.files.storage.FileSystemStorage",
590
    },
591
    "staticfiles": {
592
        "BACKEND": "privaterelay.storage.RelayStaticFilesStorage",
593
    },
594
}
595

596
# Relay does not support user-uploaded files
597
MEDIA_ROOT = None
1✔
598
MEDIA_URL = None
1✔
599

600
WHITENOISE_INDEX_FILE = True
1✔
601

602

603
# See
604
# https://whitenoise.evans.io/en/stable/django.html#WHITENOISE_ADD_HEADERS_FUNCTION
605
# Intended to ensure that the homepage does not get cached in our CDN,
606
# so that the `RedirectRootIfLoggedIn` middleware can kick in for logged-in
607
# users.
608
def set_index_cache_control_headers(
1✔
609
    headers: wsgiref.headers.Headers, path: str, url: str
610
) -> None:
611
    if DEBUG:
1!
612
        home_path = os.path.join(BASE_DIR, "frontend/out", "index.html")
1✔
613
    else:
UNCOV
614
        home_path = os.path.join(STATIC_ROOT, "index.html")
×
615
    if path == home_path:
1✔
616
        headers["Cache-Control"] = "no-cache, public"
1✔
617

618

619
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
620

621
SITE_ID = 1
1✔
622

623
AUTHENTICATION_BACKENDS = (
1✔
624
    "django.contrib.auth.backends.ModelBackend",
625
    "allauth.account.auth_backends.AuthenticationBackend",
626
)
627

628
SOCIALACCOUNT_PROVIDERS = {
1✔
629
    "fxa": {
630
        # Note: to request "profile" scope, must be a trusted Mozilla client
631
        "SCOPE": ["profile", "https://identity.mozilla.com/account/subscriptions"],
632
        "AUTH_PARAMS": {"access_type": "offline"},
633
        "OAUTH_ENDPOINT": config(
634
            "FXA_OAUTH_ENDPOINT", "https://oauth.accounts.firefox.com/v1"
635
        ),
636
        "PROFILE_ENDPOINT": config(
637
            "FXA_PROFILE_ENDPOINT", "https://profile.accounts.firefox.com/v1"
638
        ),
639
        "VERIFIED_EMAIL": True,  # Assume FxA primary email is verified
640
    }
641
}
642

643
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
644
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
645
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
646
SOCIALACCOUNT_STORE_TOKENS = True
1✔
647

648
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
649
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
650

651
FXA_REQUESTS_TIMEOUT_SECONDS = config("FXA_REQUESTS_TIMEOUT_SECONDS", 1, cast=int)
1✔
652
FXA_SETTINGS_URL = config("FXA_SETTINGS_URL", f"{FXA_BASE_ORIGIN}/settings")
1✔
653
FXA_SUBSCRIPTIONS_URL = config(
1✔
654
    "FXA_SUBSCRIPTIONS_URL", f"{FXA_BASE_ORIGIN}/subscriptions"
655
)
656
# check https://mozilla.github.io/ecosystem-platform/api#tag/Subscriptions/operation/getOauthMozillasubscriptionsCustomerBillingandsubscriptions  # noqa: E501 (line too long)
657
FXA_ACCOUNTS_ENDPOINT = config(
1✔
658
    "FXA_ACCOUNTS_ENDPOINT",
659
    "https://api.accounts.firefox.com/v1",
660
)
661
FXA_SUPPORT_URL = config("FXA_SUPPORT_URL", f"{FXA_BASE_ORIGIN}/support/")
1✔
662
USE_SUBPLAT3 = config("USE_SUBPLAT3", False, cast=bool)
1✔
663
SUBPLAT3_HOST = (
1✔
664
    "https://payments.firefox.com"
665
    if FXA_BASE_ORIGIN == "https://accounts.firefox.com"
666
    else "https://payments-next.allizom.org"
667
)
668
SUBPLAT3_PREMIUM_PRODUCT_KEY = config(
1✔
669
    "SUBPLAT3_PREMIUM_PRODUCT_KEY", "relay-premium-127", cast=str
670
)
671
SUBPLAT3_PHONES_PRODUCT_KEY = config(
1✔
672
    "SUBPLAT3_PHONES_PRODUCT_KEY", "relay-premium-127-phone", cast=str
673
)
674
SUBPLAT3_BUNDLE_PRODUCT_KEY = config(
1✔
675
    "SUBPLAT3_BUNDLE_PRODUCT_KEY", "bundle-relay-vpn-dev", cast=str
676
)
677
SUBPLAT3_MEGABUNDLE_PRODUCT_KEY = config(
1✔
678
    "SUBPLAT3_MEGABUNDLE_PRODUCT_KEY", "privacyprotectionplan", cast=str
679
)
680

681
LOGGING = {
1✔
682
    "version": 1,
683
    "filters": {
684
        "request_id": {
685
            "()": "dockerflow.logging.RequestIdLogFilter",
686
        },
687
    },
688
    "formatters": {
689
        "json": {
690
            "()": "dockerflow.logging.JsonLogFormatter",
691
            "logger_name": "fx-private-relay",
692
        }
693
    },
694
    "handlers": {
695
        "console_out": {
696
            "level": "DEBUG",
697
            "class": "logging.StreamHandler",
698
            "stream": sys.stdout,
699
            "formatter": "json",
700
            "filters": ["request_id"],
701
        },
702
        "console_err": {
703
            "level": "DEBUG",
704
            "class": "logging.StreamHandler",
705
            "formatter": "json",
706
            "filters": ["request_id"],
707
        },
708
    },
709
    "loggers": {
710
        "root": {
711
            "handlers": ["console_err"],
712
            "level": "WARNING",
713
        },
714
        "request.summary": {
715
            "handlers": ["console_out"],
716
            "level": "DEBUG",
717
            # pytest's caplog fixture requires propagate=True
718
            # outside of pytest, use propagate=False to avoid double logs
719
            "propagate": IN_PYTEST,
720
        },
721
        "events": {
722
            "handlers": ["console_err"],
723
            "level": "WARNING",
724
            "propagate": IN_PYTEST,
725
        },
726
        "eventsinfo": {
727
            "handlers": ["console_out"],
728
            "level": "INFO",
729
            "propagate": IN_PYTEST,
730
        },
731
        "abusemetrics": {
732
            "handlers": ["console_out"],
733
            "level": "INFO",
734
            "propagate": IN_PYTEST,
735
        },
736
        "studymetrics": {
737
            "handlers": ["console_out"],
738
            "level": "INFO",
739
            "propagate": IN_PYTEST,
740
        },
741
        "markus": {
742
            "handlers": ["console_out"],
743
            "level": "DEBUG",
744
            "propagate": IN_PYTEST,
745
        },
746
        GLEAN_EVENT_MOZLOG_TYPE: {
747
            "handlers": ["console_out"],
748
            "level": "DEBUG",
749
            "propagate": IN_PYTEST,
750
        },
751
        "dockerflow": {
752
            "handlers": ["console_err"],
753
            "level": "WARNING",
754
            "propagate": IN_PYTEST,
755
        },
756
    },
757
}
758

759
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
760
if DEBUG and not IN_PYTEST:
1!
UNCOV
761
    DRF_RENDERERS += [
×
762
        "rest_framework.renderers.BrowsableAPIRenderer",
763
    ]
764

765
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
766
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
767
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
768

769
REST_FRAMEWORK = {
1✔
770
    "DEFAULT_AUTHENTICATION_CLASSES": [
771
        "api.authentication.FxaTokenAuthentication",
772
        "rest_framework.authentication.TokenAuthentication",
773
        "rest_framework.authentication.SessionAuthentication",
774
    ],
775
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
776
    "DEFAULT_RENDERER_CLASSES": DRF_RENDERERS,
777
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
778
    "EXCEPTION_HANDLER": "api.views.relay_exception_handler",
779
}
780
if API_DOCS_ENABLED:
1!
781
    REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"] = "drf_spectacular.openapi.AutoSchema"
1✔
782

783
SPECTACULAR_SETTINGS = {
1✔
784
    "SWAGGER_UI_DIST": "SIDECAR",
785
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
786
    "REDOC_DIST": "SIDECAR",
787
    "TITLE": "Firefox Relay API",
788
    "DESCRIPTION": (
789
        "Keep your email safe from hackers and trackers. This API is built with"
790
        " Django REST Framework and powers the Relay website UI, add-on,"
791
        " Firefox browser, and 3rd-party app integrations."
792
    ),
793
    "VERSION": "1.0",
794
    "SERVE_INCLUDE_SCHEMA": False,
795
    "PREPROCESSING_HOOKS": ["api.schema.preprocess_ignore_deprecated_paths"],
796
    "SORT_OPERATIONS": "api.schema.sort_by_tag",
797
}
798

799
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
800
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
801
else:
UNCOV
802
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
803
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
804

805
# Turn on logging out on GET in development.
806
# This allows `/mock/logout/` in the front-end to clear the
807
# session cookie. Without this, after switching accounts in dev mode,
808
# then logging out again, API requests continue succeeding even without
809
# an auth token:
810
ACCOUNT_LOGOUT_ON_GET = DEBUG
1✔
811

812
# TODO: introduce an environment variable to control CORS_ALLOWED_ORIGINS
813
# https://mozilla-hub.atlassian.net/browse/MPP-3468
814
CORS_URLS_REGEX = r"^/api/"
1✔
815
CORS_ALLOWED_ORIGINS = [
1✔
816
    "https://vault.bitwarden.com",
817
    "https://vault.bitwarden.eu",
818
]
819
if RELAY_CHANNEL in ["dev", "stage"]:
1!
UNCOV
820
    CORS_ALLOWED_ORIGINS += [
×
821
        "https://vault.qa.bitwarden.pw",
822
        "https://vault.euqa.bitwarden.pw",
823
    ]
824
# Allow origins for each environment to help debug cors headers
825
if RELAY_CHANNEL == "local":
1!
826
    # In local dev, next runs on localhost and makes requests to /accounts/
827
    CORS_ALLOWED_ORIGINS += [
1✔
828
        "http://localhost:3000",
829
        "http://0.0.0.0:3000",
830
        "http://127.0.0.1:8000",
831
    ]
832
    CORS_URLS_REGEX = r"^/(api|accounts)/"
1✔
833
if RELAY_CHANNEL == "dev":
1!
UNCOV
834
    CORS_ALLOWED_ORIGINS += [
×
835
        "https://dev.fxprivaterelay.nonprod.cloudops.mozgcp.net",
836
    ]
837
if RELAY_CHANNEL == "stage":
1!
UNCOV
838
    CORS_ALLOWED_ORIGINS += [
×
839
        "https://stage.fxprivaterelay.nonprod.cloudops.mozgcp.net",
840
    ]
841

842
CSRF_TRUSTED_ORIGINS = []
1✔
843
if RELAY_CHANNEL == "local":
1!
844
    # In local development, the React UI can be served up from a different server
845
    # that needs to be allowed to make requests.
846
    # In production, the frontend is served by Django, is therefore on the same
847
    # origin and thus has access to the same cookies.
848
    CORS_ALLOW_CREDENTIALS = True
1✔
849
    SESSION_COOKIE_SAMESITE = None
1✔
850
    CSRF_TRUSTED_ORIGINS += [
1✔
851
        "http://localhost:3000",
852
        "http://0.0.0.0:3000",
853
    ]
854

855
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
856
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
857
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
858
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
859

860
sentry_release: str | None = None
1✔
861
if SENTRY_RELEASE:
1!
UNCOV
862
    sentry_release = SENTRY_RELEASE
×
863
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
864
    sentry_release = CIRCLE_TAG
1✔
UNCOV
865
elif (
×
866
    CIRCLE_SHA1
867
    and CIRCLE_SHA1 != "unknown"
868
    and CIRCLE_BRANCH
869
    and CIRCLE_BRANCH != "unknown"
870
):
UNCOV
871
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
872

873
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
874

875
SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", RELAY_CHANNEL)
1✔
876
# Use "local" as default rather than "prod", to catch ngrok.io URLs
877
if SENTRY_ENVIRONMENT == "prod" and SITE_ORIGIN != "https://relay.firefox.com":
1!
UNCOV
878
    SENTRY_ENVIRONMENT = "local"
×
879

880
sentry_sdk.init(
1✔
881
    dsn=config("SENTRY_DSN", None),
882
    integrations=[DjangoIntegration(cache_spans=not DEBUG)],
883
    debug=SENTRY_DEBUG,
884
    include_local_variables=DEBUG,
885
    release=sentry_release,
886
    environment=SENTRY_ENVIRONMENT,
887
)
888
# Duplicates events for unhandled exceptions, but without useful tracebacks
889
ignore_logger("request.summary")
1✔
890
# Security scanner attempts, no action required
891
# Can be re-enabled when hostname allow list implemented at the load balancer
892
ignore_logger("django.security.DisallowedHost")
1✔
893
# Fluent errors, mostly when a translation is unavailable for the locale.
894
# It is more effective to process these from logs using BigQuery than to track
895
# as events in Sentry.
896
ignore_logger("django_ftl.message_errors")
1✔
897
# Security scanner attempts on Heroku dev, no action required
898
if RELAY_CHANNEL == "dev":
1!
UNCOV
899
    ignore_logger("django.security.SuspiciousFileOperation")
×
900

901
if USE_SILK:
1!
UNCOV
902
    SILKY_PYTHON_PROFILER = True
×
UNCOV
903
    SILKY_PYTHON_PROFILER_BINARY = True
×
UNCOV
904
    SILKY_PYTHON_PROFILER_RESULT_PATH = ".silk-profiler"
×
905

906
# Settings for manage.py process_emails_from_sqs
907
PROCESS_EMAIL_BATCH_SIZE = config(
1✔
908
    "PROCESS_EMAIL_BATCH_SIZE", 10, cast=Choices(range(1, 11), cast=int)
909
)
910
PROCESS_EMAIL_DELETE_FAILED_MESSAGES = config(
1✔
911
    "PROCESS_EMAIL_DELETE_FAILED_MESSAGES", False, cast=bool
912
)
913
PROCESS_EMAIL_HEALTHCHECK_PATH = config(
1✔
914
    "PROCESS_EMAIL_HEALTHCHECK_PATH", os.path.join(TMP_DIR, "healthcheck.json")
915
)
916
PROCESS_EMAIL_MAX_SECONDS = config("PROCESS_EMAIL_MAX_SECONDS", 0, cast=int) or None
1✔
917
PROCESS_EMAIL_VERBOSITY = config(
1✔
918
    "PROCESS_EMAIL_VERBOSITY", 1, cast=Choices(range(0, 4), cast=int)
919
)
920
PROCESS_EMAIL_VISIBILITY_SECONDS = config(
1✔
921
    "PROCESS_EMAIL_VISIBILITY_SECONDS", 120, cast=int
922
)
923
PROCESS_EMAIL_WAIT_SECONDS = config("PROCESS_EMAIL_WAIT_SECONDS", 5, cast=int)
1✔
924
PROCESS_EMAIL_HEALTHCHECK_MAX_AGE = config(
1✔
925
    "PROCESS_EMAIL_HEALTHCHECK_MAX_AGE", 120, cast=int
926
)
927
PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE = config(
1✔
928
    "PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE",
929
    PROCESS_EMAIL_MAX_SECONDS or 120.0,
930
    cast=float,
931
)
932

933
# Django 3.2 switches default to BigAutoField
934
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
1✔
935

936
# python-dockerflow settings
937
DOCKERFLOW_VERSION_CALLBACK = "privaterelay.utils.get_version_info"
1✔
938
DOCKERFLOW_CHECKS = [
1✔
939
    "dockerflow.django.checks.check_database_connected",
940
    "dockerflow.django.checks.check_migrations_applied",
941
]
942
if REDIS_URL:
1!
UNCOV
943
    DOCKERFLOW_CHECKS.append("dockerflow.django.checks.check_redis_connected")
×
944
DOCKERFLOW_REQUEST_ID_HEADER_NAME = config("DOCKERFLOW_REQUEST_ID_HEADER_NAME", None)
1✔
945
SILENCED_SYSTEM_CHECKS = sorted(
1✔
946
    set(config("DJANGO_SILENCED_SYSTEM_CHECKS", default="", cast=Csv()))
947
    | {
948
        # (models.W040) SQLite does not support indexes with non-key columns.
949
        # RelayAddress index idx_ra_created_by_addon uses this for PostgreSQL.
950
        "models.W040",
951
    }
952
)
953

954
# django-ftl settings
955
AUTO_RELOAD_BUNDLES = False  # Requires pyinotify
1✔
956

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

960
# settings for kinto / remote settings
961
REMOTE_SETTINGS_SERVER = config("REMOTE_SETTINGS_SERVER", "", str)
1✔
962
REMOTE_SETTINGS_AUTH = config("REMOTE_SETTINGS_AUTH", "", str)
1✔
963
REMOTE_SETTINGS_BUCKET = config("REMOTE_SETTINGS_BUCKET", "", str)
1✔
964
REMOTE_SETTINGS_COLLECTION = config("REMOTE_SETTINGS_COLLECTION", "", str)
1✔
965
ALLOWLIST_INPUT_URL = config("ALLOWLIST_INPUT_URL", "", str)
1✔
966

967
# Patching for django-types
968
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