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

mozilla / fx-private-relay / 641d4a4a-a876-413c-b6b5-5117bf1a435e

22 Sep 2025 03:40PM UTC coverage: 88.855% (-0.008%) from 88.863%
641d4a4a-a876-413c-b6b5-5117bf1a435e

push

circleci

web-flow
Merge pull request #5885 from mozilla/hotfix/2025.09.10.01

fix(twilio): Add error handling for erroring Twilio calls

2918 of 3927 branches covered (74.31%)

Branch coverage included in aggregate %.

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

4 existing lines in 2 files now uncovered.

18073 of 19697 relevant lines covered (91.76%)

11.41 hits per line

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

77.43
/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

308
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)
1✔
309
STATSD_ENABLED: bool = (
1✔
310
    config("STATSD_ENABLED", False, cast=bool)
311
    or config("DJANGO_STATSD_ENABLED", False, cast=bool)
312
    or STATSD_DEBUG
313
)
314
STATSD_HOST = config("STATSD_HOST", "") or config("DJANGO_STATSD_HOST", "127.0.0.1")
1✔
315

316
STATSD_PORT = config("STATSD_PORT", "") or config("DJANGO_STATSD_PORT", "8125")
1✔
317
STATSD_PREFIX = config("STATSD_PREFIX", "") or config(
1✔
318
    "DJANGO_STATSD_PREFIX", "firefox_relay"
319
)
320

321
SERVE_ADDON = config("SERVE_ADDON", None)
1✔
322

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

348
if API_DOCS_ENABLED:
1!
349
    INSTALLED_APPS += [
1✔
350
        "drf_spectacular",
351
        "drf_spectacular_sidecar",
352
    ]
353

354
if DEBUG:
1!
355
    INSTALLED_APPS += [
1✔
356
        "debug_toolbar",
357
    ]
358

359
if USE_SILK:
1!
360
    INSTALLED_APPS.append("silk")
×
361

362
if ADMIN_ENABLED:
1!
363
    INSTALLED_APPS += [
×
364
        "django.contrib.admin",
365
    ]
366

367
if AWS_SES_CONFIGSET and AWS_SNS_TOPIC:
1!
368
    INSTALLED_APPS += [
1✔
369
        "emails.apps.EmailsConfig",
370
    ]
371

372
if PHONES_ENABLED:
1!
373
    INSTALLED_APPS += [
1✔
374
        "phones.apps.PhonesConfig",
375
    ]
376

377

378
MIDDLEWARE = ["privaterelay.middleware.ResponseMetrics"]
1✔
379

380
if USE_SILK:
1!
381
    MIDDLEWARE.append("silk.middleware.SilkyMiddleware")
×
382
if DEBUG:
1!
383
    MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
1✔
384

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

408
ROOT_URLCONF = "privaterelay.urls"
1✔
409

410
TEMPLATES = [
1✔
411
    {
412
        "BACKEND": "django.template.backends.django.DjangoTemplates",
413
        "DIRS": [
414
            os.path.join(BASE_DIR, "privaterelay", "templates"),
415
        ],
416
        "APP_DIRS": True,
417
        "OPTIONS": {
418
            "context_processors": [
419
                "django.template.context_processors.debug",
420
                "django.template.context_processors.request",
421
                "django.contrib.auth.context_processors.auth",
422
                "django.contrib.messages.context_processors.messages",
423
            ],
424
        },
425
    },
426
]
427

