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

mozilla / fx-private-relay / 5e7bcf23-db3c-407d-ae39-497872994e62

16 Oct 2024 12:32PM CUT coverage: 84.477% (-0.02%) from 84.495%
5e7bcf23-db3c-407d-ae39-497872994e62

push

circleci

web-flow
Merge pull request #5109 from mozilla/mpp-3901-update-spam-email-notification-content

MPP-3901: update content for disable-mask email

2370 of 3515 branches covered (67.43%)

Branch coverage included in aggregate %.

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

3 existing lines in 2 files now uncovered.

16448 of 18761 relevant lines covered (87.67%)

10.17 hits per line

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

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

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

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

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

13
from __future__ import annotations
1✔
14

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

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

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

34
from .types import CONTENT_SECURITY_POLICY_T, RELAY_CHANNEL_NAME
1✔
35

36
if TYPE_CHECKING:
37
    import wsgiref.headers
38

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

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

48
try:
1✔
49
    import google.cloud.sqlcommenter  # noqa: F401
1✔
50

51
    HAS_SQLCOMMENTER = True
1✔
52
except ImportError:
×
53
    HAS_SQLCOMMENTER = False
×
54

55
try:
1✔
56
    from privaterelay.glean.server_events import GLEAN_EVENT_MOZLOG_TYPE
1✔
57
except ImportError:
×
58
    # File may not be generated yet. Will be checked at initialization
59
    GLEAN_EVENT_MOZLOG_TYPE = "glean-server-event"
×
60

61
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
62
BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1✔
63
TMP_DIR = os.path.join(BASE_DIR, "tmp")
1✔
64
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
1✔
65

66
# Quick-start development settings - unsuitable for production
67
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
68

69
# defaulting to blank to be production-broken by default
70
SECRET_KEY = config("SECRET_KEY", None)
1✔
71
SECRET_KEY_FALLBACKS = config("SECRET_KEY_FALLBACKS", "", cast=Csv())
1✔
72
SITE_ORIGIN: str | None = config("SITE_ORIGIN", None)
1✔
73

74
ORIGIN_CHANNEL_MAP: dict[str, RELAY_CHANNEL_NAME] = {
1✔
75
    "http://127.0.0.1:8000": "local",
76
    "https://dev.fxprivaterelay.nonprod.cloudops.mozgcp.net": "dev",
77
    "https://stage.fxprivaterelay.nonprod.cloudops.mozgcp.net": "stage",
78
    "https://relay.firefox.com": "prod",
79
}
80
RELAY_CHANNEL: RELAY_CHANNEL_NAME = cast(
1✔
81
    RELAY_CHANNEL_NAME,
82
    config(
83
        "RELAY_CHANNEL",
84
        default=ORIGIN_CHANNEL_MAP.get(SITE_ORIGIN or "", "local"),
85
        cast=Choices(get_args(RELAY_CHANNEL_NAME), cast=str),
86
    ),
87
)
88

89
DEBUG = config("DEBUG", False, cast=bool)
1✔
90
if DEBUG:
1!
91
    INTERNAL_IPS = config("DJANGO_INTERNAL_IPS", default="", cast=Csv())
1✔
92
IN_PYTEST: bool = "pytest" in sys.modules
1✔
93
USE_SILK = DEBUG and HAS_SILK and not IN_PYTEST
1✔
94
DEFAULT_EXCEPTION_REPORTER_FILTER = (
1✔
95
    "privaterelay.debug.RelaySaferExceptionReporterFilter"
96
)
97

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

116
#
117
# Setup CSP
118
#
119

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

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

145
API_DOCS_ENABLED = config("API_DOCS_ENABLED", False, cast=bool) or DEBUG
1✔
146
_CSP_SCRIPT_INLINE = USE_SILK
1✔
147

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

152
if API_DOCS_ENABLED:
1!
153
    _API_DOCS_CSP_IMG_SRC = ["data:", "https://cdn.redoc.ly"]
1✔
154
    _API_DOCS_CSP_STYLE_SRC = ["https://fonts.googleapis.com"]
1✔
155
    _API_DOCS_CSP_FONT_SRC = ["https://fonts.gstatic.com"]
1✔
156
    _API_DOCS_CSP_WORKER_SRC = ["blob:"]
1✔
157
else:
158
    _API_DOCS_CSP_IMG_SRC = []
×
159
    _API_DOCS_CSP_STYLE_SRC = []
×
160
    _API_DOCS_CSP_FONT_SRC = []
×
161
    _API_DOCS_CSP_WORKER_SRC = []
×
162

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

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

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

236
REFERRER_POLICY = "strict-origin-when-cross-origin"
1✔
237

238
ALLOWED_HOSTS: list[str] = []
1✔
239
DJANGO_ALLOWED_HOSTS = config("DJANGO_ALLOWED_HOST", "", cast=Csv())
1✔
240
if DJANGO_ALLOWED_HOSTS:
1!
241
    ALLOWED_HOSTS += DJANGO_ALLOWED_HOSTS
×
242
DJANGO_ALLOWED_SUBNET = config("DJANGO_ALLOWED_SUBNET", None)
1✔
243
if DJANGO_ALLOWED_SUBNET:
1!
244
    ALLOWED_HOSTS += [str(ip) for ip in ipaddress.IPv4Network(DJANGO_ALLOWED_SUBNET)]
×
245

246

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

250

