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

mozilla / fx-private-relay / 3bcee939-bdc2-489c-aa4b-1290bbe14937

10 May 2024 12:06AM CUT coverage: 84.061% (-0.02%) from 84.08%
3bcee939-bdc2-489c-aa4b-1290bbe14937

push

circleci

actions-user
Merge in latest l10n strings

3599 of 4733 branches covered (76.04%)

Branch coverage included in aggregate %.

14685 of 17018 relevant lines covered (86.29%)

10.86 hits per line

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

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

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

105
#
106
# Setup CSP
107
#
108

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

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

134
API_DOCS_ENABLED = config("API_DOCS_ENABLED", False, cast=bool) or DEBUG
1✔
135
_CSP_SCRIPT_INLINE = API_DOCS_ENABLED or USE_SILK
1✔
136

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

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

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

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

179
CSP_DEFAULT_SRC = ["'self'"]
1✔
180
CSP_CONNECT_SRC = [
1✔
181
    "'self'",
182
    "https://www.google-analytics.com/",
183
    "https://location.services.mozilla.com",
184
    "https://api.stripe.com",
185
    BASKET_ORIGIN,
186
] + _ACCOUNT_CONNECT_SRC
187
CSP_FONT_SRC = ["'self'"] + _API_DOCS_CSP_FONT_SRC + ["https://relay.firefox.com/"]
1✔
188
CSP_IMG_SRC = ["'self'"] + _AVATAR_IMG_SRC + _API_DOCS_CSP_IMG_SRC
1✔
189
CSP_SCRIPT_SRC = (
1✔
190
    ["'self'"]
191
    + (["'unsafe-inline'"] if _CSP_SCRIPT_INLINE else [])
192
    + [
193
        "https://www.google-analytics.com/",
194
        "https://js.stripe.com/",
195
    ]
196
)
197
CSP_WORKER_SRC = _API_DOCS_CSP_WORKER_SRC or None
1✔
198
CSP_OBJECT_SRC = ["'none'"]
1✔
199
CSP_FRAME_SRC = ["https://js.stripe.com", "https://hooks.stripe.com"]
1✔
200
CSP_STYLE_SRC = (
1✔
201
    ["'self'"]
202
    + (["'unsafe-inline'"] if _CSP_STYLE_INLINE else [])
203
    + _API_DOCS_CSP_STYLE_SRC
204
    + _CSP_STYLE_HASHES
205
)
206
CSP_REPORT_URI = config("CSP_REPORT_URI", "")
1✔
207

208
REFERRER_POLICY = "strict-origin-when-cross-origin"
1✔
209

210
ALLOWED_HOSTS: list[str] = []
1✔
211
DJANGO_ALLOWED_HOSTS = config("DJANGO_ALLOWED_HOST", "", cast=Csv())
1✔
212
if DJANGO_ALLOWED_HOSTS:
1!
213
    ALLOWED_HOSTS += DJANGO_ALLOWED_HOSTS
×
214
DJANGO_ALLOWED_SUBNET = config("DJANGO_ALLOWED_SUBNET", None)
1✔
215
if DJANGO_ALLOWED_SUBNET:
1!
216
    ALLOWED_HOSTS += [str(ip) for ip in ipaddress.IPv4Network(DJANGO_ALLOWED_SUBNET)]
×
217

218

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

222

223
AWS_REGION: str | None = config("AWS_REGION", None)
1✔
224
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID", None)
1✔
225
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", None)
1✔
226
AWS_SNS_TOPIC = set(config("AWS_SNS_TOPIC", "", cast=Csv()))
1✔
227
AWS_SNS_KEY_CACHE = config("AWS_SNS_KEY_CACHE", "default")
1✔
228
AWS_SES_CONFIGSET: str | None = config("AWS_SES_CONFIGSET", None)
1✔
229
AWS_SQS_EMAIL_QUEUE_URL = config("AWS_SQS_EMAIL_QUEUE_URL", None)
1✔
230
AWS_SQS_EMAIL_DLQ_URL = config("AWS_SQS_EMAIL_DLQ_URL", None)
1✔
231

232
# Dead-Letter Queue (DLQ) for SNS push subscription
233
AWS_SQS_QUEUE_URL = config("AWS_SQS_QUEUE_URL", None)
1✔
234

235
RELAY_FROM_ADDRESS: str | None = config("RELAY_FROM_ADDRESS", None)
1✔
236
GOOGLE_ANALYTICS_ID = config("GOOGLE_ANALYTICS_ID", None)
1✔
237
GOOGLE_APPLICATION_CREDENTIALS: str = config("GOOGLE_APPLICATION_CREDENTIALS", "")
1✔
238
GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64: str = config(
1✔
239
    "GOOGLE_CLOUD_PROFILER_CREDENTIALS_B64", ""
240
)
241
INCLUDE_VPN_BANNER = config("INCLUDE_VPN_BANNER", False, cast=bool)
1✔
242
RECRUITMENT_BANNER_LINK = config("RECRUITMENT_BANNER_LINK", None)
1✔
243
RECRUITMENT_BANNER_TEXT = config("RECRUITMENT_BANNER_TEXT", None)
1✔
244
RECRUITMENT_EMAIL_BANNER_TEXT = config("RECRUITMENT_EMAIL_BANNER_TEXT", None)
1✔
245
RECRUITMENT_EMAIL_BANNER_LINK = config("RECRUITMENT_EMAIL_BANNER_LINK", None)
1✔
246