428
RELAY_FIREFOX_DOMAIN: str = config("RELAY_FIREFOX_DOMAIN", "relay.firefox.com")
1✔
429
MOZMAIL_DOMAIN: str = config("MOZMAIL_DOMAIN", "mozmail.com")
1✔
430
MAX_NUM_FREE_ALIASES: int = config("MAX_NUM_FREE_ALIASES", 5, cast=int)
1✔
431
PERIODICAL_PREMIUM_PROD_ID: str = config("PERIODICAL_PREMIUM_PROD_ID", "")
1✔
432
PREMIUM_PLAN_ID_US_MONTHLY: str = config(
1✔
433
    "PREMIUM_PLAN_ID_US_MONTHLY", "price_1LXUcnJNcmPzuWtRpbNOajYS"
434
)
435
PREMIUM_PLAN_ID_US_YEARLY: str = config(
1✔
436
    "PREMIUM_PLAN_ID_US_YEARLY", "price_1LXUdlJNcmPzuWtRKTYg7mpZ"
437
)
438
PHONE_PROD_ID = config("PHONE_PROD_ID", "")
1✔
439
PHONE_PLAN_ID_US_MONTHLY: str = config(
1✔
440
    "PHONE_PLAN_ID_US_MONTHLY", "price_1Li0w8JNcmPzuWtR2rGU80P3"
441
)
442
PHONE_PLAN_ID_US_YEARLY: str = config(
1✔
443
    "PHONE_PLAN_ID_US_YEARLY", "price_1Li15WJNcmPzuWtRIh0F4VwP"
444
)
445
BUNDLE_PROD_ID = config("BUNDLE_PROD_ID", "")
1✔
446
BUNDLE_PLAN_ID_US: str = config("BUNDLE_PLAN_ID_US", "price_1LwoSDJNcmPzuWtR6wPJZeoh")
1✔
447
MEGABUNDLE_PROD_ID = config("MEGABUNDLE_PROD_ID", "prod_SFb8iVuZIOPREe")
1✔
448
MEGABUNDLE_PLAN_ID_US: str = config(
1✔
449
    "MEGABUNDLE_PLAN_ID_US", "price_1RMAopKb9q6OnNsLSGe1vLtt"
450
)
451

452
SUBSCRIPTIONS_WITH_UNLIMITED: list[str] = config(
1✔
453
    "SUBSCRIPTIONS_WITH_UNLIMITED", default="", cast=Csv()
454
)
455
SUBSCRIPTIONS_WITH_PHONE: list[str] = config(
1✔
456
    "SUBSCRIPTIONS_WITH_PHONE", default="", cast=Csv()
457
)
458
SUBSCRIPTIONS_WITH_VPN: list[str] = config(
1✔
459
    "SUBSCRIPTIONS_WITH_VPN", default="", cast=Csv()
460
)
461

462
SUBSCRIPTIONS_THAT_MEGABUNDLE_PROVIDES: list[str] = config(
1✔
463
    "SUBSCRIPTIONS_THAT_MEGABUNDLE_PROVIDES", default="", cast=Csv()
464
)
465

466
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
467
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
468

469
MAX_ADDRESS_CREATION_PER_DAY: int = config(
1✔
470
    "MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int
471
)
472
MAX_REPLIES_PER_DAY: int = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
473
MAX_FORWARDED_PER_DAY: int = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
474
MAX_FORWARDED_EMAIL_SIZE_PER_DAY: int = config(
1✔
475
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
476
)
477
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
478
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
479
)
480

481
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
482
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
483

484
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
485

486
# Database
487
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
488

489
DATABASE_URL = config(
1✔
490
    "DATABASE_URL", default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3"))
491
)
492
DATABASES = {"default": dj_database_url.parse(DATABASE_URL)}
1✔
493
# Optionally set a test database name.
494
# This is useful for forcing an on-disk database for SQLite.
495
TEST_DB_NAME = config("TEST_DB_NAME", "")
1✔
496
if TEST_DB_NAME:
1!
497
    DATABASES["default"]["TEST"] = {"NAME": TEST_DB_NAME}
×
498

499
REDIS_URL = config("REDIS_URL", "")
1✔
500
REDIS_SELF_SIGNED_CERT = config("REDIS_SELF_SIGNED_CERT", False, bool)
1✔
501
if REDIS_URL:
1!
502
    _redis_options: dict[str, Any] = {
×
503
        "CLIENT_CLASS": "django_redis.client.DefaultClient"
504
    }
505
    # Heroku mini uses self-signed certificates
506
    if REDIS_SELF_SIGNED_CERT:
