Repository navigation
Expand file tree
/
Copy pathsettings.dist.py
More file actions
2434 lines (2260 loc) · 130 KB
/
Copy pathsettings.dist.py
File metadata and controls
2434 lines (2260 loc) · 130 KB
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
# noqa: N999 - see https://github.com/DefectDojo/django-DefectDojo/pull/11647
#########################################################################################################
# It is not recommended to edit file 'settings.dist.py', for production deployments. #
# Any customization of variables need to be done via environmental variables or in 'local_settings.py'. #
# For more information check https://documentation.defectdojo.com/getting_started/configuration/ #
#########################################################################################################
# Django settings for DefectDojo
import json
import logging
import os
import warnings
from datetime import timedelta
from email.utils import getaddresses
from pathlib import Path
import environ
from celery.schedules import crontab
from dojo import __version__
from dojo.auditlog.settings import ( # noqa: F401 -- re-exported as Django settings
AUDITLOG_DISABLE_ON_RAW_SAVE,
PGHISTORY_CONTEXT_FIELD,
PGHISTORY_FOREIGN_KEY_FIELD,
PGHISTORY_OBJ_FIELD,
)
from dojo.auditlog.settings import ENV_SCHEMA as AUDITLOG_ENV_SCHEMA
from dojo.notifications.settings import (
NOTIFICATIONS_ENV_DEFAULTS,
)
from dojo.notifications.settings import (
populate_settings as _populate_notifications_settings,
)
logger = logging.getLogger(__name__)
root = environ.Path(__file__) - 3 # Three folders back
# reference: https://pypi.org/project/django-environ/
env = environ.FileAwareEnv(
# Set casting and default values
DD_SITE_URL=(str, "http://localhost:8080"),
DD_DEBUG=(bool, False),
DD_DJANGO_DEBUG_TOOLBAR_ENABLED=(bool, False),
# django-jsonfield-backport raises a warning that can be ignored,
# see https://github.com/laymonage/django-jsonfield-backport
# debug_toolbar.E001 is raised when running tests in dev mode via run-unittests.sh
DD_SILENCED_SYSTEM_CHECKS=(list, ["debug_toolbar.E001", "django_jsonfield_backport.W001", "polymorphic.W001", "polymorphic.W002"]),
DD_TEMPLATE_DEBUG=(bool, False),
DD_LOG_LEVEL=(str, ""),
DD_DJANGO_METRICS_ENABLED=(bool, False),
DD_LOGIN_REDIRECT_URL=(str, "/"),
DD_LOGIN_URL=(str, "/login"),
DD_DJANGO_ADMIN_ENABLED=(bool, False),
DD_SESSION_COOKIE_HTTPONLY=(bool, True),
DD_CSRF_COOKIE_HTTPONLY=(bool, True),
DD_SECURE_SSL_REDIRECT=(bool, False),
DD_SECURE_CROSS_ORIGIN_OPENER_POLICY=(str, "same-origin"),
DD_SECURE_HSTS_INCLUDE_SUBDOMAINS=(bool, False),
DD_SECURE_HSTS_SECONDS=(int, 31536000), # One year expiration
DD_SESSION_COOKIE_SECURE=(bool, False),
DD_SESSION_EXPIRE_AT_BROWSER_CLOSE=(bool, False),
DD_SESSION_EXPIRE_WARNING=(int, 300), # warning 5 mins before expiration
DD_SESSION_COOKIE_AGE=(int, 1209600), # 14 days
DD_CSRF_COOKIE_SECURE=(bool, False),
DD_CSRF_TRUSTED_ORIGINS=(list, []),
DD_SECURE_CONTENT_TYPE_NOSNIFF=(bool, True),
DD_CSRF_COOKIE_SAMESITE=(str, "Lax"),
DD_SESSION_COOKIE_SAMESITE=(str, "Lax"),
DD_APPEND_SLASH=(bool, True),
DD_TIME_ZONE=(str, "UTC"),
DD_LANG=(str, "en-us"),
DD_TEAM_NAME=(str, "Security Team"),
DD_ADMINS=(str, "DefectDojo:dojo@localhost,Admin:admin@localhost"),
DD_WHITENOISE=(bool, False),
DD_TRACK_MIGRATIONS=(bool, True),
DD_SECURE_PROXY_SSL_HEADER=(bool, False),
DD_TEST_RUNNER=(str, "django.test.runner.DiscoverRunner"),
DD_URL_PREFIX=(str, ""),
DD_ROOT=(str, root("dojo")),
DD_LANGUAGE_CODE=(str, "en-us"),
DD_SITE_ID=(int, 1),
DD_USE_I18N=(bool, True),
DD_USE_TZ=(bool, True),
DD_MEDIA_URL=(str, "/media/"),
DD_MEDIA_ROOT=(str, root("media")),
DD_STATIC_URL=(str, "/static/"),
DD_STATIC_ROOT=(str, root("static")),
DD_CELERY_BROKER_URL=(str, ""),
DD_CELERY_BROKER_SCHEME=(str, "sqla+sqlite"),
DD_CELERY_BROKER_USER=(str, ""),
DD_CELERY_BROKER_PASSWORD=(str, ""),
DD_CELERY_BROKER_HOST=(str, ""),
DD_CELERY_BROKER_PORT=(int, -1),
DD_CELERY_BROKER_PATH=(str, "/dojo.celerydb.sqlite"),
DD_CELERY_BROKER_PARAMS=(str, ""),
DD_CELERY_BROKER_TRANSPORT_OPTIONS=(str, ""),
DD_CELERY_TASK_IGNORE_RESULT=(bool, True),
# Max seconds the 'async_wait' deduplication execution mode will wait for
# background deduplication/post-processing to finish before responding anyway.
DD_DEDUPLICATION_ASYNC_WAIT_TIMEOUT=(int, 60),
# Test-only: artificial delay (seconds) injected at the start of
# post_process_findings_batch so integration tests can deterministically
# observe that 'async_wait' blocks on deduplication while 'async' does not.
# Must stay 0 in production. The _FILTER (a finding-title prefix) scopes the
# delay to a single test's findings so unrelated dedupe tests are not slowed.
DD_DEDUPLICATION_BATCH_PROCESS_TEST_DELAY=(int, 0),
DD_DEDUPLICATION_BATCH_PROCESS_TEST_DELAY_FILTER=(str, ""),
DD_CELERY_RESULT_BACKEND=(str, "django-db"),
DD_CELERY_RESULT_EXPIRES=(int, 86400),
DD_CELERY_BEAT_SCHEDULE_FILENAME=(str, root("dojo.celery.beat.db")),
DD_CELERY_TASK_SERIALIZER=(str, "json"),
DD_CELERY_LOG_LEVEL=(str, "INFO"),
# Hard ceiling on task runtime. When reached, the worker process is sent SIGKILL — no cleanup
# code runs. Always set higher than DD_CELERY_TASK_SOFT_TIME_LIMIT. (0 = disabled, no limit)
DD_CELERY_TASK_TIME_LIMIT=(int, 43200), # default: 12 hours
# Raises SoftTimeLimitExceeded inside the task, giving it a chance to clean up before the hard
# kill. Set a few seconds below DD_CELERY_TASK_TIME_LIMIT so cleanup has time to finish.
# (0 = disabled, no limit)
DD_CELERY_TASK_SOFT_TIME_LIMIT=(int, 0),
# If a task sits in the broker queue for longer than this without being picked up by a worker,
# Celery silently discards it — it is never executed and no exception is raised. Does not
# affect tasks that are already running. (0 = disabled, no limit)
DD_CELERY_TASK_DEFAULT_EXPIRES=(int, 43200), # default: 12 hours
# A product's grade is recalculated at most once per this many seconds: the first finding change
# in a window queues one calculate_grade task with this countdown, and later changes in the same
# window are no-ops. 0 queues a task for every change.
DD_PRODUCT_GRADE_DEBOUNCE_SECONDS=(int, 30),
DD_TAG_BULK_ADD_BATCH_SIZE=(int, 1000),
# Tagulous slug truncate unique setting. Set to -1 to use tagulous internal default (5)
DD_TAGULOUS_SLUG_TRUNCATE_UNIQUE=(int, -1),
# Master switch for django-watson. When True (default) the post-save/pre-delete
# search indexers are registered on 9 models (write-amplification on every save,
# Finding imports especially) and the legacy /simple_search page (watson's only
# reader) is served. When False, nothing is registered, /simple_search returns
# 410 Gone, and installwatson is skipped. Pro ships this False: its native
# Postgres search (pro/search/) fully replaces watson.
DD_WATSON_SEARCH_ENABLED=(bool, True),
# Batch size for async watson search-index update tasks. Also doubles as
# the per-request intermediate-flush threshold: once the in-memory watson
# context reaches this many pending objects mid-request,
# AsyncSearchContextMiddleware flushes them to async celery tasks instead
# of waiting for end-of-request. Set to 0 (or negative) to disable the
# intermediate flush.
DD_WATSON_ASYNC_INDEX_UPDATE_BATCH_SIZE=(int, 1000),
# When True, the async watson indexer auto-derives select_related/prefetch_related
# paths from each adapter's `fields`/`store` to avoid N+1 queries during indexing.
# Falls back to a plain queryset on any error (logged).
DD_WATSON_INDEX_PREFETCH_ENABLED=(bool, True),
DD_FOOTER_VERSION=(str, ""),
# Toggle for the highly accessible notice at the top of forms ("Required fields are marked with an asterisk*")
DD_SHOW_A11Y_REQUIRED_FIELDS_NOTICE=(bool, True),
DD_DATABASE_ENGINE=(str, "django.db.backends.postgresql"),
DD_DATABASE_HOST=(str, "postgres"),
DD_DATABASE_NAME=(str, "defectdojo"),
# default django database name for testing is test_<dbname>
DD_TEST_DATABASE_NAME=(str, "test_defectdojo"),
DD_DATABASE_PASSWORD=(str, "defectdojo"),
DD_DATABASE_PORT=(int, 3306),
DD_DATABASE_USER=(str, "defectdojo"),
DD_SECRET_KEY=(str, ""),
# Older secret keys, comma separated, kept readable while DD_SECRET_KEY changes
DD_SECRET_KEY_FALLBACKS=(list, []),
DD_CREDENTIAL_AES_256_KEY=(str, "."),
DD_DATA_UPLOAD_MAX_MEMORY_SIZE=(int, 8388608), # Max post size set to 8mb
DD_DATA_UPLOAD_MAX_NUMBER_FIELDS=(int, 10240), # Max number of GET/POST parameters in a request
DD_MAX_ZIP_MEMBERS=(int, 1000),
DD_MAX_ZIP_MEMBER_SIZE=(int, 512 * 1024 * 1024), # 512 MB per member (uncompressed)
DD_MAX_ZIP_TOTAL_SIZE=(int, 1 * 1024 * 1024 * 1024), # 1 GB total (uncompressed)
DD_MAX_ZIP_RATIO=(int, 100), # max compression ratio (uncompressed / compressed)
DD_FORGOT_PASSWORD=(bool, True), # do we show link "I forgot my password" on login screen
DD_PASSWORD_RESET_TIMEOUT=(int, 259200), # 3 days, in seconds (the deafult)
DD_FORGOT_USERNAME=(bool, True), # do we show link "I forgot my username" on login screen
DD_OS_MESSAGE_ENABLED=(bool, True), # show the open-source "Upgrade to Pro" / OS message promo banner
DD_GITHUB_STAR_PROMPT_ENABLED=(bool, True), # occasionally ask established users to star DefectDojo on GitHub
# Some security policies require allowing users to have only one active session
DD_SINGLE_USER_SESSION=(bool, False),
# if somebody is using own documentation how to use DefectDojo in his own company
DD_DOCUMENTATION_URL=(str, "https://documentation.defectdojo.com"),
# merging findings doesn't always work well with dedupe and reimport etc.
# disable it if you see any issues (and report them on github)
DD_DISABLE_FINDING_MERGE=(bool, False),
# SLA Notifications via alerts and JIRA comments
# enable either DD_SLA_NOTIFY_ACTIVE or DD_SLA_NOTIFY_ACTIVE_VERIFIED_ONLY to enable the feature.
# If desired you can enable to only notify for Findings that are linked to JIRA issues.
# SLA + alert + notification env-var schema lives in dojo/notifications/settings.py.
# maximum number of result in search as search can be an expensive operation
DD_SEARCH_MAX_RESULTS=(int, 100),
DD_SIMILAR_FINDINGS_MAX_RESULTS=(int, 25),
# The maximum number of request/response pairs to return from the API. Values <0 return all pairs.
DD_MAX_REQRESP_FROM_API=(int, -1),
DD_MAX_AUTOCOMPLETE_WORDS=(int, 20000),
DD_JIRA_SSL_VERIFY=(bool, True),
DD_JIRA_DESCRIPTION_MAX_LENGTH=(int, 32767),
# When interacting with jira tickets that attached finding groups, we should no be opening any findings
# on the DefectDojo side because jira has no way of knowing if a finding really should be reopened or not
DD_JIRA_WEBHOOK_ALLOW_FINDING_GROUP_REOPEN=(bool, False),
# JIRA connection retry and timeout settings: https://developer.atlassian.com/cloud/jira/platform/rate-limiting/
# Maximum number of retry attempts for recoverable errors (429, 503, ConnectionError)
# See https://jira.readthedocs.io/ for more in the jira library used by DefectDojo
# Note: The jira library has a built-in maximum wait time of 60s for rate limiting retries.
# If JIRA's Retry-After header indicates a wait time longer than 60s, the request will fail and not be retried.
DD_JIRA_MAX_RETRIES=(int, 3),
# Connection timeout (seconds) for establishing a connection to the JIRA server
DD_JIRA_CONNECT_TIMEOUT=(int, 10),
# Read timeout (seconds) for waiting for a response from the JIRA server
DD_JIRA_READ_TIMEOUT=(int, 30),
# You can set extra Jira issue types via a simple env var that supports a csv format, like "Work Item,Vulnerability"
DD_JIRA_EXTRA_ISSUE_TYPES=(str, ""),
# if you want to keep logging to the console but in json format, change this here to 'json_console'
DD_LOGGING_HANDLER=(str, "console"),
# If true, drf-spectacular will load CSS & JS from default CDN, otherwise from static resources
DD_DEFAULT_SWAGGER_UI=(bool, False),
DD_TAG_PREFETCHING=(bool, True),
DD_QUALYS_WAS_WEAKNESS_IS_VULN=(bool, False),
# Give each Qualys WAS finding the scanner's UNIQUE_ID instead of grouping findings by QID
DD_QUALYS_WAS_UNIQUE_ID=(bool, False),
# regular expression to exclude one or more parsers
# could be usefull to limit parser allowed
# AWS Scout2 Scan Parser is deprecated (see https://github.com/DefectDojo/django-DefectDojo/pull/5268)
# when enabled in sytem settings, every minute a job run to delete excess duplicates
# we limit the amount of duplicates that can be deleted in a single run of that job
# to prevent overlapping runs of that job from occurrring
DD_DUPE_DELETE_MAX_PER_RUN=(int, 200),
# Seconds the async_dupe_delete singleton marker is held. A run holds it for its whole
# duration and releases it when it finishes; this timeout is only the ceiling for a worker
# that dies mid-run without releasing it. It must comfortably exceed a normal run so the
# lock is never released out from under an in-flight run (default 30 minutes).
DD_DUPE_DELETE_LOCK_EXPIRE=(int, 1800),
# Minutes since a duplicate was last saved before the excess-duplicate delete may remove it,
# which covers a create request still writing the finding's child rows. 0 turns the wait off.
DD_DUPE_DELETE_GRACE_MINUTES=(int, 1),
# The excess-duplicate delete skips the duplicates of a test while an import is writing it
# (a PostgreSQL advisory lock the import holds until it ends; see dojo/importers/import_lock.py).
# Turn off behind a connection pooler in transaction mode, where session locks do not hold.
DD_DUPE_DELETE_SKIP_TESTS_UNDER_IMPORT=(bool, True),
# An import lock whose every holder has been idle this many minutes is treated as abandoned (left
# behind by a host that died, or by a pooler) and no longer holds the delete back. 0 never does.
DD_DUPE_DELETE_ABANDONED_IMPORT_LOCK_MINUTES=(int, 30),
# Imports and reimports into one test run one at a time: a second one waits for the first to
# finish (a PostgreSQL advisory lock; see dojo/importers/import_lock.py). Turn off behind a
# connection pooler in transaction mode, where session locks do not hold.
DD_SERIALIZE_TEST_IMPORTS=(bool, True),
# How long an import or reimport waits for another one into the same test to finish before it
# gives up and fails with HTTP 409 Conflict (default 10 minutes). 0 fails at once instead of waiting.
# A synchronous request that waits still has to import afterwards within the web server's and
# proxy's request timeouts (30 minutes on the stock deployments), so keep it well below those.
DD_SERIALIZE_TEST_IMPORTS_WAIT_SECONDS=(int, 600),
# When enabled, superusers can edit a finding's 'mitigated date' and 'mitigated by'
# fields (e.g. backdate a mitigation) from both the UI and the API. Off by default
# because backdating a mitigation can distort SLA-compliance metrics. Changing this
# value requires a service restart to take effect.
DD_EDITABLE_MITIGATED_DATA=(bool, False),
# new feature that tracks history across multiple reimports for the same test
DD_TRACK_IMPORT_HISTORY=(bool, True),
# Batch size for reimport candidate matching (finding existing findings)
DD_IMPORT_REIMPORT_MATCH_BATCH_SIZE=(int, 1000),
# Batch size for import/reimport deduplication processing
DD_IMPORT_REIMPORT_DEDUPE_BATCH_SIZE=(int, 1000),
# Batch size for Redis pipeline when purging the Celery queue by task name
DD_CELERY_QUEUE_PURGE_BATCH_SIZE=(int, 1000),
# Maximum number of tasks to purge in a single per-task purge action
DD_CELERY_QUEUE_PURGE_MAX_TASKS=(int, 10000),
# Audit-log env-var schema (DD_ENABLE_AUDITLOG, DD_AUDITLOG_FLUSH_*) sourced
# from dojo/auditlog/settings.py.
**AUDITLOG_ENV_SCHEMA,
# Allow grouping of findings in the same test, for example to group findings per dependency
# DD_FEATURE_FINDING_GROUPS feature is moved to system_settings, will be removed from settings file
DD_FEATURE_FINDING_GROUPS=(bool, True),
DD_JIRA_TEMPLATE_ROOT=(str, "dojo/templates/issue-trackers"),
DD_TEMPLATE_DIR_PREFIX=(str, "dojo/templates/"),
DD_DUPLICATE_CLUSTER_CASCADE_DELETE=(bool, False),
# Enable Rate Limiting for the login page
DD_RATE_LIMITER_ENABLED=(bool, False),
# Account-recovery emails (password reset, forgot username) sent to one address per hour. 0 disables the limit.
DD_ACCOUNT_RECOVERY_EMAILS_PER_HOUR=(int, 5),
# Examples include 5/m 100/h and more https://django-ratelimit.readthedocs.io/en/stable/rates.html#simple-rates
DD_RATE_LIMITER_RATE=(str, "5/m"),
# Block the requests after rate limit is exceeded
DD_RATE_LIMITER_BLOCK=(bool, False),
# Forces the user to change password on next login.
DD_RATE_LIMITER_ACCOUNT_LOCKOUT=(bool, False),
# when enabled SonarQube API parser will download the security hotspots
DD_SONARQUBE_API_PARSER_HOTSPOTS=(bool, True),
# When enabled, deleting objects will be occur from the bottom up. In the example of deleting an engagement
# The objects will be deleted as follows Endpoints -> Findings -> Tests -> Engagement
DD_ASYNC_OBJECT_DELETE=(bool, False),
# The number of objects to be deleted per celeryworker
DD_ASYNC_OBEJECT_DELETE_CHUNK_SIZE=(int, 100),
# When enabled, display the preview of objects to be deleted. This can take a long time to render
# for very large objects
DD_DELETE_PREVIEW=(bool, True),
# List of acceptable file types that can be uploaded to a given object via arbitrary file upload
DD_FILE_UPLOAD_TYPES=(list, [".txt", ".pdf", ".json", ".xml", ".csv", ".yml", ".png", ".jpeg",
".sarif", ".xlsx", ".doc", ".html", ".js", ".nessus", ".zip", ".fpr"]),
# List of acceptable file types that can be (re)imported
DD_FILE_IMPORT_TYPES=(list, [".xml", ".csv", ".nessus", ".json", ".jsonl", ".html", ".js", ".zip",
".xlsx", ".txt", ".sarif", ".fpr", ".md", ".log", ".fvdl", ".spdx"]),
# Max file size for scan added via API in MB
DD_SCAN_FILE_MAX_SIZE=(int, 100),
# When disabled, existing user tokens will not be removed but it will not be
# possible to create new and it will not be possible to use exising.
DD_API_TOKENS_ENABLED=(bool, True),
# Enable endpoint which allow user to get API token when user+pass is provided
DD_API_TOKEN_AUTH_ENDPOINT_ENABLED=(bool, True),
# Default token lifetime in days. 0 = no expiry (tokens last forever).
DD_API_TOKEN_DEFAULT_EXPIRY_DAYS=(int, 0),
# You can set extra Jira headers by suppling a dictionary in header: value format (pass as env var like "headr_name=value,another_header=anohter_value")
DD_ADDITIONAL_HEADERS=(dict, {}),
# Set fields used by the hashcode generator for deduplication, via en env variable that contains a JSON string
DD_HASHCODE_FIELDS_PER_SCANNER=(str, ""),
# Set deduplication algorithms per parser, via en env variable that contains a JSON string
DD_DEDUPLICATION_ALGORITHM_PER_PARSER=(str, ""),
# When True, hash_code mass updates use the PostgreSQL VALUES-join fast writer
# (falls back to bulk_update on other backends). Set False to always use bulk_update.
DD_MASS_HASH_CODE_USE_SQL_WRITER=(bool, True),
# Specifies whether the "first seen" date of a given report should be used over the "last seen" date
DD_USE_FIRST_SEEN=(bool, False),
# When set to True, use the older version of the qualys parser that is a more heavy handed in setting severity
# with the use of CVSS scores to potentially override the severity found in the report produced by the tool
DD_QUALYS_LEGACY_SEVERITY_PARSING=(bool, True),
# When enabled, the Trufflehog Scan parser reports one finding per secret per file in a report, however
# many commits the secret appears in (the commit and the line leave the in-report fold key). Off by
# default: the parser then reports one finding per commit, as it always has, so existing findings keep
# their identity. Turn it on together with the "Unique ID from tool" deduplication algorithm for the
# scan type, which matches on the stable unique_id_from_tool the parser sets.
DD_TRUFFLEHOG_FOLD_COMMITS=(bool, False),
# When enabled, force the password field to be required for creating/updating users
DD_REQUIRE_PASSWORD_ON_USER=(bool, True),
# For HTTP requests, how long connection is open before timeout
# This settings apply only on requests performed by "requests" lib used in Dojo code (if some included lib is using "requests" as well, this does not apply there)
DD_REQUESTS_TIMEOUT=(int, 30),
# Dictates if v3 functionality will be enabled (on by default as of 3.0.0; set to False to revert to the legacy Endpoint model)
DD_V3_FEATURE_LOCATIONS=(bool, True),
# API v3 (alpha) list pagination: threshold below which `count` is exact; above it the
# response reports the Postgres planner's row estimate (flagged count_exact=false). See §4.3.
DD_API_V3_COUNT_CAP=(int, 10000),
# API v3 (alpha) ?expand= guard: maximum number of expanded relation nodes across all paths. See §4.6.
DD_API_V3_EXPAND_BUDGET=(int, 10),
# API v3 (alpha) CSV export row cap: the whole filtered set is streamed as CSV; if the filtered
# count exceeds this cap the request is a 400 telling the client to narrow the filter (never a
# silent truncation). See §4.15.
DD_API_V3_EXPORT_MAX_ROWS=(int, 100000),
# Dictates if v3 org/asset relabeling (+url routing) will be enabled (on by default as of 3.0.0; set to False to restore Product/Product Type labels and URLs)
DD_ENABLE_V3_ORGANIZATION_ASSET_RELABEL=(bool, True),
# Shared cache backend (django.core.cache). When set, Django uses RedisCache
# (e.g. redis://valkey:6379/1); when empty it falls back to LocMemCache. Used
# by general framework caching; the singleton settings cache (dojo/caching.py)
# is in-process only and does not read or write this backend.
DD_CACHE_URL=(str, ""),
# In-process (L1) read-through cache for global singleton getters (see
# dojo/caching.py). Per-thread freshness budget in seconds; -1 disables it.
# Reset every request/task, so each request/task reads the singleton once.
DD_SETTINGS_CACHE_L1_TTL=(int, 30),
# Notification env-vars (SLA notify, alert refresh/counter/cap, system-level trump). Defined in dojo.notifications.settings.
**NOTIFICATIONS_ENV_DEFAULTS,
)
def generate_url(scheme, double_slashes, user, password, host, port, path, params):
result_list = []
result_list.extend((scheme, ":"))
if double_slashes:
result_list.append("//")
result_list.append(user)
if len(password) > 0:
result_list.extend((":", password))
if len(user) > 0 or len(password) > 0:
result_list.append("@")
result_list.append(host)
if port >= 0:
result_list.extend((":", str(port)))
if len(path) > 0 and path[0] != "/":
result_list.append("/")
result_list.append(path)
if len(params) > 0 and params[0] != "?":
result_list.append("?")
result_list.append(params)
return "".join(result_list)
# Read .env file as default or from the command line, DD_ENV_PATH
if Path(root("dojo/settings/.env.prod")).is_file() or "DD_ENV_PATH" in os.environ:
env.read_env(root("dojo/settings/" + env.str("DD_ENV_PATH", ".env.prod")))
# ------------------------------------------------------------------------------
# GENERAL
# ------------------------------------------------------------------------------
# False if not in os.environ
DEBUG = env("DD_DEBUG")
DJANGO_DEBUG_TOOLBAR_ENABLED = env("DD_DJANGO_DEBUG_TOOLBAR_ENABLED")
TEMPLATE_DEBUG = env("DD_TEMPLATE_DEBUG")
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/2.0/ref/settings/#allowed-hosts
SITE_URL = env("DD_SITE_URL")
ALLOWED_HOSTS = tuple(env.list("DD_ALLOWED_HOSTS", default=["localhost", "127.0.0.1"]))
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env("DD_SECRET_KEY")
SECRET_KEY_FALLBACKS = env("DD_SECRET_KEY_FALLBACKS")
# Default cache backend (django.core.cache). Redis when DD_CACHE_URL is set,
# else per-process LocMemCache. General framework caching only; the singleton
# settings cache (dojo/caching.py) is in-process and does not use this backend.
if env("DD_CACHE_URL"):
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": env("DD_CACHE_URL"),
},
}
# In-process singleton cache (dojo/caching.py)
SETTINGS_CACHE_L1_TTL = env("DD_SETTINGS_CACHE_L1_TTL")
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = env("DD_TIME_ZONE")
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = env("DD_LANGUAGE_CODE")
SITE_ID = env("DD_SITE_ID")
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = env("DD_USE_I18N")
# Languages offered in the UI. Stored DB values and serialized API values always
# remain English regardless of the selected language; only displayed text changes.
LANGUAGES = [
("en", "English"),
("ar", "العربية"),
("bn", "বাংলা"),
("de", "Deutsch"),
("es", "Español"),
("fa", "فارسی"),
("fr", "Français"),
("he", "עברית"),
("hi", "हिन्दी"),
("id", "Bahasa Indonesia"),
("it", "Italiano"),
("ja", "日本語"),
("ko", "한국어"),
("mr", "मराठी"),
("nl", "Nederlands"),
("pl", "Polski"),
("pt-br", "Português (Brasil)"),
("ru", "Русский"),
("ta", "தமிழ்"),
("te", "తెలుగు"),
("th", "ไทย"),
("tl", "Filipino"),
("tr", "Türkçe"),
("uk", "Українська"),
("ur", "اردو"),
("vi", "Tiếng Việt"),
("zh-hans", "简体中文"),
("zh-hant", "繁體中文"),
]
# Arabic (ar), Hebrew (he), Persian (fa) and Urdu (ur) are right-to-left; the v3 UI flips
# layout via dir="rtl" (set in base.html from LANGUAGE_BIDI) plus logical CSS utilities.
# The classic UI is not RTL-aware.
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = env("DD_USE_TZ")
TEST_RUNNER = env("DD_TEST_RUNNER")
_populate_notifications_settings(env, globals())
TAG_PREFETCHING = env("DD_TAG_PREFETCHING")
# Tag bulk add batch size (used by dojo.tags.utils.bulk_add_tag_to_instances)
TAG_BULK_ADD_BATCH_SIZE = env("DD_TAG_BULK_ADD_BATCH_SIZE")
# ------------------------------------------------------------------------------
# DATABASE
# ------------------------------------------------------------------------------
# Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db
if os.getenv("DD_DATABASE_URL") is not None:
DATABASES = {
"default": env.db("DD_DATABASE_URL"),
}
else:
DATABASES = {
"default": {
"ENGINE": env("DD_DATABASE_ENGINE"),
"NAME": env("DD_DATABASE_NAME"),
"TEST": {
"NAME": env("DD_TEST_DATABASE_NAME"),
},
"USER": env("DD_DATABASE_USER"),
"PASSWORD": env("DD_DATABASE_PASSWORD"),
"HOST": env("DD_DATABASE_HOST"),
"PORT": env("DD_DATABASE_PORT"),
},
}
# Track migrations through source control rather than making migrations locally
if env("DD_TRACK_MIGRATIONS"):
MIGRATION_MODULES = {"dojo": "dojo.db_migrations"}
# Default for automatically created id fields,
# see https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
# ------------------------------------------------------------------------------
# MEDIA
# ------------------------------------------------------------------------------
DOJO_ROOT = env("DD_ROOT")
# Where Django looks for translation catalogs: dojo/locale/<lang>/LC_MESSAGES/.
LOCALE_PATHS = [Path(DOJO_ROOT) / "locale"]
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = env("DD_MEDIA_ROOT")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = env("DD_MEDIA_URL")
# ------------------------------------------------------------------------------
# STATIC
# ------------------------------------------------------------------------------
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = env("DD_STATIC_ROOT")
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = env("DD_STATIC_URL")
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
Path(DOJO_ROOT).parent / "components" / "node_modules",
)
# 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",
)
FILE_UPLOAD_HANDLERS = (
"django.core.files.uploadhandler.TemporaryFileUploadHandler",
)
DATA_UPLOAD_MAX_MEMORY_SIZE = env("DD_DATA_UPLOAD_MAX_MEMORY_SIZE")
MAX_ZIP_MEMBERS = env("DD_MAX_ZIP_MEMBERS")
MAX_ZIP_MEMBER_SIZE = env("DD_MAX_ZIP_MEMBER_SIZE")
MAX_ZIP_TOTAL_SIZE = env("DD_MAX_ZIP_TOTAL_SIZE")
MAX_ZIP_RATIO = env("DD_MAX_ZIP_RATIO")
# ------------------------------------------------------------------------------
# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
# AUTHENTICATION_BACKENDS = [
# 'axes.backends.AxesModelBackend',
# ]
ROOT_URLCONF = "dojo.urls"
# Python dotted path to the WSGI application used by Django's runserver.
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "dojo.wsgi.application"
URL_PREFIX = env("DD_URL_PREFIX")
# ------------------------------------------------------------------------------
# AUTHENTICATION
# ------------------------------------------------------------------------------
LOGIN_REDIRECT_URL = env("DD_LOGIN_REDIRECT_URL")
LOGIN_URL = env("DD_LOGIN_URL")
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
)
# Make Argon2 the default password hasher by listing it first
# Unfortunately Django doesn't provide the default built-in
# PASSWORD_HASHERS list here as a variable which we could modify,
# so we have to list all the hashers present in Django :-(
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
"django.contrib.auth.hashers.BCryptPasswordHasher",
"django.contrib.auth.hashers.MD5PasswordHasher",
]
CLASSIC_AUTH_ENABLED = True
FORGOT_PASSWORD = env("DD_FORGOT_PASSWORD")
REQUIRE_PASSWORD_ON_USER = env("DD_REQUIRE_PASSWORD_ON_USER")
FORGOT_USERNAME = env("DD_FORGOT_USERNAME")
PASSWORD_RESET_TIMEOUT = env("DD_PASSWORD_RESET_TIMEOUT")
OS_MESSAGE_ENABLED = env("DD_OS_MESSAGE_ENABLED")
GITHUB_STAR_PROMPT_ENABLED = env("DD_GITHUB_STAR_PROMPT_ENABLED")
DOCUMENTATION_URL = env("DD_DOCUMENTATION_URL")
# Setting SLA_NOTIFY_ACTIVE and SLA_NOTIFY_ACTIVE_VERIFIED to False will disable the feature
# If you import thousands of Active findings through your pipeline everyday,
# and make the choice of enabling SLA notifications for non-verified findings,
# be mindful of performance.
# SLA_NOTIFY_* are populated by dojo.notifications.settings.populate_settings (see ALERT_REFRESH section above).
SEARCH_MAX_RESULTS = env("DD_SEARCH_MAX_RESULTS")
SIMILAR_FINDINGS_MAX_RESULTS = env("DD_SIMILAR_FINDINGS_MAX_RESULTS")
MAX_REQRESP_FROM_API = env("DD_MAX_REQRESP_FROM_API")
MAX_AUTOCOMPLETE_WORDS = env("DD_MAX_AUTOCOMPLETE_WORDS")
ENABLE_AUDITLOG = env("DD_ENABLE_AUDITLOG")
LOGIN_EXEMPT_URLS = (
rf"^{URL_PREFIX}static/",
rf"^{URL_PREFIX}webhook/([\w-]+)$",
rf"^{URL_PREFIX}webhook/",
rf"^{URL_PREFIX}jira/webhook/([\w-]+)$",
rf"^{URL_PREFIX}jira/webhook/",
rf"^{URL_PREFIX}finding/image/(?P<token>[^/]+)$",
rf"^{URL_PREFIX}api/v2/",
r"complete/",
r"empty_questionnaire/([\d]+)/answer",
r"oauth2/idpresponse",
rf"^{URL_PREFIX}password_reset/",
rf"^{URL_PREFIX}forgot_username",
rf"^{URL_PREFIX}reset/",
)
# Unsafe requests that still pass while read-only mode is on: sign-in and System Settings,
# so a superuser can always turn the mode off again.
READ_ONLY_MODE_EXEMPT_URLS = (
rf"^{URL_PREFIX}login$",
rf"^{URL_PREFIX}logout$",
r"complete/",
r"oauth2/idpresponse",
rf"^{URL_PREFIX}password_reset/",
rf"^{URL_PREFIX}reset/",
rf"^{URL_PREFIX}forgot_username",
rf"^{URL_PREFIX}change_password$",
rf"^{URL_PREFIX}api/v2/api-token-auth/",
rf"^{URL_PREFIX}system_settings$",
rf"^{URL_PREFIX}api/v2/system_settings/",
)
# Inbound webhooks blocked by read-only mode get a 503 with Retry-After instead of a redirect.
# A sender reads a redirect as delivered and drops the event, but it retries a 503.
READ_ONLY_MODE_RETRY_URLS = (
rf"^{URL_PREFIX}webhook/",
rf"^{URL_PREFIX}jira/webhook/",
)
READ_ONLY_MODE_RETRY_AFTER_SECONDS = 300
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "dojo.user.validators.DojoCommonPasswordValidator",
},
{
"NAME": "dojo.user.validators.MinLengthValidator",
},
{
"NAME": "dojo.user.validators.MaxLengthValidator",
},
{
"NAME": "dojo.user.validators.NumberValidator",
},
{
"NAME": "dojo.user.validators.UppercaseValidator",
},
{
"NAME": "dojo.user.validators.LowercaseValidator",
},
{
"NAME": "dojo.user.validators.SymbolValidator",
},
]
# https://django-ratelimit.readthedocs.io/en/stable/index.html
RATE_LIMITER_ENABLED = env("DD_RATE_LIMITER_ENABLED")
ACCOUNT_RECOVERY_EMAILS_PER_HOUR = env("DD_ACCOUNT_RECOVERY_EMAILS_PER_HOUR")
RATE_LIMITER_RATE = env("DD_RATE_LIMITER_RATE") # Examples include 5/m 100/h and more https://django-ratelimit.readthedocs.io/en/stable/rates.html#simple-rates
RATE_LIMITER_BLOCK = env("DD_RATE_LIMITER_BLOCK") # Block the requests after rate limit is exceeded
RATE_LIMITER_ACCOUNT_LOCKOUT = env("DD_RATE_LIMITER_ACCOUNT_LOCKOUT") # Forces the user to change password on next login.
# ------------------------------------------------------------------------------
# SECURITY DIRECTIVES
# ------------------------------------------------------------------------------
# If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS
# (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT).
SECURE_SSL_REDIRECT = env("DD_SECURE_SSL_REDIRECT")
# If True, the SecurityMiddleware sets the X-Content-Type-Options: nosniff;
SECURE_CONTENT_TYPE_NOSNIFF = env("DD_SECURE_CONTENT_TYPE_NOSNIFF")
# Whether to use HTTPOnly flag on the session cookie.
# If this is set to True, client-side JavaScript will not to be able to access the session cookie.
SESSION_COOKIE_HTTPONLY = env("DD_SESSION_COOKIE_HTTPONLY")
# Whether to use HttpOnly flag on the CSRF cookie. If this is set to True,
# client-side JavaScript will not to be able to access the CSRF cookie.
CSRF_COOKIE_HTTPONLY = env("DD_CSRF_COOKIE_HTTPONLY")
# Whether to use a secure cookie for the session cookie. If this is set to True,
# the cookie will be marked as secure, which means browsers may ensure that the
# cookie is only sent with an HTTPS connection.
SESSION_COOKIE_SECURE = env("DD_SESSION_COOKIE_SECURE")
SESSION_COOKIE_SAMESITE = env("DD_SESSION_COOKIE_SAMESITE")
# Override default Django behavior for incorrect URLs
APPEND_SLASH = env("DD_APPEND_SLASH")
# Whether to use a secure cookie for the CSRF cookie.
CSRF_COOKIE_SECURE = env("DD_CSRF_COOKIE_SECURE")
CSRF_COOKIE_SAMESITE = env("DD_CSRF_COOKIE_SAMESITE")
# A list of trusted origins for unsafe requests (e.g. POST).
# Use comma-separated list of domains, they will be split to list automatically
# Only specify this settings if the contents is not an empty list (the default)
if env("DD_CSRF_TRUSTED_ORIGINS") != ["[]"]:
CSRF_TRUSTED_ORIGINS = env("DD_CSRF_TRUSTED_ORIGINS")
# Unless set to None, the SecurityMiddleware sets the Cross-Origin Opener Policy
# header on all responses that do not already have it to the value provided.
SECURE_CROSS_ORIGIN_OPENER_POLICY = env("DD_SECURE_CROSS_ORIGIN_OPENER_POLICY") if env("DD_SECURE_CROSS_ORIGIN_OPENER_POLICY") != "None" else None
if env("DD_SECURE_PROXY_SSL_HEADER"):
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
if env("DD_SECURE_HSTS_INCLUDE_SUBDOMAINS"):
SECURE_HSTS_SECONDS = env("DD_SECURE_HSTS_SECONDS")
SECURE_HSTS_INCLUDE_SUBDOMAINS = env("DD_SECURE_HSTS_INCLUDE_SUBDOMAINS")
SESSION_EXPIRE_AT_BROWSER_CLOSE = env("DD_SESSION_EXPIRE_AT_BROWSER_CLOSE")
SESSION_EXPIRE_WARNING = env("DD_SESSION_EXPIRE_WARNING")
SESSION_COOKIE_AGE = env("DD_SESSION_COOKIE_AGE")
# Permission-Policy header settings
# See docs at https://pypi.org/project/django-permissions-policy/
PERMISSIONS_POLICY = {
"accelerometer": [],
"ambient-light-sensor": [],
"autoplay": [],
"camera": [],
"display-capture": [],
"encrypted-media": [],
"fullscreen": [],
"geolocation": [],
"gyroscope": [],
"interest-cohort": [],
"magnetometer": [],
"microphone": [],
"midi": [],
"payment": [],
"usb": [],
}
# ------------------------------------------------------------------------------
# DEFECTDOJO SPECIFIC
# ------------------------------------------------------------------------------
ENABLE_V3_ORGANIZATION_ASSET_RELABEL = env("DD_ENABLE_V3_ORGANIZATION_ASSET_RELABEL")
# Credential Key
CREDENTIAL_AES_256_KEY = env("DD_CREDENTIAL_AES_256_KEY")
DB_KEY = env("DD_CREDENTIAL_AES_256_KEY")
# Used in a few places to prefix page headings and in email salutations
TEAM_NAME = env("DD_TEAM_NAME")
# Used to configure a custom version in the footer of the base.html template.
FOOTER_VERSION = env("DD_FOOTER_VERSION")
# Toggle for the highly accessible notice at the top of forms ("Required fields are marked with an asterisk*")
SHOW_A11Y_REQUIRED_FIELDS_NOTICE = env("DD_SHOW_A11Y_REQUIRED_FIELDS_NOTICE")
# V3 Feature Flags
V3_FEATURE_LOCATIONS = env("DD_V3_FEATURE_LOCATIONS")
# ------------------------------------------------------------------------------
# API v3 (alpha)
# ------------------------------------------------------------------------------
# The API is mounted at /api/v3/ and stays there through beta and GA (no URL migration). It is an
# alpha: the contract may change at any time. Alpha status is signaled by the OpenAPI version
# (API_V3_VERSION), the X-API-Status header, and the docs banner -- not by the URL (D1/§4.1). This
# is the single source of truth for the prefix and version string -- do not hardcode them anywhere.
API_V3_URL_PREFIX = "api/v3"
API_V3_VERSION = "3.0.0-alpha"
API_V3_STATUS = "alpha"
# Count/expand tuning (§4.3, §4.6); settings-overridable per the plan.
API_V3_COUNT_CAP = env("DD_API_V3_COUNT_CAP")
API_V3_EXPAND_BUDGET = env("DD_API_V3_EXPAND_BUDGET")
# CSV export row cap (§4.15); settings-overridable per the plan.
API_V3_EXPORT_MAX_ROWS = env("DD_API_V3_EXPORT_MAX_ROWS")
# List pagination bounds (§4.3).
API_V3_PAGE_LIMIT_DEFAULT = 25
API_V3_PAGE_LIMIT_MAX = 250
# v3 handles its own auth (token + session); exempt it from the UI login-redirect middleware
# exactly as /api/v2/ is (so anonymous requests get a 401 problem+json, not a /login redirect).
LOGIN_EXEMPT_URLS += (rf"^{URL_PREFIX}{API_V3_URL_PREFIX}/",)
# ------------------------------------------------------------------------------
# ADMIN
# ------------------------------------------------------------------------------
ADMINS = getaddresses([env("DD_ADMINS")])
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# Django admin enabled
DJANGO_ADMIN_ENABLED = env("DD_DJANGO_ADMIN_ENABLED")
# ------------------------------------------------------------------------------
# API V2
# ------------------------------------------------------------------------------
API_TOKENS_ENABLED = env("DD_API_TOKENS_ENABLED")
API_TOKEN_AUTH_ENDPOINT_ENABLED = env("DD_API_TOKEN_AUTH_ENDPOINT_ENABLED")
API_TOKEN_DEFAULT_EXPIRY_DAYS = env("DD_API_TOKEN_DEFAULT_EXPIRY_DAYS")
REST_FRAMEWORK = {
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework.authentication.SessionAuthentication",
"dojo.user.authentication.DojoBasicAuthentication",
),
"DEFAULT_PERMISSION_CLASSES": (
"rest_framework.permissions.DjangoModelPermissions",
),
"DEFAULT_RENDERER_CLASSES": (
"rest_framework.renderers.JSONRenderer",
),
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 25,
"EXCEPTION_HANDLER": "dojo.api_v2.exception_handler.custom_exception_handler",
}
if API_TOKENS_ENABLED:
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] += ("dojo.user.authentication.ExpiringTokenAuthentication",)
SPECTACULAR_SETTINGS = {
"TITLE": "DefectDojo API v2",
"DESCRIPTION": "DefectDojo - Open Source vulnerability Management made easy. Prefetch related parameters/responses not yet in the schema.",
"VERSION": __version__,
"SCHEMA_PATH_PREFIX": "/api/v2",
# OTHER SETTINGS
# the following set to False could help some client generators
# 'ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE': False,
"PREPROCESSING_HOOKS": ["dojo.urls.drf_spectacular_preprocessing_filter_spec"],
"POSTPROCESSING_HOOKS": ["dojo.api_v2.prefetch.schema.prefetch_postprocessing_hook"],
# show file selection dialogue, see https://github.com/tfranzel/drf-spectacular/issues/455
"COMPONENT_SPLIT_REQUEST": True,
"SWAGGER_UI_SETTINGS": {
"docExpansion": "none",
},
}
if not env("DD_DEFAULT_SWAGGER_UI"):
SPECTACULAR_SETTINGS["SWAGGER_UI_DIST"] = "SIDECAR"
SPECTACULAR_SETTINGS["SWAGGER_UI_FAVICON_HREF"] = "SIDECAR"
# ------------------------------------------------------------------------------
# TEMPLATES
# ------------------------------------------------------------------------------
# The UI lives in a single tree at dojo/templates/, searched ahead of the
# sub-package template dirs (dojo/auditlog, dojo/notifications, dojo/github).
# The list is shared by reference with the FilesystemLoader entry below, so any
# late-binding settings can append a template dir at startup and have it
# picked up at render time.
_DOJO_TEMPLATE_DIRS = [
root("dojo/templates"),
root("dojo/auditlog/templates"),
root("dojo/notifications/templates"),
root("dojo/github/templates"),
]
# Mirrors what APP_DIRS=True would build, except that the filesystem dirs above
# are searched first and the whole chain is wrapped in the cached loader outside
# of debug mode.
_DOJO_TEMPLATE_LOADERS = [
("django.template.loaders.filesystem.Loader", _DOJO_TEMPLATE_DIRS),
"django.template.loaders.app_directories.Loader",
]
if not env("DD_DEBUG"):
_DOJO_TEMPLATE_LOADERS = [
("django.template.loaders.cached.Loader", _DOJO_TEMPLATE_LOADERS),
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
# DIRS shares the _DOJO_TEMPLATE_DIRS list reference with the
# FilesystemLoader entry below; later append()s land in both places.
"DIRS": _DOJO_TEMPLATE_DIRS,
# APP_DIRS must stay False whenever "loaders" is set explicitly; the
# app_directories.Loader entry below covers the same ground.
"APP_DIRS": False,
"OPTIONS": {
"debug": env("DD_DEBUG"),
"loaders": _DOJO_TEMPLATE_LOADERS,
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"dojo.context_processors.globalize_vars",
"dojo.context_processors.bind_system_settings",
"dojo.notifications.context_processors.bind_alert_count",
"dojo.context_processors.bind_announcement",
"dojo.notifications.context_processors.session_expiry_notification",
"dojo.context_processors.labels",
],
},
},
]
# ------------------------------------------------------------------------------
# APPS
# ------------------------------------------------------------------------------
INSTALLED_APPS = (
"django.contrib.auth",
"django.contrib.contenttypes",
# Registers the postgres-specific lookups and index expressions
# (trigram word similarity, tsvector search) used by global search.
"django.contrib.postgres",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
"polymorphic", # provides admin templates
"django.contrib.admin",
"django.contrib.humanize",
"dojo",
"watson",
"imagekit",
"multiselectfield",
"rest_framework",
"rest_framework.authtoken",
"dbbackup",
"django_celery_results",
"drf_spectacular",
"drf_spectacular_sidecar", # required for Django collectstatic discovery
"django_tagulous", # app_label stays "tagulous" (DB tables/static paths unaffected)
"fontawesomefree",
"django_filters",
"auditlog",
"pgtrigger",
"pghistory",
"single_session",
"django_htmx",
)
# ------------------------------------------------------------------------------
# MIDDLEWARE
# ------------------------------------------------------------------------------
DJANGO_MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"dojo.middleware.APITrailingSlashMiddleware",
"dojo.middleware.DojoSettingsManagerMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.middleware.security.SecurityMiddleware",
"django_permissions_policy.PermissionsPolicyMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"dojo.middleware.LanguagePreferenceMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django_htmx.middleware.HtmxMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"dojo.middleware.LoginRequiredMiddleware",
"dojo.middleware.ReadOnlyModeMiddleware",
"dojo.middleware.AdditionalHeaderMiddleware",
"crum.CurrentRequestUserMiddleware",
"dojo.authorization.middleware.AuthorizationMiddleware",
"dojo.middleware.AsyncSearchContextMiddleware",