247
PHONES_ENABLED: bool = config("PHONES_ENABLED", False, cast=bool)
1✔
248
PHONES_NO_CLIENT_CALLS_IN_TEST = False  # Override in tests that do not test clients
1✔
249
TWILIO_ACCOUNT_SID: str | None = config("TWILIO_ACCOUNT_SID", None)
1✔
250
TWILIO_AUTH_TOKEN: str | None = config("TWILIO_AUTH_TOKEN", None)
1✔
251
TWILIO_MAIN_NUMBER: str | None = config("TWILIO_MAIN_NUMBER", None)
1✔
252
TWILIO_SMS_APPLICATION_SID: str | None = config("TWILIO_SMS_APPLICATION_SID", None)
1✔
253
TWILIO_MESSAGING_SERVICE_SID: list[str] = config(
1✔
254
    "TWILIO_MESSAGING_SERVICE_SID", "", cast=Csv()
255
)
256
TWILIO_TEST_ACCOUNT_SID: str | None = config("TWILIO_TEST_ACCOUNT_SID", None)
1✔
257
TWILIO_TEST_AUTH_TOKEN: str | None = config("TWILIO_TEST_AUTH_TOKEN", None)
1✔
258
TWILIO_ALLOWED_COUNTRY_CODES = {
1✔
259
    code.upper() for code in config("TWILIO_ALLOWED_COUNTRY_CODES", "US,CA", cast=Csv())
260
}
261
MAX_MINUTES_TO_VERIFY_REAL_PHONE: int = config(
1✔
262
    "MAX_MINUTES_TO_VERIFY_REAL_PHONE", 5, cast=int
263
)
264
MAX_TEXTS_PER_BILLING_CYCLE: int = config("MAX_TEXTS_PER_BILLING_CYCLE", 75, cast=int)
1✔
265
MAX_MINUTES_PER_BILLING_CYCLE: int = config(
1✔
266
    "MAX_MINUTES_PER_BILLING_CYCLE", 50, cast=int
267
)
268
DAYS_PER_BILLING_CYCLE = config("DAYS_PER_BILLING_CYCLE", 30, cast=int)
1✔
269
MAX_DAYS_IN_MONTH = 31
1✔
270
IQ_ENABLED = config("IQ_ENABLED", False, cast=bool)
1✔
271
IQ_FOR_VERIFICATION: bool = config("IQ_FOR_VERIFICATION", False, cast=bool)
1✔
272
IQ_FOR_NEW_NUMBERS = config("IQ_FOR_NEW_NUMBERS", False, cast=bool)
1✔
273
IQ_MAIN_NUMBER: str = config("IQ_MAIN_NUMBER", "")
1✔
274
IQ_OUTBOUND_API_KEY: str = config("IQ_OUTBOUND_API_KEY", "")
1✔
275
IQ_INBOUND_API_KEY = config("IQ_INBOUND_API_KEY", "")
1✔
276
IQ_MESSAGE_API_ORIGIN = config(
1✔
277
    "IQ_MESSAGE_API_ORIGIN", "https://messagebroker.inteliquent.com"
278
)
279
IQ_MESSAGE_PATH = "/msgbroker/rest/publishMessages"
1✔
280
IQ_PUBLISH_MESSAGE_URL: str = f"{IQ_MESSAGE_API_ORIGIN}{IQ_MESSAGE_PATH}"
1✔
281

282
DJANGO_STATSD_ENABLED = config("DJANGO_STATSD_ENABLED", False, cast=bool)
1✔
283
STATSD_DEBUG = config("STATSD_DEBUG", False, cast=bool)
1✔
284
STATSD_ENABLED: bool = DJANGO_STATSD_ENABLED or STATSD_DEBUG
1✔
285
STATSD_HOST = config("DJANGO_STATSD_HOST", "127.0.0.1")
1✔
286
STATSD_PORT = config("DJANGO_STATSD_PORT", "8125")
1✔
287
STATSD_PREFIX = config("DJANGO_STATSD_PREFIX", "fx.private.relay")
1✔
288

289
SERVE_ADDON = config("SERVE_ADDON", None)
1✔
290

291
# Application definition
292
INSTALLED_APPS = [
1✔
293
    "whitenoise.runserver_nostatic",
294
    "django.contrib.staticfiles",
295
    "django.contrib.auth",
296
    "django.contrib.contenttypes",
297
    "django.contrib.sessions",
298
    "django.contrib.messages",
299
    "django.contrib.sites",
300
    "django_filters",
301
    "django_ftl.apps.DjangoFtlConfig",
302
    "dockerflow.django",
303
    "allauth",
304
    "allauth.account",
305
    "allauth.socialaccount",
306
    "allauth.socialaccount.providers.fxa",
307
    "rest_framework",
308
    "rest_framework.authtoken",
309
    "corsheaders",
310
    "waffle",
311
    "privaterelay.apps.PrivateRelayConfig",
312
    "api.apps.ApiConfig",
313
]
314

315
if API_DOCS_ENABLED:
1!
316
    INSTALLED_APPS += [
1✔
317
        "drf_spectacular",
318
        "drf_spectacular_sidecar",
319
    ]
320

321
if DEBUG:
1!
322
    INSTALLED_APPS += [
1✔
323
        "debug_toolbar",
324
    ]
325

326
if USE_SILK:
1!
327
    INSTALLED_APPS.append("silk")
×
328

329
if ADMIN_ENABLED:
1!
330
    INSTALLED_APPS += [
×
331
        "django.contrib.admin",
332
    ]
333

334
if AWS_SES_CONFIGSET and AWS_SNS_TOPIC:
1!
335
    INSTALLED_APPS += [
1✔
336
        "emails.apps.EmailsConfig",
337
    ]
338

339
if PHONES_ENABLED:
1!
340
    INSTALLED_APPS += [
1✔
341
        "phones.apps.PhonesConfig",
342
    ]
343

344

345
# statsd middleware has to be first to catch errors in everything else
346
def _get_initial_middleware() -> list[str]:
1✔
347
    if STATSD_ENABLED:
1!
348
        return [
×
349
            "privaterelay.middleware.ResponseMetrics",
350
        ]
351
    return []
1✔
352

353

354
MIDDLEWARE = _get_initial_middleware()
1✔
355

356
if USE_SILK:
1!
357
    MIDDLEWARE.append("silk.middleware.SilkyMiddleware")
×
358
if DEBUG:
1!
359
    MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
1✔
360

361
MIDDLEWARE += [
1✔
362
    "django.middleware.security.SecurityMiddleware",
363
    "csp.middleware.CSPMiddleware",
364
    "privaterelay.middleware.RedirectRootIfLoggedIn",
365
    "privaterelay.middleware.RelayStaticFilesMiddleware",
366
    "django.contrib.sessions.middleware.SessionMiddleware",
367
    "corsheaders.middleware.CorsMiddleware",
368
    "django.middleware.common.CommonMiddleware",
369
    "django.middleware.csrf.CsrfViewMiddleware",
370
    "django.contrib.auth.middleware.AuthenticationMiddleware",
371
    "django.contrib.messages.middleware.MessageMiddleware",
372
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
373
    "django.middleware.locale.LocaleMiddleware",
374
    "allauth.account.middleware.AccountMiddleware",
375
    "django_ftl.middleware.activate_from_request_language_code",
376
    "django_referrer_policy.middleware.ReferrerPolicyMiddleware",
377
    "dockerflow.django.middleware.DockerflowMiddleware",
378
    "waffle.middleware.WaffleMiddleware",
379
    "privaterelay.middleware.AddDetectedCountryToRequestAndResponseHeaders",
380
    "privaterelay.middleware.StoreFirstVisit",
381
    "google.cloud.sqlcommenter.django.middleware.SqlCommenter",
382
]
383

384
ROOT_URLCONF = "privaterelay.urls"
1✔
385

386
TEMPLATES = [
1✔
387
    {
388
        "BACKEND": "django.template.backends.django.DjangoTemplates",
389
        "DIRS": [
390
            os.path.join(BASE_DIR, "privaterelay", "templates"),
391
        ],
392
        "APP_DIRS": True,
393
        "OPTIONS": {
394
            "context_processors": [
395
                "django.template.context_processors.debug",
396
                "django.template.context_processors.request",
397
                "django.contrib.auth.context_processors.auth",
398
                "django.contrib.messages.context_processors.messages",
399
            ],
400
        },
401
    },
402
]
403

404
RELAY_FIREFOX_DOMAIN: str = config("RELAY_FIREFOX_DOMAIN", "relay.firefox.com")
1✔
405
MOZMAIL_DOMAIN: str = config("MOZMAIL_DOMAIN", "mozmail.com")
1✔
406
MAX_NUM_FREE_ALIASES: int = config("MAX_NUM_FREE_ALIASES", 5, cast=int)
1✔
407
PERIODICAL_PREMIUM_PROD_ID: str = config("PERIODICAL_PREMIUM_PROD_ID", "")
1✔
408
PREMIUM_PLAN_ID_US_MONTHLY: str = config(
1✔
409
    "PREMIUM_PLAN_ID_US_MONTHLY", "price_1LXUcnJNcmPzuWtRpbNOajYS"
410
)
411
PREMIUM_PLAN_ID_US_YEARLY: str = config(
1✔
412
    "PREMIUM_PLAN_ID_US_YEARLY", "price_1LXUdlJNcmPzuWtRKTYg7mpZ"
413
)
414
PHONE_PROD_ID = config("PHONE_PROD_ID", "")
1✔
415
PHONE_PLAN_ID_US_MONTHLY: str = config(
1✔
416
    "PHONE_PLAN_ID_US_MONTHLY", "price_1Li0w8JNcmPzuWtR2rGU80P3"
417
)
418
PHONE_PLAN_ID_US_YEARLY: str = config(
1✔
419
    "PHONE_PLAN_ID_US_YEARLY", "price_1Li15WJNcmPzuWtRIh0F4VwP"
420
)
421
BUNDLE_PROD_ID = config("BUNDLE_PROD_ID", "")
1✔
422
BUNDLE_PLAN_ID_US: str = config("BUNDLE_PLAN_ID_US", "price_1LwoSDJNcmPzuWtR6wPJZeoh")
1✔
423

424
SUBSCRIPTIONS_WITH_UNLIMITED: list[str] = config(
1✔
425
    "SUBSCRIPTIONS_WITH_UNLIMITED", default="", cast=Csv()
426
)
427
SUBSCRIPTIONS_WITH_PHONE: list[str] = config(
1✔
428
    "SUBSCRIPTIONS_WITH_PHONE", default="", cast=Csv()
429
)
430
SUBSCRIPTIONS_WITH_VPN: list[str] = config(
1✔
431
    "SUBSCRIPTIONS_WITH_VPN", default="", cast=Csv()
432
)
433

434
MAX_ONBOARDING_AVAILABLE = config("MAX_ONBOARDING_AVAILABLE", 0, cast=int)
1✔
435
MAX_ONBOARDING_FREE_AVAILABLE = config("MAX_ONBOARDING_FREE_AVAILABLE", 3, cast=int)
1✔
436

437
MAX_ADDRESS_CREATION_PER_DAY = config("MAX_ADDRESS_CREATION_PER_DAY", 100, cast=int)
1✔
438
MAX_REPLIES_PER_DAY = config("MAX_REPLIES_PER_DAY", 100, cast=int)
1✔
439
MAX_FORWARDED_PER_DAY = config("MAX_FORWARDED_PER_DAY", 1000, cast=int)
1✔
440
MAX_FORWARDED_EMAIL_SIZE_PER_DAY = config(
1✔
441
    "MAX_FORWARDED_EMAIL_SIZE_PER_DAY", 1_000_000_000, cast=int
442
)
443
PREMIUM_FEATURE_PAUSED_DAYS: int = config(
1✔
444
    "ACCOUNT_PREMIUM_FEATURE_PAUSED_DAYS", 1, cast=int
445
)
446

447
SOFT_BOUNCE_ALLOWED_DAYS: int = config("SOFT_BOUNCE_ALLOWED_DAYS", 1, cast=int)
1✔
448
HARD_BOUNCE_ALLOWED_DAYS: int = config("HARD_BOUNCE_ALLOWED_DAYS", 30, cast=int)
1✔
449

450
WSGI_APPLICATION = "privaterelay.wsgi.application"
1✔
451

452
# Database
453
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
454

455
DATABASES = {
1✔
456
    "default": dj_database_url.config(
457
        default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3"))
458
    )
459
}
460
# Optionally set a test database name.
461
# This is useful for forcing an on-disk database for SQLite.
462
TEST_DB_NAME = config("TEST_DB_NAME", "")
1✔
463
if TEST_DB_NAME:
1!
464
    DATABASES["default"]["TEST"] = {"NAME": TEST_DB_NAME}
×
465

466
REDIS_URL = config("REDIS_URL", "")
1✔
467
if REDIS_URL:
1!
468
    CACHES = {
×
469
        "default": {
470
            "BACKEND": "django_redis.cache.RedisCache",
471
            "LOCATION": REDIS_URL,
472
            "OPTIONS": {
473
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
474
            },
475
        }
476
    }
477
    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
×
478
    SESSION_CACHE_ALIAS = "default"
×
479
elif RELAY_CHANNEL == "local":
1!
480
    CACHES = {
1✔
481
        "default": {
482
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
483
        }
484
    }
485

486
# Password validation
487
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
488
# only needed when admin UI is enabled
489
if ADMIN_ENABLED:
1!
490
    _DJANGO_PWD_VALIDATION = "django.contrib.auth.password_validation"  # noqa: E501, S105 (long line, possible password)
×
491
    AUTH_PASSWORD_VALIDATORS = [
×
492
        {"NAME": _DJANGO_PWD_VALIDATION + ".UserAttributeSimilarityValidator"},
493
        {"NAME": _DJANGO_PWD_VALIDATION + ".MinimumLengthValidator"},
494
        {"NAME": _DJANGO_PWD_VALIDATION + ".CommonPasswordValidator"},
495
        {"NAME": _DJANGO_PWD_VALIDATION + ".NumericPasswordValidator"},
496
    ]