×
507
        _redis_options["CONNECTION_POOL_KWARGS"] = {
×
508
            "ssl_cert_reqs": None,
509
            "ssl_check_hostname": False,
510
        }
511

512
    CACHES = {
×
513
        "default": {
514
            "BACKEND": "django_redis.cache.RedisCache",
515
            "LOCATION": REDIS_URL,
516
            "OPTIONS": _redis_options,
517
        }
518
    }
519
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
×
520
    SESSION_CACHE_ALIAS = "default"
×
521
elif RELAY_CHANNEL == "local":
1!
522
    CACHES = {
1✔
523
        "default": {
524
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
525
        }
526
    }
527

528
# Password validation
529
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
530
# only needed when admin UI is enabled
531
if ADMIN_ENABLED:
1!
532
    _DJANGO_PWD_VALIDATION = "django.contrib.auth.password_validation"  # noqa: E501, S105 (long line, possible password)
×
533
    AUTH_PASSWORD_VALIDATORS = [
×
534
        {"NAME": _DJANGO_PWD_VALIDATION + ".UserAttributeSimilarityValidator"},
535
        {"NAME": _DJANGO_PWD_VALIDATION + ".MinimumLengthValidator"},
536
        {"NAME": _DJANGO_PWD_VALIDATION + ".CommonPasswordValidator"},
537
        {"NAME": _DJANGO_PWD_VALIDATION + ".NumericPasswordValidator"},
538
    ]
539

540

541
# Internationalization
542
# https://docs.djangoproject.com/en/2.2/topics/i18n/
543

544
LANGUAGE_CODE = "en"
1✔
545

546
# Mozilla l10n directories use lang-locale language codes,
547
# so we need to add those to LANGUAGES so Django's LocaleMiddleware
548
# can find them.
549
LANGUAGES = DEFAULT_LANGUAGES + [
1✔
550
    ("zh-tw", "Chinese"),
551
    ("zh-cn", "Chinese"),
552
    ("es-es", "Spanish"),
553
    ("pt-pt", "Portuguese"),
554
    ("skr", "Saraiki"),
555
]
556

557
TIME_ZONE = "UTC"
1✔
558

559
USE_I18N = True
1✔
560

561

562
USE_TZ = True
1✔
563

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

585
# Relay does not support user-uploaded files
586
MEDIA_ROOT = None
1✔
587
MEDIA_URL = None
1✔
588

589
WHITENOISE_INDEX_FILE = True
1✔
590

591

592
# See
593
# https://whitenoise.evans.io/en/stable/django.html#WHITENOISE_ADD_HEADERS_FUNCTION
594
# Intended to ensure that the homepage does not get cached in our CDN,
595
# so that the `RedirectRootIfLoggedIn` middleware can kick in for logged-in
596
# users.
597
def set_index_cache_control_headers(
1✔
598
    headers: wsgiref.headers.Headers, path: str, url: str
599
) -> None:
600
    if DEBUG:
1!
601
        home_path = os.path.join(BASE_DIR, "frontend/out", "index.html")
1✔
602
    else:
603
        home_path = os.path.join(STATIC_ROOT, "index.html")
×
604
    if path == home_path:
1✔
605
        headers["Cache-Control"] = "no-cache, public"
1✔
606

607

608
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
609

610
SITE_ID = 1
1✔
611

612
AUTHENTICATION_BACKENDS = (
1✔
613
    "django.contrib.auth.backends.ModelBackend",
614
    "allauth.account.auth_backends.AuthenticationBackend",
615
)
616

617
SOCIALACCOUNT_PROVIDERS = {
1✔
618
    "fxa": {
619
        # Note: to request "profile" scope, must be a trusted Mozilla client
620
        "SCOPE": ["profile", "https://identity.mozilla.com/account/subscriptions"],
621
        "AUTH_PARAMS": {"access_type": "offline"},
622
        "OAUTH_ENDPOINT": config(
623
            "FXA_OAUTH_ENDPOINT", "https://oauth.accounts.firefox.com/v1"
624
        ),
625
        "PROFILE_ENDPOINT": config(
626
            "FXA_PROFILE_ENDPOINT", "https://profile.accounts.firefox.com/v1"
627
        ),
628
        "VERIFIED_EMAIL": True,  # Assume FxA primary email is verified
629
    }
630
}
631

