-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.py
1043 lines (944 loc) · 31.3 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import os
import warnings
from pathlib import Path
from typing import Callable
from django.urls import reverse_lazy
import sentry_sdk
from corsheaders.defaults import default_headers as default_cors_headers
from log_outgoing_requests.formatters import HttpFormatter
from notifications_api_common.settings import * # noqa
from .utils import (
config,
get_django_project_dir,
get_project_dirname,
get_sentry_integrations,
strip_protocol_from_origin,
)
PROJECT_DIRNAME = get_project_dirname()
# Build paths inside the project, so further paths can be defined relative to
# the code root.
DJANGO_PROJECT_DIR = get_django_project_dir()
BASE_DIR = Path(DJANGO_PROJECT_DIR).resolve().parents[1]
#
# Core Django settings
#
SITE_ID = config(
"SITE_ID",
default=1,
help_text="The database ID of the site object. You usually won't have to touch this.",
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config(
"SECRET_KEY",
help_text=(
"Secret key that's used for certain cryptographic utilities. "
"You should generate one via `miniwebtool <https://www.miniwebtool.com/django-secret-key-generator>`_"
),
)
# NEVER run with DEBUG=True in production-like environments
DEBUG = config(
"DEBUG",
default=False,
help_text=(
"Only set this to ``True`` on a local development environment. "
"Various other security settings are derived from this setting!"
),
)
# = domains we're running on
ALLOWED_HOSTS = config(
"ALLOWED_HOSTS",
default="",
split=True,
help_text=(
"a comma separated (without spaces!) list of domains that serve "
"the installation. Used to protect against Host header attacks."
),
group="Required",
)
USE_X_FORWARDED_HOST = config(
"USE_X_FORWARDED_HOST",
default=False,
help_text=(
"whether to grab the domain/host from the X-Forwarded-Host header or not. "
"This header is typically set by reverse proxies (such as nginx, traefik, Apache...). "
"Note: this is a header that can be spoofed and you need to ensure you control it before enabling this."
),
)
IS_HTTPS = config(
"IS_HTTPS",
default=not DEBUG,
help_text=(
"Used to construct absolute URLs and controls a variety of security settings. "
"Defaults to the inverse of ``DEBUG``."
),
auto_display_default=False,
)
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = "nl-nl"
TIME_ZONE = "UTC" # note: this *may* affect the output of DRF datetimes
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_THOUSAND_SEPARATOR = True
#
# DATABASE and CACHING setup
#
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": config(
"DB_NAME",
PROJECT_DIRNAME,
group="Database",
help_text="name of the PostgreSQL database.",
),
"USER": config(
"DB_USER",
PROJECT_DIRNAME,
group="Database",
help_text="username of the database user.",
),
"PASSWORD": config(
"DB_PASSWORD",
PROJECT_DIRNAME,
group="Database",
help_text="password of the database user.",
),
"HOST": config(
"DB_HOST",
"localhost",
group="Database",
help_text=(
"hostname of the PostgreSQL database. Defaults to ``db`` for the docker environment, "
"otherwise defaults to ``localhost``."
),
auto_display_default=False,
),
"PORT": config(
"DB_PORT", 5432, group="Database", help_text="port number of the database"
),
}
}
# keep the current schema for now and deal with migrating to BigAutoField later, see
# https://docs.djangoproject.com/en/4.0/ref/settings/#std:setting-DEFAULT_AUTO_FIELD
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
CACHE_DEFAULT = config(
"CACHE_DEFAULT",
"localhost:6379/0",
help_text="redis cache address for the default cache (this **MUST** be set when using Docker)",
group="Required",
)
CACHE_AXES = config(
"CACHE_AXES",
"localhost:6379/0",
help_text=(
"redis cache address for the brute force login protection cache "
"(this **MUST** be set when using Docker)"
),
group="Required",
)
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"redis://{CACHE_DEFAULT}",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True,
},
},
"axes": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"redis://{CACHE_AXES}",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True,
},
},
"oidc": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"redis://{CACHE_DEFAULT}",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True,
},
},
}
#
# APPLICATIONS enabled for this project
#
INSTALLED_APPS = [
# Note: contenttypes should be first, see Django ticket #10827
"django.contrib.contenttypes",
"django.contrib.auth",
"django.contrib.sessions",
# Note: If enabled, at least one Site object is required
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
# Optional applications.
"django_admin_index",
"ordered_model",
"django.contrib.admin",
# External applications.
"axes",
"django_filters",
"csp",
"corsheaders",
"vng_api_common",
"notifications_api_common",
"drf_spectacular",
"rest_framework",
"django_markup",
"solo",
# Two-factor authentication in the Django admin, enforced.
"django_otp",
"django_otp.plugins.otp_static",
"django_otp.plugins.otp_totp",
"two_factor",
"two_factor.plugins.webauthn",
"maykin_2fa",
"privates",
"django_jsonform",
"simple_certmanager",
"zgw_consumers",
"mozilla_django_oidc",
"mozilla_django_oidc_db",
"log_outgoing_requests",
"django_setup_configuration",
"open_api_framework",
PROJECT_DIRNAME,
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"maykin_2fa.middleware.OTPMiddleware",
"mozilla_django_oidc_db.middleware.SessionRefresh",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"axes.middleware.AxesMiddleware",
"csp.contrib.rate_limiting.RateLimitedCSPMiddleware",
]
ROOT_URLCONF = f"{PROJECT_DIRNAME}.urls"
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
)
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [Path(DJANGO_PROJECT_DIR) / "templates"],
"APP_DIRS": False, # conflicts with explicity specifying the loaders
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"open_api_framework.context_processors.admin_settings",
f"{PROJECT_DIRNAME}.utils.context_processors.settings",
],
"loaders": TEMPLATE_LOADERS,
},
}
]
WSGI_APPLICATION = f"{PROJECT_DIRNAME}.wsgi.application"
# Translations
LOCALE_PATHS = (Path(DJANGO_PROJECT_DIR) / "conf" / "locale",)
#
# SERVING of static and media files
#
STATIC_URL = "/static/"
STATIC_ROOT = Path(BASE_DIR) / "static"
# Additional locations of static files
STATICFILES_DIRS = [Path(DJANGO_PROJECT_DIR) / "static"]
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
MEDIA_ROOT = Path(BASE_DIR) / "media"
MEDIA_URL = "/media/"
FILE_UPLOAD_PERMISSIONS = 0o644
#
# Sending EMAIL
#
EMAIL_HOST = config(
"EMAIL_HOST",
default="localhost",
help_text="hostname for the outgoing e-mail server (this **MUST** be set when using Docker)",
group="Required",
)
EMAIL_PORT = config(
"EMAIL_PORT",
default=25,
help_text=(
"port number of the outgoing e-mail server. Note that if you're on Google Cloud, "
"sending e-mail via port 25 is completely blocked and you should use 487 for TLS."
),
) # disabled on Google Cloud, use 487 instead
EMAIL_HOST_USER = config(
"EMAIL_HOST_USER", default="", help_text="username to connect to the mail server"
)
EMAIL_HOST_PASSWORD = config(
"EMAIL_HOST_PASSWORD",
default="",
help_text="password to connect to the mail server",
)
EMAIL_USE_TLS = config(
"EMAIL_USE_TLS",
default=False,
help_text=(
"whether to use TLS or not to connect to the mail server. "
"Should be True if you're changing the ``EMAIL_PORT`` to 487."
),
)
EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = config(
"DEFAULT_FROM_EMAIL",
f"{PROJECT_DIRNAME}@example.com",
help_text="The default email address from which emails are sent",
)
#
# LOGGING
#
LOG_STDOUT = config(
"LOG_STDOUT", default=False, help_text="whether to log to stdout or not"
)
LOG_LEVEL = config(
"LOG_LEVEL",
default="WARNING",
help_text=(
"control the verbosity of logging output. "
"Available values are ``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO`` and ``DEBUG``"
),
)
LOG_QUERIES = config(
"LOG_QUERIES",
default=False,
help_text=(
"enable (query) logging at the database backend level. Note that you "
"must also set ``DEBUG=1``, which should be done very sparingly!"
),
)
LOG_REQUESTS = config(
"LOG_REQUESTS", default=False, help_text="enable logging of the outgoing requests"
)
if LOG_QUERIES and not DEBUG:
warnings.warn(
"Requested LOG_QUERIES=1 but DEBUG is false, no query logs will be emited.",
RuntimeWarning,
)
LOGGING_DIR = Path(BASE_DIR) / "log"
logging_root_handlers = ["console"] if LOG_STDOUT else ["project"]
logging_django_handlers = ["console"] if LOG_STDOUT else ["django"]
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(levelname)s %(name)s %(module)s %(process)d %(thread)d %(message)s"
},
"timestamped": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
"simple": {"format": "%(levelname)s %(message)s"},
"performance": {"format": "%(asctime)s %(process)d | %(thread)d | %(message)s"},
"db": {"format": "%(asctime)s | %(message)s"},
"outgoing_requests": {"()": HttpFormatter},
},
"filters": {
"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"},
},
"handlers": {
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
},
"null": {"level": "DEBUG", "class": "logging.NullHandler"},
"console": {
"level": LOG_LEVEL,
"class": "logging.StreamHandler",
"formatter": "timestamped",
},
"console_db": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "db",
},
"django": {
"level": LOG_LEVEL,
"class": "logging.handlers.RotatingFileHandler",
"filename": Path(LOGGING_DIR) / "django.log",
"formatter": "verbose",
"maxBytes": 1024 * 1024 * 10, # 10 MB
"backupCount": 10,
},
"project": {
"level": LOG_LEVEL,
"class": "logging.handlers.RotatingFileHandler",
"filename": Path(LOGGING_DIR) / f"{PROJECT_DIRNAME}.log",
"formatter": "verbose",
"maxBytes": 1024 * 1024 * 10, # 10 MB
"backupCount": 10,
},
"performance": {
"level": "INFO",
"class": "logging.handlers.RotatingFileHandler",
"filename": Path(LOGGING_DIR) / "performance.log",
"formatter": "performance",
"maxBytes": 1024 * 1024 * 10, # 10 MB
"backupCount": 10,
},
"requests": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler",
"filename": Path(LOGGING_DIR) / "requests.log",
"formatter": "timestamped",
"maxBytes": 1024 * 1024 * 10, # 10 MB
"backupCount": 10,
},
"log_outgoing_requests": {
"level": "DEBUG",
"formatter": "outgoing_requests",
"class": "logging.StreamHandler", # to write to stdout
},
"save_outgoing_requests": {
"level": "DEBUG",
# enabling saving to database
"class": "log_outgoing_requests.handlers.DatabaseOutgoingRequestsHandler",
},
},
"loggers": {
"": {
"handlers": logging_root_handlers,
"level": "ERROR",
"propagate": False,
},
PROJECT_DIRNAME: {
"handlers": logging_root_handlers,
"level": LOG_LEVEL,
"propagate": True,
},
"mozilla_django_oidc": {
"handlers": logging_root_handlers,
"level": LOG_LEVEL,
},
f"{PROJECT_DIRNAME}.utils.middleware": {
"handlers": logging_root_handlers,
"level": LOG_LEVEL,
"propagate": False,
},
"vng_api_common": {
"handlers": ["console"],
"level": LOG_LEVEL,
"propagate": True,
},
"django.db.backends": {
"handlers": ["console_db"] if LOG_QUERIES else [],
"level": "DEBUG",
"propagate": False,
},
"django.request": {
"handlers": logging_django_handlers,
"level": LOG_LEVEL,
"propagate": True,
},
"django.template": {
"handlers": ["console"],
"level": "INFO",
"propagate": False,
},
"log_outgoing_requests": {
"handlers": (
["log_outgoing_requests", "save_outgoing_requests"]
if LOG_REQUESTS
else []
),
"level": "DEBUG",
"propagate": True,
},
},
}
#
# AUTH settings - user accounts, passwords, backends...
#
AUTH_USER_MODEL = "accounts.User"
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# Allow logging in with both username+password and email+password
AUTHENTICATION_BACKENDS = [
"axes.backends.AxesBackend",
f"{PROJECT_DIRNAME}.accounts.backends.UserModelEmailBackend",
"django.contrib.auth.backends.ModelBackend",
"mozilla_django_oidc_db.backends.OIDCAuthenticationBackend",
]
SESSION_COOKIE_NAME = f"{PROJECT_DIRNAME}_sessionid"
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
LOGIN_URL = reverse_lazy("admin:login")
LOGIN_REDIRECT_URL = reverse_lazy("admin:index")
LOGOUT_REDIRECT_URL = reverse_lazy("admin:index")
#
# SECURITY settings
#
SESSION_COOKIE_SECURE = IS_HTTPS
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = config(
"SESSION_COOKIE_SAMESITE",
"Strict",
help_text=(
"The value of the SameSite flag on the session cookie. This flag prevents the "
"cookie from being sent in cross-site requests thus preventing CSRF attacks and "
"making some methods of stealing session cookie impossible."
),
)
CSRF_COOKIE_SECURE = IS_HTTPS
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = config(
"CSRF_COOKIE_SAMESITE",
"Strict",
help_text=(
"The value of the SameSite flag on the CSRF cookie. This flag prevents the cookie "
"from being sent in cross-site requests."
),
)
if IS_HTTPS:
SECURE_HSTS_SECONDS = 31536000
X_FRAME_OPTIONS = "DENY"
#
# Silenced checks
#
SILENCED_SYSTEM_CHECKS = [
"rest_framework.W001",
"debug_toolbar.W006",
]
#
# Increase number of parameters for GET/POST requests
#
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000
#
# Custom settings
#
ENVIRONMENT = config(
"ENVIRONMENT",
"",
help_text=(
"An identifier for the environment, displayed in the admin depending on "
"the settings module used and included in the error monitoring (see ``SENTRY_DSN``). "
"The default is set according to ``DJANGO_SETTINGS_MODULE``."
),
auto_display_default=False,
)
ENVIRONMENT_SHOWN_IN_ADMIN = True
# Generating the schema, depending on the component
subpath = config(
"SUBPATH",
None,
help_text=(
"If hosted on a subpath, provide the value here. If you provide ``/gateway``, "
"the component assumes its running at the base URL: ``https://somedomain/gateway/``. "
"Defaults to an empty string."
),
)
if subpath:
if not subpath.startswith("/"):
subpath = f"/{subpath}"
SUBPATH = subpath
if "GIT_SHA" in os.environ:
GIT_SHA = config("GIT_SHA", "", add_to_docs=False)
# in docker (build) context, there is no .git directory
elif (Path(BASE_DIR) / ".git").exists():
try:
import git
except ImportError:
GIT_SHA = None
else:
repo = git.Repo(search_parent_directories=True)
GIT_SHA = repo.head.object.hexsha
else:
GIT_SHA = None
RELEASE = config(
"RELEASE",
GIT_SHA,
help_text="The version number or commit hash of the application (this is also sent to Sentry).",
auto_display_default=False,
)
NUM_PROXIES = config( # TODO: this also is relevant for DRF settings if/when we have rate-limited endpoints
"NUM_PROXIES",
default=1,
cast=lambda val: int(val) if val is not None else None,
help_text=(
"the number of reverse proxies in front of the application, as an integer. "
"This is used to determine the actual client IP adres. "
"On Kubernetes with an ingress you typically want to set this to 2."
),
)
##############################
# #
# 3RD PARTY LIBRARY SETTINGS #
# #
##############################
#
# DJANGO-AXES (6.0+)
#
AXES_CACHE = "axes" # refers to CACHES setting
# The number of login attempts allowed before a record is created for the
# failed logins. Default: 3
AXES_FAILURE_LIMIT = 5
AXES_LOCK_OUT_AT_FAILURE = True # Default: True
# If set, defines a period of inactivity after which old failed login attempts
# will be forgotten. Can be set to a python timedelta object or an integer. If
# an integer, will be interpreted as a number of hours. Default: None
AXES_COOLOFF_TIME = datetime.timedelta(minutes=5)
# The number of reverse proxies
AXES_IPWARE_PROXY_COUNT = NUM_PROXIES - 1 if NUM_PROXIES else None
# If set, specifies a template to render when a user is locked out. Template
# receives cooloff_time and failure_limit as context variables. Default: None
AXES_LOCKOUT_TEMPLATE = "account_blocked.html"
AXES_LOCKOUT_PARAMETERS = [["ip_address", "user_agent", "username"]]
AXES_BEHIND_REVERSE_PROXY = IS_HTTPS
# By default, Axes obfuscates values for formfields named "password", but the admin
# interface login formfield name is "auth-password", so we want to obfuscate that
AXES_SENSITIVE_PARAMETERS = ["password", "auth-password"] # nosec
# The default meta precedence order
IPWARE_META_PRECEDENCE_ORDER = (
"HTTP_X_FORWARDED_FOR",
"X_FORWARDED_FOR", # <client>, <proxy1>, <proxy2>
"HTTP_CLIENT_IP",
"HTTP_X_REAL_IP",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR",
)
#
# DJANGO-CORS-MIDDLEWARE
#
CORS_ALLOW_ALL_ORIGINS = config(
"CORS_ALLOW_ALL_ORIGINS",
default=False,
group="Cross-Origin-Resource-Sharing",
help_text="allow cross-domain access from any client",
)
CORS_ALLOWED_ORIGINS = config(
"CORS_ALLOWED_ORIGINS",
split=True,
default=[],
group="Cross-Origin-Resource-Sharing",
help_text=(
"explicitly list the allowed origins for cross-domain requests. "
"Example: http://localhost:3000,https://some-app.gemeente.nl"
),
)
CORS_ALLOWED_ORIGIN_REGEXES = config(
"CORS_ALLOWED_ORIGIN_REGEXES",
split=True,
default=[],
group="Cross-Origin-Resource-Sharing",
help_text="same as ``CORS_ALLOWED_ORIGINS``, but supports regular expressions",
)
# Authorization is included in default_cors_headers
CORS_ALLOW_HEADERS = (
list(default_cors_headers)
+ [
"accept-crs",
"content-crs",
]
+ config(
"CORS_EXTRA_ALLOW_HEADERS",
split=True,
default=[],
group="Cross-Origin-Resource-Sharing",
help_text=(
"headers that are allowed to be sent as part of the cross-domain request. "
"By default, Authorization, Accept-Crs and Content-Crs are already included. "
"The value of this variable is added to these already included headers."
),
)
)
CORS_EXPOSE_HEADERS = [
"content-crs",
]
# Django's SESSION_COOKIE_SAMESITE = "Lax" prevents session cookies from being sent
# cross-domain. There is no need for these cookies to be sent, since the API itself
# uses Bearer Authentication.
# we can't easily derive this from django-cors-headers, see also
# https://pypi.org/project/django-cors-headers/#csrf-integration
#
# So we do a best effort attempt at re-using configuration parameters, with an escape
# hatch to override it.
CSRF_TRUSTED_ORIGINS = config(
"CSRF_TRUSTED_ORIGINS",
split=True,
default=[strip_protocol_from_origin(origin) for origin in CORS_ALLOWED_ORIGINS],
help_text="A list of trusted origins for unsafe requests (e.g. POST)",
)
#
# DJANGO-PRIVATES -- safely serve files after authorization
#
PRIVATE_MEDIA_ROOT = Path(BASE_DIR) / "private-media"
PRIVATE_MEDIA_URL = "/private-media/"
#
# NOTIFICATIONS-API-COMMON
#
NOTIFICATIONS_DISABLED = config(
"NOTIFICATIONS_DISABLED",
default=False,
help_text=(
"indicates whether or not notifications should be sent to the Notificaties API "
"for operations on the API endpoints. "
"Defaults to ``True`` for the ``dev`` environment, otherwise defaults to ``False``"
),
auto_display_default=False,
)
#
# SENTRY - error monitoring
#
def init_sentry(before_send: Callable | None = None):
SENTRY_DSN = config(
"SENTRY_DSN",
None,
help_text=(
"URL of the sentry project to send error reports to. Default empty, "
"i.e. -> no monitoring set up. Highly recommended to configure this."
),
auto_display_default=False,
)
if SENTRY_DSN:
SENTRY_CONFIG = {
"dsn": SENTRY_DSN,
"release": RELEASE or "RELEASE not set",
"environment": ENVIRONMENT,
}
# Allow projects to define their own before_send filters
if before_send:
SENTRY_CONFIG["before_send"] = before_send
sentry_sdk.init(
**SENTRY_CONFIG,
integrations=get_sentry_integrations(),
send_default_pii=True,
)
#
# CELERY
#
CELERY_BROKER_URL = config(
"CELERY_RESULT_BACKEND",
"redis://localhost:6379/1",
group="Celery",
help_text="the URL of the backend/broker that will be used by Celery to send the notifications",
)
CELERY_RESULT_BACKEND = config(
"CELERY_RESULT_BACKEND",
"redis://localhost:6379/1",
group="Celery",
help_text="the URL of the backend/broker that will be used by Celery to send the notifications",
)
#
# DJANGO-ADMIN-INDEX
#
ADMIN_INDEX_SHOW_REMAINING_APPS_TO_SUPERUSERS = False
ADMIN_INDEX_AUTO_CREATE_APP_GROUP = False
#
# Mozilla Django OIDC DB settings
#
OIDC_AUTHENTICATE_CLASS = "mozilla_django_oidc_db.views.OIDCAuthenticationRequestView"
# Use custom callback view to handle admin login error situations
# NOTE the AdminLoginFailure view for mozilla-django-oidc-db should be added to the projects
# urlpatterns to properly catch errors
OIDC_CALLBACK_CLASS = "mozilla_django_oidc_db.views.OIDCCallbackView"
MOZILLA_DJANGO_OIDC_DB_CACHE = "oidc"
MOZILLA_DJANGO_OIDC_DB_CACHE_TIMEOUT = 5 * 60
#
# Elastic APM
#
ELASTIC_APM_SERVER_URL = config(
"ELASTIC_APM_SERVER_URL",
None,
help_text="URL where Elastic APM is hosted",
group="Elastic APM",
)
ELASTIC_APM = {
# FIXME this does change the default service name, because PROJECT_DIRNAME != PROJECT_NAME
"SERVICE_NAME": config(
"ELASTIC_APM_SERVICE_NAME",
f"{PROJECT_DIRNAME} - {ENVIRONMENT}",
help_text=(
f"Name of the service for this application in Elastic APM. "
f"Defaults to ``{PROJECT_DIRNAME} - <environment>``"
),
group="Elastic APM",
auto_display_default=False,
),
"SECRET_TOKEN": config(
"ELASTIC_APM_SECRET_TOKEN",
"default",
help_text="Token used to communicate with Elastic APM",
group="Elastic APM",
),
"SERVER_URL": ELASTIC_APM_SERVER_URL,
"TRANSACTION_SAMPLE_RATE": config(
"ELASTIC_APM_TRANSACTION_SAMPLE_RATE",
0.1,
help_text=(
"By default, the agent will sample every transaction (e.g. request to your service). "
"To reduce overhead and storage requirements, set the sample rate to a value between 0.0 and 1.0"
),
group="Elastic APM",
),
}
if not ELASTIC_APM_SERVER_URL:
ELASTIC_APM["ENABLED"] = False
ELASTIC_APM["SERVER_URL"] = "http://localhost:8200"
else:
MIDDLEWARE = ["elasticapm.contrib.django.middleware.TracingMiddleware"] + MIDDLEWARE
INSTALLED_APPS = INSTALLED_APPS + [
"elasticapm.contrib.django",
]
#
# MAYKIN-2FA
# Uses django-two-factor-auth under the hood, so relevant upstream package settings
# apply too.
#
# we run the admin site monkeypatch instead.
TWO_FACTOR_PATCH_ADMIN = False
# Relying Party name for WebAuthn (hardware tokens)
TWO_FACTOR_WEBAUTHN_RP_NAME = f"{PROJECT_DIRNAME} - admin"
# use platform for fingerprint readers etc., or remove the setting to allow any.
# cross-platform would limit the options to devices like phones/yubikeys
TWO_FACTOR_WEBAUTHN_AUTHENTICATOR_ATTACHMENT = "cross-platform"
# add entries from AUTHENTICATION_BACKENDS that already enforce their own two-factor
# auth, avoiding having some set up MFA again in the project.
MAYKIN_2FA_ALLOW_MFA_BYPASS_BACKENDS = [
"mozilla_django_oidc_db.backends.OIDCAuthenticationBackend",
]
# if DISABLE_2FA is true, fill the MAYKIN_2FA_ALLOW_MFA_BYPASS_BACKENDS with all
# configured AUTHENTICATION_BACKENDS and thus disabeling the entire 2FA chain.
if config(
"DISABLE_2FA",
default=False,
help_text="Whether or not two factor authentication should be disabled",
): # pragma: no cover
MAYKIN_2FA_ALLOW_MFA_BYPASS_BACKENDS = AUTHENTICATION_BACKENDS
#
# LOG OUTGOING REQUESTS
#
LOG_OUTGOING_REQUESTS_EMIT_BODY = config(
"LOG_OUTGOING_REQUESTS_EMIT_BODY",
default=True,
help_text="Whether or not outgoing request bodies should be logged",
)
LOG_OUTGOING_REQUESTS_DB_SAVE = config(
"LOG_OUTGOING_REQUESTS_DB_SAVE",
default=False,
help_text="Whether or not outgoing request logs should be saved to the database",
)
LOG_OUTGOING_REQUESTS_DB_SAVE_BODY = config(
"LOG_OUTGOING_REQUESTS_DB_SAVE_BODY",
default=True,
help_text="Whether or not outgoing request bodies should be saved to the database",
)
LOG_OUTGOING_REQUESTS_RESET_DB_SAVE_AFTER = None
LOG_OUTGOING_REQUESTS_MAX_AGE = config(
"LOG_OUTGOING_REQUESTS_MAX_AGE",
default=7,
help_text="The amount of time after which request logs should be deleted from the database",
) # number of days
#
# Django CSP settings
#
# explanation of directives: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# and how to specify them: https://django-csp.readthedocs.io/en/latest/configuration.html
#
# NOTE: make sure values are a tuple or list, and to quote special values like 'self'
# ideally we'd use BASE_URI but it'd have to be lazy or cause issues
CSP_DEFAULT_SRC = [
"'self'",
] + config(
"CSP_EXTRA_DEFAULT_SRC",
default=[],
split=True,
group="Content Security Policy",
help_text="Extra default source URLs for CSP other than ``self``. "
"Used for ``img-src``, ``style-src`` and ``script-src``",
)
CSP_REPORT_URI = config(
"CSP_REPORT_URI",
None,
group="Content Security Policy",
help_text="URI of the``report-uri`` directive.",
)
CSP_REPORT_PERCENTAGE = config(
"CSP_REPORT_PERCENTAGE",
0,
group="Content Security Policy",
help_text="Percentage of requests that get the ``report-uri`` directive.",
) # float between 0 and 1
CSP_FORM_ACTION = (
config(
"CSP_FORM_ACTION",
default=["\"'self'\""]
+ config(
"CSP_EXTRA_FORM_ACTION",
default=[],
split=True,
group="Content Security Policy",
help_text="Add additional ``form-action`` source to the default ",
),
split=True,
group="Content Security Policy",
help_text="Override the default ``form-action`` source",
)
+ CORS_ALLOWED_ORIGINS
)