497

498

499
# Internationalization
500
# https://docs.djangoproject.com/en/2.2/topics/i18n/
501

502
LANGUAGE_CODE = "en"
1✔
503

504
# Mozilla l10n directories use lang-locale language codes,
505
# so we need to add those to LANGUAGES so Django's LocaleMiddleware
506
# can find them.
507
LANGUAGES = DEFAULT_LANGUAGES + [
1✔
508
    ("zh-tw", "Chinese"),
509
    ("zh-cn", "Chinese"),
510
    ("es-es", "Spanish"),
511
    ("pt-pt", "Portuguese"),
512
    ("skr", "Saraiki"),
513
]
514

515
TIME_ZONE = "UTC"
1✔
516

517
USE_I18N = True
1✔
518

519

520
USE_TZ = True
1✔
521

522
STATICFILES_DIRS = [
1✔
523
    os.path.join(BASE_DIR, "frontend/out"),
524
]
525
# Static files (the front-end in /frontend/)
526
# https://whitenoise.evans.io/en/stable/django.html#using-whitenoise-with-webpack-browserify-latest-js-thing
527
STATIC_URL = "/"
1✔
528
if DEBUG:
1!
529
    # In production, we run collectstatic to index all static files.
530
    # However, when running locally, we want to automatically pick up
531
    # all files spewed out by `npm run watch` in /frontend/out,
532
    # and we're fine with the performance impact of that.
533
    WHITENOISE_ROOT = os.path.join(BASE_DIR, "frontend/out")
1✔
534
STORAGES = {
1✔
535
    "default": {
536
        "BACKEND": "django.core.files.storage.FileSystemStorage",
537
    },
538
    "staticfiles": {
539
        "BACKEND": "privaterelay.storage.RelayStaticFilesStorage",
540
    },
541
}
542

543
# Relay does not support user-uploaded files
544
MEDIA_ROOT = None
1✔
545
MEDIA_URL = None
1✔
546

547
WHITENOISE_INDEX_FILE = True
1✔
548

549

550
# See
551
# https://whitenoise.evans.io/en/stable/django.html#WHITENOISE_ADD_HEADERS_FUNCTION
552
# Intended to ensure that the homepage does not get cached in our CDN,
553
# so that the `RedirectRootIfLoggedIn` middleware can kick in for logged-in
554
# users.
555
def set_index_cache_control_headers(
1✔
556
    headers: wsgiref.headers.Headers, path: str, url: str
557
) -> None:
558
    if DEBUG:
1!
559
        home_path = os.path.join(BASE_DIR, "frontend/out", "index.html")
1✔
560
    else:
561
        home_path = os.path.join(STATIC_ROOT, "index.html")
×
562
    if path == home_path:
1✔
563
        headers["Cache-Control"] = "no-cache, public"
1✔
564

565

566
WHITENOISE_ADD_HEADERS_FUNCTION = set_index_cache_control_headers
1✔
567

568
SITE_ID = 1
1✔
569

570
AUTHENTICATION_BACKENDS = (
1✔
571
    "django.contrib.auth.backends.ModelBackend",
572
    "allauth.account.auth_backends.AuthenticationBackend",
573
)
574

575
SOCIALACCOUNT_PROVIDERS = {
1✔
576
    "fxa": {
577
        # Note: to request "profile" scope, must be a trusted Mozilla client
578
        "SCOPE": ["profile", "https://identity.mozilla.com/account/subscriptions"],
579
        "AUTH_PARAMS": {"access_type": "offline"},
580
        "OAUTH_ENDPOINT": config(
581
            "FXA_OAUTH_ENDPOINT", "https://oauth.accounts.firefox.com/v1"
582
        ),
583
        "PROFILE_ENDPOINT": config(
584
            "FXA_PROFILE_ENDPOINT", "https://profile.accounts.firefox.com/v1"
585
        ),
586
        "VERIFIED_EMAIL": True,  # Assume FxA primary email is verified
587
    }
588
}
589

590
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
1✔
591
SOCIALACCOUNT_AUTO_SIGNUP = True
1✔
592
SOCIALACCOUNT_LOGIN_ON_GET = True
1✔
593
SOCIALACCOUNT_STORE_TOKENS = True
1✔
594

595
ACCOUNT_ADAPTER = "privaterelay.allauth.AccountAdapter"
1✔
596
ACCOUNT_PRESERVE_USERNAME_CASING = False
1✔
597
ACCOUNT_USERNAME_REQUIRED = False
1✔
598