632
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
633
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
634
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
635
SOCIALACCOUNT_STORE_TOKENS = True
1✔
636

637
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
638
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
639

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

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

748
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
749
if DEBUG and not IN_PYTEST:
1!
750
    DRF_RENDERERS += [
×
751
        "rest_framework.renderers.BrowsableAPIRenderer",
752
    ]
753

754
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
755
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
756
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
757

758
REST_FRAMEWORK = {
1✔
759
    "DEFAULT_AUTHENTICATION_CLASSES": [
760
        "api.authentication.FxaTokenAuthentication",
761
        "rest_framework.authentication.TokenAuthentication",
762
        "rest_framework.authentication.SessionAuthentication",
763
    ],
764
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
765
    "DEFAULT_RENDERER_CLASSES": DRF_RENDERERS,
766
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
767
    "EXCEPTION_HANDLER": "api.views.relay_exception_handler",
768
}
769
if API_DOCS_ENABLED:
1!
770
    REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"] = "drf_spectacular.openapi.AutoSchema"
1✔
771

772
SPECTACULAR_SETTINGS = {
1✔
773
    "SWAGGER_UI_DIST": "SIDECAR",
774
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
775
    "REDOC_DIST": "SIDECAR",
776
    "TITLE": "Firefox Relay API",
777
    "DESCRIPTION": (
778
        "Keep your email safe from hackers and trackers. This API is built with"
779
        " Django REST Framework and powers the Relay website UI, add-on,"
780
        " Firefox browser, and 3rd-party app integrations."
781
    ),
782
    "VERSION": "1.0",
783
    "SERVE_INCLUDE_SCHEMA": False,
784
    "PREPROCESSING_HOOKS": ["api.schema.preprocess_ignore_deprecated_paths"],
785
    "SORT_OPERATIONS": "api.schema.sort_by_tag",
786
}
787

788
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
789
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
790
else:
791
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
792
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
793

794
# Turn on logging out on GET in development.
795
# This allows `/mock/logout/` in the front-end to clear the
796
# session cookie. Without this, after switching accounts in dev mode,
797
# then logging out again, API requests continue succeeding even without
798
# an auth token:
799
ACCOUNT_LOGOUT_ON_GET = DEBUG
1✔
800

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

831
CSRF_TRUSTED_ORIGINS = []
1✔
832
if RELAY_CHANNEL == "local":
1!
833
    # In local development, the React UI can be served up from a different server
834
    # that needs to be allowed to make requests.
835
    # In production, the frontend is served by Django, is therefore on the same
836
    # origin and thus has access to the same cookies.
837
    CORS_ALLOW_CREDENTIALS = True
1✔
838
    SESSION_COOKIE_SAMESITE = None
1✔
839
    CSRF_TRUSTED_ORIGINS += [
1✔
840
        "http://localhost:3000",
841
        "http://0.0.0.0:3000",
842
    ]
843

844
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
845
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
846
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
847
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
848

849
sentry_release: str | None = None
1✔
850
if SENTRY_RELEASE:
1!
851
    sentry_release = SENTRY_RELEASE
×
852
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
853
    sentry_release = CIRCLE_TAG
1✔
UNCOV
854
elif (
×
855
    CIRCLE_SHA1
856
    and CIRCLE_SHA1 != "unknown"
857
    and CIRCLE_BRANCH
858
    and CIRCLE_BRANCH != "unknown"
859
):
UNCOV
860
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
861

862
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
863

864
SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", RELAY_CHANNEL)
1✔
865
# Use "local" as default rather than "prod", to catch ngrok.io URLs
866
if SENTRY_ENVIRONMENT == "prod" and SITE_ORIGIN != "https://relay.firefox.com":
1!
867
    SENTRY_ENVIRONMENT = "local"
×
868

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

890
if USE_SILK:
1!
891
    SILKY_PYTHON_PROFILER = True
