forked from DefectDojo/django-DefectDojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.py
3358 lines (2959 loc) · 137 KB
/
filters.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 collections
import decimal
import logging
import warnings
from datetime import datetime, timedelta
import pytz
import six
import tagulous
from auditlog.models import LogEntry
from django import forms
from django.apps import apps
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import JSONField, Q
from django.forms import HiddenInput
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django_filters import (
BooleanFilter,
CharFilter,
DateFilter,
DateFromToRangeFilter,
FilterSet,
ModelChoiceFilter,
ModelMultipleChoiceFilter,
MultipleChoiceFilter,
NumberFilter,
OrderingFilter,
RangeFilter,
)
from django_filters import rest_framework as filters
from django_filters.filters import ChoiceFilter, _truncate
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from polymorphic.base import ManagerInheritanceWarning
# from tagulous.forms import TagWidget
# import tagulous
from dojo.authorization.roles_permissions import Permissions
from dojo.endpoint.queries import get_authorized_endpoints
from dojo.engagement.queries import get_authorized_engagements
from dojo.finding.helper import (
ACCEPTED_FINDINGS_QUERY,
CLOSED_FINDINGS_QUERY,
FALSE_POSITIVE_FINDINGS_QUERY,
INACTIVE_FINDINGS_QUERY,
NOT_ACCEPTED_FINDINGS_QUERY,
OPEN_FINDINGS_QUERY,
OUT_OF_SCOPE_FINDINGS_QUERY,
UNDER_REVIEW_QUERY,
VERIFIED_FINDINGS_QUERY,
WAS_ACCEPTED_FINDINGS_QUERY,
)
from dojo.finding.queries import get_authorized_findings
from dojo.finding_group.queries import get_authorized_finding_groups
from dojo.models import (
EFFORT_FOR_FIXING_CHOICES,
ENGAGEMENT_STATUS_CHOICES,
IMPORT_ACTIONS,
SEVERITY_CHOICES,
App_Analysis,
ChoiceQuestion,
Cred_Mapping,
Development_Environment,
Dojo_Group,
Dojo_User,
Endpoint,
Endpoint_Status,
Engagement,
Engagement_Survey,
Finding,
Finding_Group,
Finding_Template,
Note_Type,
Product,
Product_API_Scan_Configuration,
Product_Type,
Question,
Risk_Acceptance,
Test,
Test_Import,
Test_Import_Finding_Action,
Test_Type,
TextQuestion,
Vulnerability_Id,
)
from dojo.product.queries import get_authorized_products
from dojo.product_type.queries import get_authorized_product_types
from dojo.risk_acceptance.queries import get_authorized_risk_acceptances
from dojo.test.queries import get_authorized_tests
from dojo.user.queries import get_authorized_users
from dojo.utils import get_system_setting, is_finding_groups_enabled
logger = logging.getLogger(__name__)
local_tz = pytz.timezone(get_system_setting('time_zone'))
BOOLEAN_CHOICES = (('false', 'No'), ('true', 'Yes'),)
EARLIEST_FINDING = None
def custom_filter(queryset, name, value):
values = value.split(',')
filter = (f'{name}__in')
return queryset.filter(Q(**{filter: values}))
def custom_vulnerability_id_filter(queryset, name, value):
values = value.split(',')
ids = Vulnerability_Id.objects \
.filter(vulnerability_id__in=values) \
.values_list('finding_id', flat=True)
return queryset.filter(id__in=ids)
def vulnerability_id_filter(queryset, name, value):
ids = Vulnerability_Id.objects \
.filter(vulnerability_id=value) \
.values_list('finding_id', flat=True)
return queryset.filter(id__in=ids)
def now():
return local_tz.localize(datetime.today())
class NumberInFilter(filters.BaseInFilter, filters.NumberFilter):
pass
class CharFieldInFilter(filters.BaseInFilter, filters.CharFilter):
def __init__(self, *args, **kwargs):
super(CharFilter, self).__init__(*args, **kwargs)
class FindingStatusFilter(ChoiceFilter):
def any(self, qs, name):
return qs
def open(self, qs, name):
return qs.filter(OPEN_FINDINGS_QUERY)
def verified(self, qs, name):
return qs.filter(VERIFIED_FINDINGS_QUERY)
def out_of_scope(self, qs, name):
return qs.filter(OUT_OF_SCOPE_FINDINGS_QUERY)
def false_positive(self, qs, name):
return qs.filter(FALSE_POSITIVE_FINDINGS_QUERY)
def inactive(self, qs, name):
return qs.filter(INACTIVE_FINDINGS_QUERY)
def risk_accepted(self, qs, name):
return qs.filter(ACCEPTED_FINDINGS_QUERY)
def closed(self, qs, name):
return qs.filter(CLOSED_FINDINGS_QUERY)
def under_review(self, qs, name):
return qs.filter(UNDER_REVIEW_QUERY)
options = {
None: (_('Any'), any),
0: (_('Open'), open),
1: (_('Verified'), verified),
2: (_('Out Of Scope'), out_of_scope),
3: (_('False Positive'), false_positive),
4: (_('Inactive'), inactive),
5: (_('Risk Accepted'), risk_accepted),
6: (_('Closed'), closed),
7: (_('Under Review'), under_review),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
earliest_finding = get_earliest_finding(qs)
if earliest_finding is not None:
start_date = local_tz.localize(datetime.combine(
earliest_finding.date, datetime.min.time())
)
self.start_date = _truncate(start_date - timedelta(days=1))
self.end_date = _truncate(now() + timedelta(days=1))
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](self, qs, self.field_name)
class FindingSLAFilter(ChoiceFilter):
def any(self, qs, name):
return qs
def sla_satisfied(self, qs, name):
# return findings that have an sla expiration date after today or no sla expiration date
return qs.filter(Q(sla_expiration_date__isnull=True) | Q(sla_expiration_date__gt=timezone.now().date()))
def sla_violated(self, qs, name):
# return active findings that have an sla expiration date before today
return qs.filter(
Q(
active=True,
false_p=False,
duplicate=False,
out_of_scope=False,
risk_accepted=False,
is_mitigated=False,
mitigated=None,
) & Q(sla_expiration_date__lt=timezone.now().date())
)
options = {
None: (_('Any'), any),
0: (_('False'), sla_satisfied),
1: (_('True'), sla_violated),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](self, qs, self.field_name)
class ProductSLAFilter(ChoiceFilter):
def any(self, qs, name):
return qs
def sla_satisifed(self, qs, name):
for product in qs:
if product.violates_sla():
qs = qs.exclude(id=product.id)
return qs
def sla_violated(self, qs, name):
for product in qs:
if not product.violates_sla():
qs = qs.exclude(id=product.id)
return qs
options = {
None: (_('Any'), any),
0: (_('False'), sla_satisifed),
1: (_('True'), sla_violated),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](self, qs, self.field_name)
def get_earliest_finding(queryset=None):
if queryset is None: # don't to 'if not queryset' which will trigger the query
queryset = Finding.objects.all()
try:
EARLIEST_FINDING = queryset.earliest('date')
except (Finding.DoesNotExist, Endpoint_Status.DoesNotExist):
EARLIEST_FINDING = None
return EARLIEST_FINDING
def cwe_options(queryset):
cwe = {}
cwe = dict([cwe, cwe]
for cwe in queryset.order_by().values_list('cwe', flat=True).distinct()
if isinstance(cwe, int) and cwe is not None and cwe > 0)
cwe = collections.OrderedDict(sorted(cwe.items()))
return list(cwe.items())
class DojoFilter(FilterSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in ['tags', 'test__tags', 'test__engagement__tags', 'test__engagement__product__tags',
'not_tags', 'not_test__tags', 'not_test__engagement__tags', 'not_test__engagement__product__tags']:
if field in self.form.fields:
tags_filter = self.filters['tags']
model = tags_filter.model
self.form.fields[field] = model._meta.get_field("tags").formfield()
# we defer applying the select2 autocomplete because there can be multiple forms on the same page
# and form.js would then apply select2 multiple times, resulting in duplicated fields
# the initialization now happens in filter_js_snippet.html
self.form.fields[field].widget.tag_options = \
self.form.fields[field].widget.tag_options + tagulous.models.options.TagOptions(autocomplete_settings={'width': '200px', 'defer': True})
tagged_model, exclude = get_tags_model_from_field_name(field)
if tagged_model: # only if not the normal tags field
self.form.fields[field].label = get_tags_label_from_model(tagged_model)
self.form.fields[field].autocomplete_tags = tagged_model.tags.tag_model.objects.all().order_by('name')
if exclude:
self.form.fields[field].label = 'Not ' + self.form.fields[field].label
def get_tags_model_from_field_name(field):
exclude = False
if field.startswith('not_'):
field = field.replace('not_', '')
exclude = True
try:
parts = field.split('__')
model_name = parts[-2]
return apps.get_model(f'dojo.{model_name}', require_ready=True), exclude
except Exception:
return None, exclude
def get_tags_label_from_model(model):
if model:
return f'Tags ({model.__name__.title()})'
else:
return 'Tags (Unknown)'
def get_finding_filterset_fields(metrics=False, similar=False, filter_string_matching=False):
fields = []
if similar:
fields.extend([
'id',
'hash_code'
])
fields.extend(['title', 'component_name', 'component_version'])
if metrics:
fields.extend([
'start_date',
'end_date',
])
fields.extend([
'date',
'cwe',
'severity',
'last_reviewed',
'last_status_update',
'mitigated',
'reporter',
'reviewers',
])
if filter_string_matching:
fields.extend([
'reporter',
'reviewers',
'test__engagement__product__prod_type__name',
'test__engagement__product__name',
'test__engagement__name',
'test__title',
])
else:
fields.extend([
'reporter',
'reviewers',
'test__engagement__product__prod_type',
'test__engagement__product',
'test__engagement',
'test',
])
fields.extend([
'test__test_type',
'test__engagement__version',
'test__version',
'endpoints',
'status',
'active',
'verified',
'duplicate',
'is_mitigated',
'out_of_scope',
'false_p',
'has_component',
'has_notes',
'file_path',
'unique_id_from_tool',
'vuln_id_from_tool',
'service',
'epss_score',
'epss_score_range',
'epss_percentile',
'epss_percentile_range',
])
if similar:
fields.extend([
'id',
])
fields.extend([
'param',
'payload',
'risk_acceptance',
])
if get_system_setting('enable_jira'):
fields.extend([
'has_jira_issue',
'jira_creation',
'jira_change',
'jira_issue__jira_key',
])
if is_finding_groups_enabled():
if filter_string_matching:
fields.extend([
'has_finding_group',
'finding_group__name',
])
else:
fields.extend([
'has_finding_group',
'finding_group',
])
if get_system_setting('enable_jira'):
fields.extend([
'has_jira_group_issue',
])
return fields
class FindingTagFilter(DojoFilter):
tag = CharFilter(
field_name="tags__name",
lookup_expr="icontains",
label="Tag name contains",
help_text="Search for tags on a Finding that contain a given pattern")
tags = ModelMultipleChoiceFilter(
field_name="tags__name",
to_field_name="name",
queryset=Finding.tags.tag_model.objects.all().order_by("name"),
help_text="Filter Findings by the selected tags")
test__tags = ModelMultipleChoiceFilter(
field_name="test__tags__name",
to_field_name="name",
queryset=Test.tags.tag_model.objects.all().order_by("name"),
help_text="Filter Tests by the selected tags")
test__engagement__tags = ModelMultipleChoiceFilter(
field_name="test__engagement__tags__name",
to_field_name="name",
queryset=Engagement.tags.tag_model.objects.all().order_by("name"),
help_text="Filter Engagements by the selected tags")
test__engagement__product__tags = ModelMultipleChoiceFilter(
field_name="test__engagement__product__tags__name",
to_field_name="name",
queryset=Product.tags.tag_model.objects.all().order_by("name"),
help_text="Filter Products by the selected tags")
not_tags = ModelMultipleChoiceFilter(
field_name="tags__name",
to_field_name="name",
queryset=Finding.tags.tag_model.objects.all().order_by("name"),
help_text="Search for tags on a Finding that contain a given pattern, and exclude them",
exclude=True)
not_test__tags = ModelMultipleChoiceFilter(
field_name="test__tags__name",
to_field_name="name",
label="Test without tags",
queryset=Test.tags.tag_model.objects.all().order_by("name"),
help_text="Search for tags on a Test that contain a given pattern, and exclude them",
exclude=True)
not_test__engagement__tags = ModelMultipleChoiceFilter(
field_name="test__engagement__tags__name",
to_field_name="name",
label="Engagement without tags",
queryset=Engagement.tags.tag_model.objects.all().order_by("name"),
help_text="Search for tags on a Engagement that contain a given pattern, and exclude them",
exclude=True)
not_test__engagement__product__tags = ModelMultipleChoiceFilter(
field_name="test__engagement__product__tags__name",
to_field_name="name",
label="Product without tags",
queryset=Product.tags.tag_model.objects.all().order_by("name"),
help_text="Search for tags on a Product that contain a given pattern, and exclude them",
exclude=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class FindingTagStringFilter(FilterSet):
tags_contains = CharFilter(
label="Finding Tag Contains",
field_name="tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Finding that contain a given pattern")
tags = CharFilter(
label="Finding Tag",
field_name="tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Finding that are an exact match")
test__tags_contains = CharFilter(
label="Test Tag Contains",
field_name="test__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Finding that contain a given pattern")
test__tags = CharFilter(
label="Test Tag",
field_name="test__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Finding that are an exact match")
test__engagement__tags_contains = CharFilter(
label="Engagement Tag Contains",
field_name="test__engagement__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Finding that contain a given pattern")
test__engagement__tags = CharFilter(
label="Engagement Tag",
field_name="test__engagement__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Finding that are an exact match")
test__engagement__product__tags_contains = CharFilter(
label="Product Tag Contains",
field_name="test__engagement__product__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Finding that contain a given pattern")
test__engagement__product__tags = CharFilter(
label="Product Tag",
field_name="test__engagement__product__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Finding that are an exact match")
not_tags_contains = CharFilter(
label="Finding Tag Does Not Contain",
field_name="tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Finding that contain a given pattern, and exclude them",
exclude=True)
not_tags = CharFilter(
label="Not Finding Tag",
field_name="tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Finding that are an exact match, and exclude them",
exclude=True)
not_test__tags_contains = CharFilter(
label="Test Tag Does Not Contain",
field_name="test__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Test that contain a given pattern, and exclude them",
exclude=True)
not_test__tags = CharFilter(
label="Not Test Tag",
field_name="test__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Test that are an exact match, and exclude them",
exclude=True)
not_test__engagement__tags_contains = CharFilter(
label="Engagement Tag Does Not Contain",
field_name="test__engagement__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Engagement that contain a given pattern, and exclude them",
exclude=True)
not_test__engagement__tags = CharFilter(
label="Not Engagement Tag",
field_name="test__engagement__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Engagement that are an exact match, and exclude them",
exclude=True)
not_test__engagement__product__tags_contains = CharFilter(
label="Product Tag Does Not Contain",
field_name="test__engagement__product__tags__name",
lookup_expr="icontains",
help_text="Search for tags on a Product that contain a given pattern, and exclude them",
exclude=True)
not_test__engagement__product__tags = CharFilter(
label="Not Product Tag",
field_name="test__engagement__product__tags__name",
lookup_expr="iexact",
help_text="Search for tags on a Product that are an exact match, and exclude them",
exclude=True)
def delete_tags_from_form(self, tag_list: list):
for tag in tag_list:
self.form.fields.pop(tag, None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class DateRangeFilter(ChoiceFilter):
options = {
None: (_('Any date'), lambda qs, name: qs.all()),
1: (_('Today'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
f'{name}__month': now().month,
f'{name}__day': now().day
})),
2: (_('Past 7 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=7)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
3: (_('Past 30 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=30)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
4: (_('Past 90 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=90)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
5: (_('Current month'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
f'{name}__month': now().month
})),
6: (_('Current year'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
})),
7: (_('Past year'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=365)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](qs, self.field_name)
class DateRangeOmniFilter(ChoiceFilter):
options = {
None: (_('Any date'), lambda qs, name: qs.all()),
1: (_('Today'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
f'{name}__month': now().month,
f'{name}__day': now().day
})),
2: (_('Next 7 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() + timedelta(days=1)),
f'{name}__lt': _truncate(now() + timedelta(days=7)),
})),
3: (_('Next 30 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() + timedelta(days=1)),
f'{name}__lt': _truncate(now() + timedelta(days=30)),
})),
4: (_('Next 90 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() + timedelta(days=1)),
f'{name}__lt': _truncate(now() + timedelta(days=90)),
})),
5: (_('Past 7 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=7)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
6: (_('Past 30 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=30)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
7: (_('Past 90 days'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=90)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
8: (_('Current month'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
f'{name}__month': now().month
})),
9: (_('Past year'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() - timedelta(days=365)),
f'{name}__lt': _truncate(now() + timedelta(days=1)),
})),
10: (_('Current year'), lambda qs, name: qs.filter(**{
f'{name}__year': now().year,
})),
11: (_('Next year'), lambda qs, name: qs.filter(**{
f'{name}__gte': _truncate(now() + timedelta(days=1)),
f'{name}__lt': _truncate(now() + timedelta(days=365)),
})),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](qs, self.field_name)
class ReportBooleanFilter(ChoiceFilter):
options = {
None: (_('Either'), lambda qs, name: qs.all()),
1: (_('Yes'), lambda qs, name: qs.filter(**{
f'{name}': True
})),
2: (_('No'), lambda qs, name: qs.filter(**{
f'{name}': False
})),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](qs, self.field_name)
class ReportRiskAcceptanceFilter(ChoiceFilter):
def any(self, qs, name):
return qs.all()
def accepted(self, qs, name):
# return qs.filter(risk_acceptance__isnull=False)
return qs.filter(ACCEPTED_FINDINGS_QUERY)
def not_accepted(self, qs, name):
return qs.filter(NOT_ACCEPTED_FINDINGS_QUERY)
def was_accepted(self, qs, name):
return qs.filter(WAS_ACCEPTED_FINDINGS_QUERY)
options = {
None: (_('Either'), any),
1: (_('Yes'), accepted),
2: (_('No'), not_accepted),
3: (_('Expired'), was_accepted),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](self, qs, self.field_name)
class MetricsDateRangeFilter(ChoiceFilter):
def any(self, qs, name):
earliest_finding = get_earliest_finding(qs)
if earliest_finding is not None:
start_date = local_tz.localize(datetime.combine(
earliest_finding.date, datetime.min.time())
)
self.start_date = _truncate(start_date - timedelta(days=1))
self.end_date = _truncate(now() + timedelta(days=1))
return qs.all()
def current_month(self, qs, name):
self.start_date = local_tz.localize(
datetime(now().year, now().month, 1, 0, 0, 0))
self.end_date = now()
return qs.filter(**{
f'{name}__year': self.start_date.year,
f'{name}__month': self.start_date.month
})
def current_year(self, qs, name):
self.start_date = local_tz.localize(
datetime(now().year, 1, 1, 0, 0, 0))
self.end_date = now()
return qs.filter(**{
f'{name}__year': now().year,
})
def past_x_days(self, qs, name, days):
self.start_date = _truncate(now() - timedelta(days=days))
self.end_date = _truncate(now() + timedelta(days=1))
return qs.filter(**{
f'{name}__gte': self.start_date,
f'{name}__lt': self.end_date,
})
def past_seven_days(self, qs, name):
return self.past_x_days(qs, name, 7)
def past_thirty_days(self, qs, name):
return self.past_x_days(qs, name, 30)
def past_ninety_days(self, qs, name):
return self.past_x_days(qs, name, 90)
def past_six_months(self, qs, name):
return self.past_x_days(qs, name, 183)
def past_year(self, qs, name):
return self.past_x_days(qs, name, 365)
options = {
None: (_('Past 30 days'), past_thirty_days),
1: (_('Past 7 days'), past_seven_days),
2: (_('Past 90 days'), past_ninety_days),
3: (_('Current month'), current_month),
4: (_('Current year'), current_year),
5: (_('Past 6 Months'), past_six_months),
6: (_('Past year'), past_year),
7: (_('Any date'), any),
}
def __init__(self, *args, **kwargs):
kwargs['choices'] = [
(key, value[0]) for key, value in six.iteritems(self.options)]
super().__init__(*args, **kwargs)
def filter(self, qs, value):
if value == 8:
return qs
earliest_finding = get_earliest_finding(qs)
if earliest_finding is not None:
start_date = local_tz.localize(datetime.combine(
earliest_finding.date, datetime.min.time())
)
self.start_date = _truncate(start_date - timedelta(days=1))
self.end_date = _truncate(now() + timedelta(days=1))
try:
value = int(value)
except (ValueError, TypeError):
value = None
return self.options[value][1](self, qs, self.field_name)
class ProductComponentFilter(DojoFilter):
component_name = CharFilter(lookup_expr='icontains', label="Module Name")
component_version = CharFilter(lookup_expr='icontains', label="Module Version")
o = OrderingFilter(
fields=(
('component_name', 'component_name'),
('component_version', 'component_version'),
('active', 'active'),
('duplicate', 'duplicate'),
('total', 'total'),
),
field_labels={
'component_name': 'Component Name',
'component_version': 'Component Version',
'active': 'Active',
'duplicate': 'Duplicate',
'total': 'Total',
}
)
class ComponentFilterWithoutObjectLookups(ProductComponentFilter):
test__engagement__product__prod_type__name = CharFilter(
field_name="test__engagement__product__prod_type__name",
lookup_expr="iexact",
label="Product Type Name",
help_text="Search for Product Type names that are an exact match")
test__engagement__product__prod_type__name_contains = CharFilter(
field_name="test__engagement__product__prod_type__name",
lookup_expr="icontains",
label="Product Type Name Contains",
help_text="Search for Product Type names that contain a given pattern")
test__engagement__product__name = CharFilter(
field_name="test__engagement__product__name",
lookup_expr="iexact",
label="Product Name",
help_text="Search for Product names that are an exact match")
test__engagement__product__name_contains = CharFilter(
field_name="test__engagement__product__name",
lookup_expr="icontains",
label="Product Name Contains",
help_text="Search for Product names that contain a given pattern")
class ComponentFilter(ProductComponentFilter):
test__engagement__product__prod_type = ModelMultipleChoiceFilter(
queryset=Product_Type.objects.none(),
label="Product Type")
test__engagement__product = ModelMultipleChoiceFilter(
queryset=Product.objects.none(),
label="Product")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form.fields[
'test__engagement__product__prod_type'].queryset = get_authorized_product_types(Permissions.Product_Type_View)
self.form.fields[
'test__engagement__product'].queryset = get_authorized_products(Permissions.Product_View)
class EngagementDirectFilterHelper(FilterSet):
name = CharFilter(lookup_expr="icontains", label="Engagement name contains")
version = CharFilter(field_name="version", lookup_expr="icontains", label="Engagement version")
test__version = CharFilter(field_name="test__version", lookup_expr="icontains", label="Test version")
product__name = CharFilter(lookup_expr="icontains", label="Product name contains")
status = MultipleChoiceFilter(choices=ENGAGEMENT_STATUS_CHOICES, label="Status")
tag = CharFilter(field_name="tags__name", lookup_expr="icontains", label="Tag name contains")
not_tag = CharFilter(field_name="tags__name", lookup_expr="icontains", label="Not tag name contains", exclude=True)
has_tags = BooleanFilter(field_name="tags", lookup_expr="isnull", exclude=True, label="Has tags")
target_start = DateRangeFilter()
target_end = DateRangeFilter()
test__engagement__product__lifecycle = MultipleChoiceFilter(
choices=Product.LIFECYCLE_CHOICES,
label="Product lifecycle",
null_label="Empty")
o = OrderingFilter(
# tuple-mapping retains order
fields=(
("target_start", "target_start"),
("name", "name"),
("product__name", "product__name"),
("product__prod_type__name", "product__prod_type__name"),
("lead__first_name", "lead__first_name"),
),
field_labels={
"target_start": "Start date",
"name": "Engagement",
"product__name": "Product Name",
"product__prod_type__name": "Product Type",
"lead__first_name": "Lead",
}
)
class EngagementDirectFilter(EngagementDirectFilterHelper, DojoFilter):
lead = ModelChoiceFilter(queryset=Dojo_User.objects.none(), label="Lead")
product__prod_type = ModelMultipleChoiceFilter(
queryset=Product_Type.objects.none(),
label="Product Type")
tags = ModelMultipleChoiceFilter(
field_name="tags__name",
to_field_name="name",
queryset=Engagement.tags.tag_model.objects.all().order_by("name"))
not_tags = ModelMultipleChoiceFilter(
field_name="tags__name",
to_field_name="name",
exclude=True,
queryset=Engagement.tags.tag_model.objects.all().order_by("name"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form.fields["product__prod_type"].queryset = get_authorized_product_types(Permissions.Product_Type_View)
self.form.fields["lead"].queryset = get_authorized_users(Permissions.Product_Type_View) \
.filter(engagement__lead__isnull=False).distinct()
class Meta:
model = Engagement
fields = ["product__name", "product__prod_type"]
class EngagementDirectFilterWithoutObjectLookups(EngagementDirectFilterHelper):
lead = CharFilter(
field_name="lead__username",
lookup_expr="iexact",
label="Lead Username",
help_text="Search for Lead username that are an exact match")
lead_contains = CharFilter(
field_name="lead__username",
lookup_expr="icontains",
label="Lead Username Contains",
help_text="Search for Lead username that contain a given pattern")
product__prod_type__name = CharFilter(
field_name="product__prod_type__name",
lookup_expr="iexact",
label="Product Type Name",
help_text="Search for Product Type names that are an exact match")
product__prod_type__name_contains = CharFilter(
field_name="product__prod_type__name",
lookup_expr="icontains",
label="Product Type Name Contains",
help_text="Search for Product Type names that contain a given pattern")
class Meta: