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

mozilla / fx-private-relay / f9d7cefa-25bb-4602-bc7c-dfeaebfdaf04

29 May 2025 09:50PM CUT coverage: 85.63%. Remained the same
f9d7cefa-25bb-4602-bc7c-dfeaebfdaf04

push

circleci

web-flow
Merge pull request #5604 from mozilla/pricing-grid-style-fix

pricing-grid-fix

2516 of 3650 branches covered (68.93%)

Branch coverage included in aggregate %.

17661 of 19913 relevant lines covered (88.69%)

9.65 hits per line

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

78.01
/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("DJANGO_INTERNAL_IPS", default="", cast=Csv())
1✔
84
IN_PYTEST: bool = "pytest" in sys.modules
1✔
85
USE_SILK = DEBUG and HAS_SILK and not IN_PYTEST
1✔
86
DEFAULT_EXCEPTION_REPORTER_FILTER = (
1✔
87
    "privaterelay.debug.RelaySaferExceptionReporterFilter"
88
)
89

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

108
#
109
# Setup CSP
110
#
111

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

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

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

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

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

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

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

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

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

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

238

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

242

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

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

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

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

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

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

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

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

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

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

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

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

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

370

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

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

378
MIDDLEWARE += [
1✔
379
    "django.middleware.security.SecurityMiddleware",
380
    "privaterelay.middleware.EagerNonceCSPMiddleware",
381
    "privaterelay.middleware.RedirectRootIfLoggedIn",
382
    "privaterelay.middleware.RelayStaticFilesMiddleware",
383
    "django.contrib.sessions.middleware.SessionMiddleware",
384
    "corsheaders.middleware.CorsMiddleware",
385
    "django.middleware.common.CommonMiddleware",
386
    "django.middleware.csrf.CsrfViewMiddleware",
387
    "django.contrib.auth.middleware.AuthenticationMiddleware",
388
    "django.contrib.messages.middleware.MessageMiddleware",
389
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
390
    "django.middleware.locale.LocaleMiddleware",
391
    "allauth.account.middleware.AccountMiddleware",
392
    "django_ftl.middleware.activate_from_request_language_code",
393
    "django_referrer_policy.middleware.ReferrerPolicyMiddleware",
394
    "dockerflow.django.middleware.DockerflowMiddleware",
395
    "waffle.middleware.WaffleMiddleware",
396
    "privaterelay.middleware.AddDetectedCountryToRequestAndResponseHeaders",
397
    "privaterelay.middleware.StoreFirstVisit",
398
    "privaterelay.middleware.GleanApiAccessMiddleware",
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
MEGABUNDLE_PROD_ID = config("MEGABUNDLE_PROD_ID", "prod_SFb8iVuZIOPREe")
1✔
441
MEGABUNDLE_PLAN_ID_US: str = config(
1✔
442
    "MEGABUNDLE_PLAN_ID_US", "price_1RMAopKb9q6OnNsLSGe1vLtt"
443
)
444

445
SUBSCRIPTIONS_WITH_UNLIMITED: list[str] = config(
1✔
446
    "SUBSCRIPTIONS_WITH_UNLIMITED", default="", cast=Csv()
447
)
448
SUBSCRIPTIONS_WITH_PHONE: list[str] = config(
1✔
449
    "SUBSCRIPTIONS_WITH_PHONE", default="", cast=Csv()
450
)
451
SUBSCRIPTIONS_WITH_VPN: list[str] = config(
1✔
452
    "SUBSCRIPTIONS_WITH_VPN", default="", cast=Csv()
453
)
454

455
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
456
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
457

458
MAX_ADDRESS_CREATION_PER_DAY: int = config(
1✔
459
    "MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int
460
)
461
MAX_REPLIES_PER_DAY: int = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
462
MAX_FORWARDED_PER_DAY: int = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
463
MAX_FORWARDED_EMAIL_SIZE_PER_DAY: int = config(
1✔
464
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
465
)
466
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
467
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
468
)
469

470
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
471
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
472

473
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
474

475
# Database
476
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
477

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

488
REDIS_URL = config("REDIS_URL", "")
1✔
489
REDIS_SELF_SIGNED_CERT = config("REDIS_SELF_SIGNED_CERT", False, bool)
1✔
490
if REDIS_URL:
1!
491
    _redis_options: dict[str, Any] = {
×
492
        "CLIENT_CLASS": "django_redis.client.DefaultClient"
493
    }