×
892
    SILKY_PYTHON_PROFILER_BINARY = True
×
893
    SILKY_PYTHON_PROFILER_RESULT_PATH = ".silk-profiler"
×
894

895
# Settings for manage.py process_emails_from_sqs
896
PROCESS_EMAIL_BATCH_SIZE = config(
1✔
897
    "PROCESS_EMAIL_BATCH_SIZE", 10, cast=Choices(range(1, 11), cast=int)
898
)
899
PROCESS_EMAIL_DELETE_FAILED_MESSAGES = config(
1✔
900
    "PROCESS_EMAIL_DELETE_FAILED_MESSAGES", False, cast=bool
901
)
902
PROCESS_EMAIL_HEALTHCHECK_PATH = config(
1✔
903
    "PROCESS_EMAIL_HEALTHCHECK_PATH", os.path.join(TMP_DIR, "healthcheck.json")
904
)
905
PROCESS_EMAIL_MAX_SECONDS = config("PROCESS_EMAIL_MAX_SECONDS", 0, cast=int) or None
1✔
906
PROCESS_EMAIL_VERBOSITY = config(
1✔
907
    "PROCESS_EMAIL_VERBOSITY", 1, cast=Choices(range(0, 4), cast=int)
908
)
909
PROCESS_EMAIL_VISIBILITY_SECONDS = config(
1✔
910
    "PROCESS_EMAIL_VISIBILITY_SECONDS", 120, cast=int
911
)
912
PROCESS_EMAIL_WAIT_SECONDS = config("PROCESS_EMAIL_WAIT_SECONDS", 5, cast=int)
1✔
913
PROCESS_EMAIL_HEALTHCHECK_MAX_AGE = config(
1✔
914
    "PROCESS_EMAIL_HEALTHCHECK_MAX_AGE", 120, cast=int
915
)
916
PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE = config(
1✔
917
    "PROCESS_EMAIL_MAX_SECONDS_PER_MESSAGE",
918
    PROCESS_EMAIL_MAX_SECONDS or 120.0,
919
    cast=float,
920
)
921

922
# Django 3.2 switches default to BigAutoField
923
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
1✔
924

925
# python-dockerflow settings
926
DOCKERFLOW_VERSION_CALLBACK = "privaterelay.utils.get_version_info"
1✔
927
DOCKERFLOW_CHECKS = [
1✔
928
    "dockerflow.django.checks.check_database_connected",
929
    "dockerflow.django.checks.check_migrations_applied",
930
]
931
if REDIS_URL:
1!
932
    DOCKERFLOW_CHECKS.append("dockerflow.django.checks.check_redis_connected")
×
933
DOCKERFLOW_REQUEST_ID_HEADER_NAME = config("DOCKERFLOW_REQUEST_ID_HEADER_NAME", None)
1✔
934
SILENCED_SYSTEM_CHECKS = sorted(
1✔
935
    set(config("DJANGO_SILENCED_SYSTEM_CHECKS", default="", cast=Csv()))
936
    | {
937
        # (models.W040) SQLite does not support indexes with non-key columns.
938
        # RelayAddress index idx_ra_created_by_addon uses this for PostgreSQL.
939
        "models.W040",
940
    }
941
)
942

943
# django-ftl settings
944
AUTO_RELOAD_BUNDLES = False  # Requires pyinotify
1✔
945

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

949
# settings for kinto / remote settings
950
REMOTE_SETTINGS_SERVER = config("REMOTE_SETTINGS_SERVER", "", str)
1✔
951
REMOTE_SETTINGS_AUTH = config("REMOTE_SETTINGS_AUTH", "", str)
1✔
952
REMOTE_SETTINGS_BUCKET = config("REMOTE_SETTINGS_BUCKET", "", str)
1✔
953
REMOTE_SETTINGS_COLLECTION = config("REMOTE_SETTINGS_COLLECTION", "", str)
1✔
954
ALLOWLIST_INPUT_URL = config("ALLOWLIST_INPUT_URL", "", str)
1✔
955

956
# Patching for django-types
957
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