251
AWS_REGION: str | None = config("AWS_REGION", None)
1✔
252
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID", None)
1✔
253
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", None)
1✔
254
AWS_SNS_TOPIC = set(config("AWS_SNS_TOPIC", "", cast=Csv()))
1✔
255
AWS_SNS_KEY_CACHE = config("AWS_SNS_KEY_CACHE", "default")
1✔
256
AWS_SES_CONFIGSET: str | None = config("AWS_SES_CONFIGSET", None)
1✔
257
AWS_SQS_EMAIL_QUEUE_URL = config("AWS_SQS_EMAIL_QUEUE_URL", None)
1✔
258
AWS_SQS_EMAIL_DLQ_URL = config("AWS_SQS_EMAIL_DLQ_URL", None)
1✔
259

260
# Dead-Letter Queue (DLQ) for SNS push subscription
261
AWS_SQS_QUEUE_URL = config("AWS_SQS_QUEUE_URL", None)
1✔
262

263
RELAY_FROM_ADDRESS: str | None = config("RELAY_FROM_ADDRESS", None)
1✔
264
GOOGLE_ANALYTICS_ID = config("GOOGLE_ANALYTICS_ID", None)
1✔
265
GA4_MEASUREMENT_ID = config("GA4_MEASUREMENT_ID", None)
1✔
266
GOOGLE_APPLICATION_CREDENTIALS: str = config("GOOGLE_APPLICATION_CREDENTIALS", "")
1✔
267
GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64: str = config(
1✔
268
    "GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64", ""
269
)
270
INCLUDE_VPN_BANNER = config("INCLUDE_VPN_BANNER", False, cast=bool)
1✔
271
RECRUITMENT_BANNER_LINK = config("RECRUITMENT_BANNER_LINK", None)
1✔
272
RECRUITMENT_BANNER_TEXT = config("RECRUITMENT_BANNER_TEXT", None)
1✔
273
RECRUITMENT_EMAIL_BANNER_TEXT = config("RECRUITMENT_EMAIL_BANNER_TEXT", None)
1✔
274
RECRUITMENT_EMAIL_BANNER_LINK = config("RECRUITMENT_EMAIL_BANNER_LINK", None)
1✔
275

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

315
DJANGO_STATSD_ENABLED = config("DJANGO_STATSD_ENABLED", False, cast=bool)
1✔
316
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)
1✔
317
STATSD_ENABLED: bool = DJANGO_STATSD_ENABLED or STATSD_DEBUG
1✔
318
STATSD_HOST = config("DJANGO_STATSD_HOST", "127.0.0.1")
1✔
319
STATSD_PORT = config("DJANGO_STATSD_PORT", "8125")
1✔
320
STATSD_PREFIX = config("DJANGO_STATSD_PREFIX", "fx.private.relay")
1✔
321

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

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

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

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

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

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

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

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

378

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

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

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

408
if HAS_SQLCOMMENTER:
1!
409
    MIDDLEWARE.append("google.cloud.sqlcommenter.django.middleware.SqlCommenter")
1✔
410

411
ROOT_URLCONF = "privaterelay.urls"
1✔
412

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

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

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

461
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
462
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
463

464
MAX_ADDRESS_CREATION_PER_DAY: int = config(
1✔
465
    "MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int
466
)
467
MAX_REPLIES_PER_DAY: int = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
468
MAX_FORWARDED_PER_DAY: int = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
469
MAX_FORWARDED_EMAIL_SIZE_PER_DAY: int = config(
1✔
470
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
471
)
472
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
473
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
474
)
475

476
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
477
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
478

479
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
480

481
# Database
482
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
483

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

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

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

526

527
# Internationalization
528
# https://docs.djangoproject.com/en/2.2/topics/i18n/
529

530
LANGUAGE_CODE = "en"
1✔
531

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

543
TIME_ZONE = "UTC"
1✔
544

545
USE_I18N = True
1✔
546

547

548
USE_TZ = True
1✔
549

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

571
# Relay does not support user-uploaded files
572
MEDIA_ROOT = None
1✔
573
MEDIA_URL = None
1✔
574

575
WHITENOISE_INDEX_FILE = True
1✔
576

577

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

593

594
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
595

596
SITE_ID = 1
1✔
597

598
AUTHENTICATION_BACKENDS = (
1✔
599
    "django.contrib.auth.backends.ModelBackend",
600
    "allauth.account.auth_backends.AuthenticationBackend",
601
)
602

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

618
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
619
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
620
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
621
SOCIALACCOUNT_STORE_TOKENS = True
1✔
622

623
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
624
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
625
ACCOUNT_USERNAME_REQUIRED = False
1✔
626

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

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

717
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
718
if DEBUG and not IN_PYTEST:
1!
719
    DRF_RENDERERS += [
×
720
        "rest_framework.renderers.BrowsableAPIRenderer",
721
    ]
722

723
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
724
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
725
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
726

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

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

757
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
758
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
759
else:
760
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
761
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
762

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

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

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

813
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
814
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
815
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
816
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
817

818
sentry_release: str | None = None
1✔
819
if SENTRY_RELEASE:
1!
820
    sentry_release = SENTRY_RELEASE
×
821
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
822
    sentry_release = CIRCLE_TAG
1✔
UNCOV
823
elif (
×
824
    CIRCLE_SHA1
825
    and CIRCLE_SHA1 != "unknown"
826
    and CIRCLE_BRANCH
827
    and CIRCLE_BRANCH != "unknown"
828
):
UNCOV
829
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
830

831
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
832

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

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

859

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

884
if USE_SILK:
1!
885
    SILKY_PYTHON_PROFILER = True
×
886
    SILKY_PYTHON_PROFILER_BINARY = True
×
887
    SILKY_PYTHON_PROFILER_RESULT_PATH = ".silk-profiler"
×
888

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

916
# Django 3.2 switches default to BigAutoField
917
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
1✔
918

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

937
# django-ftl settings
938
AUTO_RELOAD_BUNDLES = False  # Requires pyinotify
1✔
939

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

943
# Patching for django-types
944
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