599
FXA_REQUESTS_TIMEOUT_SECONDS = config("FXA_REQUESTS_TIMEOUT_SECONDS", 1, cast=int)
1✔
600
FXA_SETTINGS_URL = config("FXA_SETTINGS_URL", f"{FXA_BASE_ORIGIN}/settings")
1✔
601
FXA_SUBSCRIPTIONS_URL = config(
1✔
602
    "FXA_SUBSCRIPTIONS_URL", f"{FXA_BASE_ORIGIN}/subscriptions"
603
)
604
# check https://mozilla.github.io/ecosystem-platform/api#tag/Subscriptions/operation/getOauthMozillasubscriptionsCustomerBillingandsubscriptions  # noqa: E501 (line too long)
605
FXA_ACCOUNTS_ENDPOINT = config(
1✔
606
    "FXA_ACCOUNTS_ENDPOINT",
607
    "https://api.accounts.firefox.com/v1",
608
)
609
FXA_SUPPORT_URL = config("FXA_SUPPORT_URL", f"{FXA_BASE_ORIGIN}/support/")
1✔
610

611
LOGGING = {
1✔
612
    "version": 1,
613
    "filters": {
614
        "request_id": {
615
            "()": "dockerflow.logging.RequestIdLogFilter",
616
        },
617
    },
618
    "formatters": {
619
        "json": {
620
            "()": "dockerflow.logging.JsonLogFormatter",
621
            "logger_name": "fx-private-relay",
622
        }
623
    },
624
    "handlers": {
625
        "console_out": {
626
            "level": "DEBUG",
627
            "class": "logging.StreamHandler",
628
            "stream": sys.stdout,
629
            "formatter": "json",
630
            "filters": ["request_id"],
631
        },
632
        "console_err": {
633
            "level": "DEBUG",
634
            "class": "logging.StreamHandler",
635
            "formatter": "json",
636
            "filters": ["request_id"],
637
        },
638
    },
639
    "loggers": {
640
        "root": {
641
            "handlers": ["console_err"],
642
            "level": "WARNING",
643
        },
644
        "request.summary": {
645
            "handlers": ["console_out"],
646
            "level": "DEBUG",
647
            # pytest's caplog fixture requires propagate=True
648
            # outside of pytest, use propagate=False to avoid double logs
649
            "propagate": IN_PYTEST,
650
        },
651
        "events": {
652
            "handlers": ["console_err"],
653
            "level": "ERROR",
654
            "propagate": IN_PYTEST,
655
        },
656
        "eventsinfo": {
657
            "handlers": ["console_out"],
658
            "level": "INFO",
659
            "propagate": IN_PYTEST,
660
        },
661
        "abusemetrics": {
662
            "handlers": ["console_out"],
663
            "level": "INFO",
664
            "propagate": IN_PYTEST,
665
        },
666
        "studymetrics": {
667
            "handlers": ["console_out"],
668
            "level": "INFO",
669
            "propagate": IN_PYTEST,
670
        },
671
        "markus": {
672
            "handlers": ["console_out"],
673
            "level": "DEBUG",
674
            "propagate": IN_PYTEST,
675
        },
676
        GLEAN_EVENT_MOZLOG_TYPE: {
677
            "handlers": ["console_out"],
678
            "level": "DEBUG",
679
            "propagate": IN_PYTEST,
680
        },
681
        "dockerflow": {
682
            "handlers": ["console_err"],
683
            "level": "WARNING",
684
            "propagate": IN_PYTEST,
685
        },
686
    },
687
}
688

689
DRF_RENDERERS = ["rest_framework.renderers.JSONRenderer"]
1✔
690
if DEBUG and not IN_PYTEST:
1!
691
    DRF_RENDERERS += [
×
692
        "rest_framework.renderers.BrowsableAPIRenderer",
693
    ]
694

695
FIRST_EMAIL_RATE_LIMIT = config("FIRST_EMAIL_RATE_LIMIT", "5/minute")
1✔
696
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
697
    FIRST_EMAIL_RATE_LIMIT = "1000/minute"
1✔
698

699
REST_FRAMEWORK = {
1✔
700
    "DEFAULT_AUTHENTICATION_CLASSES": [
701
        "api.authentication.FxaTokenAuthentication",
702
        "rest_framework.authentication.TokenAuthentication",
703
        "rest_framework.authentication.SessionAuthentication",
704
    ],
705
    "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
706
    "DEFAULT_RENDERER_CLASSES": DRF_RENDERERS,
707
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
708
    "EXCEPTION_HANDLER": "api.views.relay_exception_handler",
709
}
710
if API_DOCS_ENABLED:
1!
711
    REST_FRAMEWORK["DEFAULT_SCHEMA_CLASS"] = "drf_spectacular.openapi.AutoSchema"
1✔
712

713
SPECTACULAR_SETTINGS = {
1✔
714
    "SWAGGER_UI_DIST": "SIDECAR",
715
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
716
    "REDOC_DIST": "SIDECAR",
717
    "TITLE": "Firefox Relay API",
718
    "DESCRIPTION": (
719
        "Keep your email safe from hackers and trackers. This API is built with"
720
        " Django REST Framework and powers the Relay website UI, add-on,"
721
        " Firefox browser, and 3rd-party app integrations."
722
    ),
723
    "VERSION": "1.0",
724
    "SERVE_INCLUDE_SCHEMA": False,
725
    "PREPROCESSING_HOOKS": ["api.schema.preprocess_ignore_deprecated_paths"],
726
    "SORT_OPERATIONS": "api.schema.sort_by_tag",
727
}
728