494
    # Heroku mini uses self-signed certificates
495
    if REDIS_SELF_SIGNED_CERT:
×
496
        _redis_options["CONNECTION_POOL_KWARGS"] = {
×
497
            "ssl_cert_reqs": None,
498
            "ssl_check_hostname": False,
499
        }
500

501
    CACHES = {
×
502
        "default": {
503
            "BACKEND": "django_redis.cache.RedisCache",
504
            "LOCATION": REDIS_URL,
505
            "OPTIONS": _redis_options,
506
        }
507
    }
508
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
×
509
    SESSION_CACHE_ALIAS = "default"
×
510
elif RELAY_CHANNEL == "local":
1!
511
    CACHES = {
1✔
512
        "default": {
513
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
514
        }
515
    }
516

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

529

530
# Internationalization
531
# https://docs.djangoproject.com/en/2.2/topics/i18n/
532

533
LANGUAGE_CODE = "en"
1✔
534

535
# Mozilla l10n directories use lang-locale language codes,
536
# so we need to add those to LANGUAGES so Django's LocaleMiddleware
537
# can find them.
538
LANGUAGES = DEFAULT_LANGUAGES + [
1✔
539
    ("zh-tw", "Chinese"),
540
    ("zh-cn", "Chinese"),
541
    ("es-es", "Spanish"),
542
    ("pt-pt", "Portuguese"),
543
    ("skr", "Saraiki"),
544
]
545

546
TIME_ZONE = "UTC"
1✔
547

548
USE_I18N = True
1✔
549

550

551
USE_TZ = True
1✔
552

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

574
# Relay does not support user-uploaded files
575
MEDIA_ROOT = None
1✔
576
MEDIA_URL = None
1✔
577

578
WHITENOISE_INDEX_FILE = True
1✔
579

580

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

596

597
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
598

599
SITE_ID = 1
1✔
600

601
AUTHENTICATION_BACKENDS = (
1✔
602
    "django.contrib.auth.backends.ModelBackend",
603
    "allauth.account.auth_backends.AuthenticationBackend",
604
)
605

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

621
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
622
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
623
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
624
SOCIALACCOUNT_STORE_TOKENS = True
1✔
625

626
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
627
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
628

629
FXA_REQUESTS_TIMEOUT_SECONDS = config("FXA_REQUESTS_TIMEOUT_SECONDS", 1, cast=int)
1✔
630
FXA_SETTINGS_URL = config("FXA_SETTINGS_URL", f"{FXA_BASE_ORIGIN}/settings")
1✔
631
FXA_SUBSCRIPTIONS_URL = config(
1✔
632
    "FXA_SUBSCRIPTIONS_URL", f"{FXA_BASE_ORIGIN}/subscriptions"
633
)
634
# check https://mozilla.github.io/ecosystem-platform/api#tag/Subscriptions/operation/getOauthMozillasubscriptionsCustomerBillingandsubscriptions  # noqa: E501 (line too long)
635
FXA_ACCOUNTS_ENDPOINT = config(
1✔
636
    "FXA_ACCOUNTS_ENDPOINT",
637
    "https://api.accounts.firefox.com/v1",
638
)
639
FXA_SUPPORT_URL = config("FXA_SUPPORT_URL", f"{FXA_BASE_ORIGIN}/support/")
1✔
640
USE_SUBPLAT3 = config("USE_SUBPLAT3", False, cast=bool)
1✔
641
SUBPLAT3_HOST = (
1✔
642
    "https://payments.firefox.com"
643
    if FXA_BASE_ORIGIN == "https://accounts.firefox.com"
644
    else "https://payments-next.stage.fxa.nonprod.webservices.mozgcp.net"
645
)
646
SUBPLAT3_PREMIUM_PRODUCT_KEY = config(
1✔
647
    "SUBPLAT3_PREMIUM_PRODUCT_KEY", "relay-premium-127", cast=str
648
)
649
SUBPLAT3_PHONES_PRODUCT_KEY = config(
1✔
650
    "SUBPLAT3_PHONES_PRODUCT_KEY", "relay-premium-127-phone", cast=str
651
)
652
SUBPLAT3_BUNDLE_PRODUCT_KEY = config(
1✔
653
    "SUBPLAT3_BUNDLE_PRODUCT_KEY", "bundle-relay-vpn-dev", cast=str
654
)
655
SUBPLAT3_MEGABUNDLE_PRODUCT_KEY = config(
1✔
656
    "SUBPLAT3_MEGABUNDLE_PRODUCT_KEY", "privacyprotectionplan", cast=str
657
)
658

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

737
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
738
if DEBUG and not IN_PYTEST:
1!
739
    DRF_RENDERERS += [
×
740
        "rest_framework.renderers.BrowsableAPIRenderer",
741
    ]
742

743
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
744
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
745
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
746

747
REST_FRAMEWORK = {
1✔
748
    "DEFAULT_AUTHENTICATION_CLASSES": [
749
        "api.authentication.FxaTokenAuthentication",
750
        "rest_framework.authentication.TokenAuthentication",
751
        "rest_framework.authentication.SessionAuthentication",
752
    ],
753
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
754
    "DEFAULT_RENDERER_CLASSES": DRF_RENDERERS,
755
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
756
    "EXCEPTION_HANDLER": "api.views.relay_exception_handler",
757
}
758
if API_DOCS_ENABLED:
1!
759
    REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"] = "drf_spectacular.openapi.AutoSchema"
1✔
760

761
SPECTACULAR_SETTINGS = {
1✔
762
    "SWAGGER_UI_DIST": "SIDECAR",
763
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
764
    "REDOC_DIST": "SIDECAR",
765
    "TITLE": "Firefox Relay API",
766
    "DESCRIPTION": (
767
        "Keep your email safe from hackers and trackers. This API is built with"
768
        " Django REST Framework and powers the Relay website UI, add-on,"
769
        " Firefox browser, and 3rd-party app integrations."
770
    ),
771
    "VERSION": "1.0",
772
    "SERVE_INCLUDE_SCHEMA": False,
773
    "PREPROCESSING_HOOKS": ["api.schema.preprocess_ignore_deprecated_paths"],
774
    "SORT_OPERATIONS": "api.schema.sort_by_tag",
775
}
776

777
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
778
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
779
else:
780
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
781
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
782

783
# Turn on logging out on GET in development.
784
# This allows `/mock/logout/` in the front-end to clear the
785
# session cookie. Without this, after switching accounts in dev mode,
786
# then logging out again, API requests continue succeeding even without
787
# an auth token:
788
ACCOUNT_LOGOUT_ON_GET = DEBUG
1✔
789

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

820
CSRF_TRUSTED_ORIGINS = []
1✔
821
if RELAY_CHANNEL == "local":
1!
822
    # In local development, the React UI can be served up from a different server
823
    # that needs to be allowed to make requests.
824
    # In production, the frontend is served by Django, is therefore on the same
825
    # origin and thus has access to the same cookies.
826
    CORS_ALLOW_CREDENTIALS = True
1✔
827
    SESSION_COOKIE_SAMESITE = None
1✔
828
    CSRF_TRUSTED_ORIGINS += [
1✔
829
        "http://localhost:3000",
830
        "http://0.0.0.0:3000",
831
    ]
832

833
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
834
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
835
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
836
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
837

838
sentry_release: str | None = None
1✔
839
if SENTRY_RELEASE:
1!
840
    sentry_release = SENTRY_RELEASE
×
841
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
842
    sentry_release = CIRCLE_TAG
1✔
843
elif (
×
844
    CIRCLE_SHA1
845
    and CIRCLE_SHA1 != "unknown"
846
    and CIRCLE_BRANCH
847
    and CIRCLE_BRANCH != "unknown"
848
):
849
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
850

851
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
852

853
SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", RELAY_CHANNEL)
1✔
854
# Use "local" as default rather than "prod", to catch ngrok.io URLs
855
if SENTRY_ENVIRONMENT == "prod" and SITE_ORIGIN != "https://relay.firefox.com":
1!
856
    SENTRY_ENVIRONMENT = "local"
×
857

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

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

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

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

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

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

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

938
# settings for kinto / remote settings
939
REMOTE_SETTINGS_SERVER = config("REMOTE_SETTINGS_SERVER", "", str)
1✔
940
REMOTE_SETTINGS_AUTH = config("REMOTE_SETTINGS_AUTH", "", str)
1✔
941
REMOTE_SETTINGS_BUCKET = config("REMOTE_SETTINGS_BUCKET", "", str)
1✔
942
REMOTE_SETTINGS_COLLECTION = config("REMOTE_SETTINGS_COLLECTION", "", str)
1✔
943
ALLOWLIST_INPUT_URL = config("ALLOWLIST_INPUT_URL", "", str)
1✔
944

945
# Patching for django-types
946
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