729
if IN_PYTEST or RELAY_CHANNEL in ["local", "dev"]:
1!
730
    _DEFAULT_PHONE_RATE_LIMIT = "1000/minute"
1✔
731
else:
732
    _DEFAULT_PHONE_RATE_LIMIT = "5/minute"
×
733
PHONE_RATE_LIMIT = config("PHONE_RATE_LIMIT", _DEFAULT_PHONE_RATE_LIMIT)
1✔
734

735
# Turn on logging out on GET in development.
736
# This allows `/mock/logout/` in the front-end to clear the
737
# session cookie. Without this, after switching accounts in dev mode,
738
# then logging out again, API requests continue succeeding even without
739
# an auth token:
740
ACCOUNT_LOGOUT_ON_GET = DEBUG
1✔
741

742
# TODO: introduce an environment variable to control CORS_ALLOWED_ORIGINS
743
# https://mozilla-hub.atlassian.net/browse/MPP-3468
744
CORS_URLS_REGEX = r"^/api/"
1✔
745
CORS_ALLOWED_ORIGINS = [
1✔
746
    "https://vault.bitwarden.com",
747
    "https://vault.bitwarden.eu",
748
]
749
if RELAY_CHANNEL in ["dev", "stage"]:
1!
750
    CORS_ALLOWED_ORIGINS += [
×
751
        "https://vault.qa.bitwarden.pw",
752
        "https://vault.euqa.bitwarden.pw",
753
    ]
754
# Allow origins for each environment to help debug cors headers
755
if RELAY_CHANNEL == "local":
1!
756
    # In local dev, next runs on localhost and makes requests to /accounts/
757
    CORS_ALLOWED_ORIGINS += [
1✔
758
        "http://localhost:3000",
759
        "http://0.0.0.0:3000",
760
        "http://127.0.0.1:8000",
761
    ]
762
    CORS_URLS_REGEX = r"^/(api|accounts)/"
1✔
763
if RELAY_CHANNEL == "dev":
1!
764
    CORS_ALLOWED_ORIGINS += [
×
765
        "https://dev.fxprivaterelay.nonprod.cloudops.mozgcp.net",
766
    ]
767
if RELAY_CHANNEL == "stage":
1!
768
    CORS_ALLOWED_ORIGINS += [
×
769
        "https://stage.fxprivaterelay.nonprod.cloudops.mozgcp.net",
770
    ]
771

772
CSRF_TRUSTED_ORIGINS = []
1✔
773
if RELAY_CHANNEL == "local":
1!
774
    # In local development, the React UI can be served up from a different server
775
    # that needs to be allowed to make requests.
776
    # In production, the frontend is served by Django, is therefore on the same
777
    # origin and thus has access to the same cookies.
778
    CORS_ALLOW_CREDENTIALS = True
1✔
779
    SESSION_COOKIE_SAMESITE = None
1✔
780
    CSRF_TRUSTED_ORIGINS += [
1✔
781
        "http://localhost:3000",
782
        "http://0.0.0.0:3000",
783
    ]
784

785
SENTRY_RELEASE = config("SENTRY_RELEASE", "")
1✔
786
CIRCLE_SHA1 = config("CIRCLE_SHA1", "")
1✔
787
CIRCLE_TAG = config("CIRCLE_TAG", "")
1✔
788
CIRCLE_BRANCH = config("CIRCLE_BRANCH", "")
1✔
789

790
sentry_release: str | None = None
1✔
791
if SENTRY_RELEASE:
1!
792
    sentry_release = SENTRY_RELEASE
×
793
elif CIRCLE_TAG and CIRCLE_TAG != "unknown":
1!
794
    sentry_release = CIRCLE_TAG
1✔
795
elif (
×
796
    CIRCLE_SHA1
797
    and CIRCLE_SHA1 != "unknown"
798
    and CIRCLE_BRANCH
799
    and CIRCLE_BRANCH != "unknown"
800
):
801
    sentry_release = f"{CIRCLE_BRANCH}:{CIRCLE_SHA1}"
×
802

803
SENTRY_DEBUG = config("SENTRY_DEBUG", DEBUG, cast=bool)
1✔
804

805
SENTRY_ENVIRONMENT = config("SENTRY_ENVIRONMENT", RELAY_CHANNEL)
1✔
806
# Use "local" as default rather than "prod", to catch ngrok.io URLs
807
if SENTRY_ENVIRONMENT == "prod" and SITE_ORIGIN != "https://relay.firefox.com":
1!
808
    SENTRY_ENVIRONMENT = "local"
×
809

810
sentry_sdk.init(
1✔
811
    dsn=config("SENTRY_DSN", None),
812
    integrations=[DjangoIntegration(cache_spans=not DEBUG)],
813
    debug=SENTRY_DEBUG,
814
    include_local_variables=DEBUG,
815
    release=sentry_release,
816
    environment=SENTRY_ENVIRONMENT,
817
)
818
# Duplicates events for unhandled exceptions, but without useful tracebacks
819
ignore_logger("request.summary")
1✔
820
# Security scanner attempts, no action required
821
# Can be re-enabled when hostname allow list implemented at the load balancer
822
ignore_logger("django.security.DisallowedHost")
1✔
823
# Fluent errors, mostly when a translation is unavailable for the locale.
824
# It is more effective to process these from logs using BigQuery than to track
825
# as events in Sentry.
826
ignore_logger("django_ftl.message_errors")
1✔
827
# Security scanner attempts on Heroku dev, no action required
828
if RELAY_CHANNEL == "dev":
1!
829
    ignore_logger("django.security.SuspiciousFileOperation")
×
830

831

832
_MARKUS_BACKENDS: list[dict[str, Any]] = []
1✔
833
if DJANGO_STATSD_ENABLED:
1!
834
    _MARKUS_BACKENDS.append(
×
835
        {
836
            "class": "markus.backends.datadog.DatadogMetrics",
837
            "options": {
838
                "statsd_host": STATSD_HOST,
839
                "statsd_port": STATSD_PORT,
840
                "statsd_prefix": STATSD_PREFIX,
841
            },
842
        }
843
    )
844
if STATSD_DEBUG:
1!
845
    _MARKUS_BACKENDS.append(
×
846
        {
847
            "class": "markus.backends.logging.LoggingMetrics",
848
            "options": {
849
                "logger_name": "markus",
850
                "leader": "METRICS",
851
            },
852
        }
853
    )
854
markus.configure(backends=_MARKUS_BACKENDS)
1✔
855

856
if USE_SILK:
1!
857
    SILKY_PYTHON_PROFILER = True
×
858
    SILKY_PYTHON_PROFILER_BINARY = True
×
859
    SILKY_PYTHON_PROFILER_RESULT_PATH = ".silk-profiler"
×
860

861
# Settings for manage.py process_emails_from_sqs
862
PROCESS_EMAIL_BATCH_SIZE = config(
1✔
863
    "PROCESS_EMAIL_BATCH_SIZE", 10, cast=Choices(range(1, 11), cast=int)
864
)
865
PROCESS_EMAIL_DELETE_FAILED_MESSAGES = config(
1✔
866
    "PROCESS_EMAIL_DELETE_FAILED_MESSAGES", False, cast=bool
867
)
868
PROCESS_EMAIL_HEALTHCHECK_PATH = config(
1✔
869
    "PROCESS_EMAIL_HEALTHCHECK_PATH", os.path.join(TMP_DIR, "healthcheck.json")
870
)
871
PROCESS_EMAIL_MAX_SECONDS = config("PROCESS_EMAIL_MAX_SECONDS", 0, cast=int) or None
1✔
872
PROCESS_EMAIL_VERBOSITY = config(
1✔
873
    "PROCESS_EMAIL_VERBOSITY", 1, cast=Choices(range(0, 4), cast=int)
874
)
875
PROCESS_EMAIL_VISIBILITY_SECONDS = config(
1✔
876
    "PROCESS_EMAIL_VISIBILITY_SECONDS", 120, cast=int
877
)
878
PROCESS_EMAIL_WAIT_SECONDS = config("PROCESS_EMAIL_WAIT_SECONDS", 5, cast=int)
1✔
879
PROCESS_EMAIL_HEALTHCHECK_MAX_AGE = config(
1✔
880
    "PROCESS_EMAIL_HEALTHCHECK_MAX_AGE", 120, cast=int
881
)
882

883
# Django 3.2 switches default to BigAutoField
884
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
1✔
885

886
# python-dockerflow settings
887
DOCKERFLOW_VERSION_CALLBACK = "privaterelay.utils.get_version_info"
1✔
888
DOCKERFLOW_CHECKS = [
1✔
889
    "dockerflow.django.checks.check_database_connected",
890
    "dockerflow.django.checks.check_migrations_applied",
891
]
892
if REDIS_URL:
1!
893
    DOCKERFLOW_CHECKS.append("dockerflow.django.checks.check_redis_connected")
×
894
DOCKERFLOW_REQUEST_ID_HEADER_NAME = config("DOCKERFLOW_REQUEST_ID_HEADER_NAME", None)
1✔
895
SILENCED_SYSTEM_CHECKS = sorted(
1✔
896
    set(config("DJANGO_SILENCED_SYSTEM_CHECKS", default="", cast=Csv()))
897
    | {
898
        # (models.W040) SQLite does not support indexes with non-key columns.
899
        # RelayAddress index idx_ra_created_by_addon uses this for PostgreSQL.
900
        "models.W040",
901
    }
902
)
903

904
# django-ftl settings
905
AUTO_RELOAD_BUNDLES = False  # Requires pyinotify
1✔
906

907
# Patching for django-types
908
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