forked from DefectDojo/django-DefectDojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
1685 lines (1379 loc) · 62.1 KB
/
api.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
# see tastypie documentation at http://django-tastypie.readthedocs.org/en
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.http import HttpResponse
from django.urls import resolve, get_script_prefix
import base64
from tastypie import fields
from tastypie import http
from tastypie.fields import RelatedField
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from tastypie.authorization import DjangoAuthorization
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.exceptions import Unauthorized, ImmediateHttpResponse, NotFound
from tastypie.http import HttpCreated
from tastypie.resources import ModelResource, Resource, sanitize
from tastypie.serializers import Serializer
from tastypie.validation import FormValidation, Validation
from tastypie.exceptions import BadRequest
from django.urls.exceptions import Resolver404
from django.utils import timezone
from django.db.models import Count, Q
from django.conf import settings
from django.utils.cache import patch_cache_control, patch_vary_headers
from django.views.decorators.csrf import csrf_exempt
from dojo.models import Product, Engagement, Test, Finding, \
User, Stub_Finding, Risk_Acceptance, \
Finding_Template, Test_Type, Development_Environment, \
BurpRawRequestResponse, Endpoint, Notes, JIRA_Project, JIRA_Instance, \
JIRA_Issue, Tool_Product_Settings, Tool_Configuration, Tool_Type, \
Languages, Language_Type, App_Analysis, Product_Type, Note_Type, \
Endpoint_Status, SEVERITY_CHOICES
from dojo.forms import ProductForm, EngForm, TestForm, \
FindingForm, StubFindingForm, FindingTemplateForm, \
ImportScanForm, JIRAForm, JIRAProjectForm, EditEndpointForm, \
JIRA_IssueForm, ToolConfigForm, ToolProductSettingsForm, \
ToolTypeForm, LanguagesTypeForm, Languages_TypeTypeForm, App_AnalysisTypeForm, \
Development_EnvironmentForm, Product_TypeForm, Test_TypeForm, NoteTypeForm
from dojo.tools.factory import import_parser_factory, requires_file
from datetime import datetime
from .object.parser import import_object_eng
"""
Setup logging for the api
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] %(message)s',
datefmt='%d/%b/%Y %H:%M:%S',
filename=settings.DOJO_ROOT + '/../dojo.log',
)
logger = logging.getLogger(__name__)
"""
class ModelFormValidation(FormValidation):
"""
Override tastypie's standard ``FormValidation`` since this does not care
about URI to PK conversion for ``ToOneField`` or ``ToManyField``.
"""
resource = ModelResource
def __init__(self, **kwargs):
if 'resource' not in kwargs:
raise ImproperlyConfigured("You must provide a 'resource' to 'ModelFormValidation' classes.")
self.resource = kwargs.pop('resource')
super(ModelFormValidation, self).__init__(**kwargs)
def _get_pk_from_resource_uri(self, resource_field, resource_uri):
""" Return the pk of a resource URI """
base_resource_uri = resource_field.to().get_resource_uri()
if not resource_uri.startswith(base_resource_uri):
raise Exception("Couldn't match resource_uri {0} with {1}".format(resource_uri, base_resource_uri))
before, after = resource_uri.split(base_resource_uri)
return after[:-1] if after.endswith('/') else after
def form_args(self, bundle):
rsc = self.resource()
kwargs = super(ModelFormValidation, self).form_args(bundle)
for name, rel_field in list(rsc.fields.items()):
data = kwargs['data']
if not issubclass(rel_field.__class__, RelatedField):
continue # Not a resource field
if name in data and data[name] is not None:
resource_uri = (data[name] if rel_field.full is False
else data[name]['resource_uri'])
pk = self._get_pk_from_resource_uri(rel_field, resource_uri)
kwargs['data'][name] = pk
return kwargs
class BaseModelResource(ModelResource):
def wrap_view(self, view):
"""
Wraps views to check if APIv1 is enabled
"""
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
api_v1_deprecation_warning = 'APIv1 is deprecated and may contain vulnerabilities. It is disabled by default. '
if not settings.LEGACY_API_V1_ENABLE:
raise BadRequest({'code': 666, 'message': api_v1_deprecation_warning + 'It can be enabled at your own risk by setting DD_LEGACY_API_V1_ENABLE to True, or by setting LEGACY_API_V1_ENABLE to True in settings(.dist).py or local_settings.py. APIv1 will be removed at 2021-06-30'})
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
# Our response can vary based on a number of factors, use
# the cache class to determine what we should ``Vary`` on so
# caches won't return the wrong (cached) version.
varies = getattr(self._meta.cache, "varies", [])
if varies:
patch_vary_headers(response, varies)
if self._meta.cache.cacheable(request, response):
if self._meta.cache.cache_control():
# If the request is cacheable and we have a
# ``Cache-Control`` available then patch the header.
patch_cache_control(response, **self._meta.cache.cache_control())
if request.is_ajax() and not response.has_header("Cache-Control"):
# IE excessively caches XMLHttpRequests, so we're disabling
# the browser cache here.
# See http://www.enhanceie.com/ie/bugs.asp for details.
patch_cache_control(response, no_cache=True)
# official header for deprecation
response['Deprecation'] = 'true'
# official header for warning (666 is not official)
response['Warning'] = '666 APIv1 ' + api_v1_deprecation_warning + 'At your own or your admins risk it has been enabled. APIv1 will be removed at 2021-06-30'
return response
except (BadRequest, fields.ApiFieldError) as e:
data = {"error": sanitize(e.args[0]) if getattr(e, 'args') else ''}
return self.error_response(request, data, response_class=http.HttpBadRequest)
except ValidationError as e:
data = {"error": sanitize(e.messages)}
return self.error_response(request, data, response_class=http.HttpBadRequest)
except Exception as e:
# Prevent muting non-django's exceptions
# i.e. RequestException from 'requests' library
if hasattr(e, 'response') and isinstance(e.response, HttpResponse):
return e.response
# A real, non-expected exception.
# Handle the case where the full traceback is more helpful
# than the serialized error.
if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
raise
# Re-raise the error to get a proper traceback when the error
# happend during a test case
if request.META.get('SERVER_NAME') == 'testserver':
raise
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper
@classmethod
def get_fields(cls, fields=None, excludes=None):
"""
Unfortunately we must override this method because tastypie ignores
'blank' attribute on model fields.
Here we invoke an insane workaround hack due to metaclass inheritance
issues:
http://stackoverflow.com/questions/12757468/invoking-super-in-classmethod-called-from-metaclass-new
"""
this_class = next(
c for c in cls.__mro__
if c.__module__ == __name__ and c.__name__ == 'BaseModelResource')
fields = super(this_class, cls).get_fields(fields=fields,
excludes=excludes)
if not cls._meta.object_class:
return fields
for django_field in cls._meta.object_class._meta.fields:
if django_field.blank is True:
res_field = fields.get(django_field.name, None)
if res_field:
res_field.blank = True
return fields
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.Meta.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
# Authentication class - this only allows for header auth, no url parms allowed
# like parent class.
class DojoApiKeyAuthentication(ApiKeyAuthentication):
def extract_credentials(self, request):
if (request.META.get('HTTP_AUTHORIZATION') and
request.META['HTTP_AUTHORIZATION'].lower().startswith('apikey ')):
(auth_type, data) = request.META['HTTP_AUTHORIZATION'].split()
if auth_type.lower() != 'apikey':
raise ValueError("Incorrect authorization header.")
username, api_key = data.split(':', 1)
else:
raise ValueError("Incorrect authorization header.")
return username, api_key
# Authorization class for Product
class UserProductsOnlyAuthorization(Authorization):
def read_list(self, object_list, bundle):
# This assumes a ``QuerySet`` from ``ModelResource``.
if bundle.request.user.is_staff:
return object_list
return object_list.filter(authorized_users__in=[bundle.request.user])
def read_detail(self, object_list, bundle):
# Is the requested object owned by the user?
return (bundle.request.user.is_staff or
bundle.request.user in bundle.obj.authorized_users)
def create_list(self, object_list, bundle):
# Assuming they're auto-assigned to ``user``.
return object_list.filter(authorized_users__in=[bundle.request.user])
def create_detail(self, object_list, bundle):
return (bundle.request.user.is_staff or
bundle.request.user in bundle.obj.authorized_users)
def update_list(self, object_list, bundle):
allowed = []
# Since they may not all be saved, iterate over them.
for obj in object_list:
if (bundle.request.user.is_staff or
bundle.request.user in bundle.obj.authorized_users):
allowed.append(obj)
return allowed
def update_detail(self, object_list, bundle):
return (bundle.request.user.is_staff or
bundle.request.user in bundle.obj.authorized_users)
def delete_list(self, object_list, bundle):
# Sorry user, no deletes for you!
raise Unauthorized("Sorry, no deletes.")
def delete_detail(self, object_list, bundle):
raise Unauthorized("Sorry, no deletes.")
"""
Look up resource only, no update, store, delete
"""
class UserResource(BaseModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'users'
fields = ['id', 'username', 'first_name', 'last_name', 'last_login']
list_allowed_methods = ['get']
detail_allowed_methods = ['get']
include_resource_uri = True
filtering = {
'id': ALL,
'username': ALL,
'first_name': ALL,
'last_name': ALL
}
authorization = DjangoAuthorization()
authentication = DojoApiKeyAuthentication()
serializer = Serializer(formats=['json'])
"""
/api/v1/product_types/
GET [/id/], DELETE [/id/]
Expects: no params
Returns product_types: ALL
Relevant apply filter ?id=?
POST, PUT [/id/]
Expects *name
"""
class ProductTypeResource(BaseModelResource):
class Meta:
resource_name = 'product_types'
list_allowed_methods = ['get', 'post']
# disabled delete. Should not be allowed without fine authorization.
detail_allowed_methods = ['get', 'post', 'put']
queryset = Product_Type.objects.all().order_by('id')
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=Product_TypeForm, resource=ProductTypeResource)
"""
POST, PUT
Expects *product name, *description, *prod_type [1-7]
"""
class ProductResource(BaseModelResource):
class Meta:
resource_name = 'products'
# disabled delete. Should not be allowed without fine authorization.
list_allowed_methods = ['get', 'post'] # only allow get for lists
detail_allowed_methods = ['get', 'post', 'put']
queryset = Product.objects.all().order_by('name')
queryset = queryset.annotate(active_finding_count=Count('engagement__test__finding__id', filter=Q(engagement__test__finding__active=True)))
ordering = ['name', 'id', 'description', 'findings_count', 'created',
'product_type_id']
excludes = ['tid', 'manager', 'prod_manager', 'tech_contact',
'updated']
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'prod_type': ALL,
'created': ALL,
'findings_count': ALL
}
authentication = DojoApiKeyAuthentication()
authorization = UserProductsOnlyAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=ProductForm, resource=ProductResource)
def dehydrate(self, bundle):
# Append the tags in a comma delimited list with the tag element
"""
tags = ""
for tag in bundle.obj.tags.all():
tags = tags + str(tag) + ","
if len(tags) > 0:
tags = tags[:-1]
bundle.data['tags'] = tags
"""
try:
bundle.data['prod_type'] = bundle.obj.prod_type
except:
bundle.data['prod_type'] = 'unknown'
bundle.data['findings_count'] = bundle.obj.findings_count
return bundle
def obj_create(self, bundle, request=None, **kwargs):
bundle = super(ProductResource, self).obj_create(bundle)
"""
tags = bundle.data['tags']
bundle.obj.tags = tags
"""
return bundle
def obj_update(self, bundle, request=None, **kwargs):
bundle = super(ProductResource, self).obj_update(bundle, request, **kwargs)
"""
tags = bundle.data['tags']
bundle.obj.tags = tags
"""
return bundle
"""
/api/v1/tool_configurations/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Tool_ConfigurationResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class Tool_TypeResource(BaseModelResource):
class Meta:
resource_name = 'tool_types'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Tool_Type.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'description': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=ToolTypeForm, resource=Tool_TypeResource)
"""
/api/v1/tool_configurations/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Tool_ConfigurationResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class Tool_ConfigurationResource(BaseModelResource):
tool_type = fields.ForeignKey(Tool_TypeResource, 'tool_type', full=False, null=False)
class Meta:
resource_name = 'tool_configurations'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Tool_Configuration.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'tool_type': ALL_WITH_RELATIONS,
'tool_project_id': ALL,
'url': ALL,
'authentication_type': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
excludes = ['password', 'ssh', 'api_key']
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=ToolConfigForm, resource=Tool_ConfigurationResource)
"""
/api/v1/note_type/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Note_TypeResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class Note_TypeResource(BaseModelResource):
# note_type = fields.ForeignKey(Note_Type, 'note_Type')
class Meta:
resource_name = 'note_type'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Note_Type.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'description': ALL_WITH_RELATIONS,
'is_single': ALL,
'is_active': ALL,
'is_mandatory': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=NoteTypeForm, resource=Note_TypeResource)
"""
POST, PUT [/id/]
Expects *product *target_start, *target_end, *status[In Progress, On Hold,
Completed], threat_model, pen_test, api_test, check_list
"""
class EngagementResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
lead = fields.ForeignKey(UserResource, 'lead',
full=False, null=True)
source_code_management_server = fields.ForeignKey(Tool_ConfigurationResource, 'source_code_management_server',
full=False, null=True)
build_server = fields.ForeignKey(Tool_ConfigurationResource, 'build_server',
full=False, null=True)
orchestration_engine = fields.ForeignKey(Tool_ConfigurationResource, 'orchestration_engine',
full=False, null=True)
class Meta:
resource_name = 'engagements'
list_allowed_methods = ['get', 'post', 'patch']
# disabled delete for /id/
detail_allowed_methods = ['get', 'post', 'put', 'patch']
queryset = Engagement.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'active': ALL,
'eng_type': ALL,
'target_start': ALL,
'target_end': ALL,
'requester': ALL,
'report_type': ALL,
'updated': ALL,
'threat_model': ALL,
'api_test': ALL,
'pen_test': ALL,
'status': ALL,
'product': ALL,
'name': ALL,
'product_id': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=EngForm, resource=EngagementResource)
def dehydrate(self, bundle):
if bundle.obj.eng_type is not None:
bundle.data['eng_type'] = bundle.obj.eng_type.name
else:
bundle.data['eng_type'] = None
bundle.data['product_id'] = bundle.obj.product.id
bundle.data['report_type'] = bundle.obj.report_type
bundle.data['requester'] = bundle.obj.requester
return bundle
"""
/api/v1/app_analysis/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Tool_ConfigurationResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class App_AnalysisResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
user = fields.ForeignKey(UserResource, 'user', null=False)
class Meta:
resource_name = 'app_analysis'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = App_Analysis.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'product': ALL_WITH_RELATIONS,
'user': ALL,
'confidence': ALL,
'version': ALL,
'icon': ALL,
'website': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=App_AnalysisTypeForm, resource=App_AnalysisResource)
"""
/api/v1/language_types/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Tool_ConfigurationResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class LanguageTypeResource(BaseModelResource):
class Meta:
resource_name = 'language_types'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Language_Type.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'language': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=Languages_TypeTypeForm, resource=LanguageTypeResource)
"""
/api/v1/languages/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns Tool_ConfigurationResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DELETE [/id/]
"""
class LanguagesResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
language_type = fields.ForeignKey(LanguageTypeResource, 'language', full=False, null=False)
user = fields.ForeignKey(UserResource, 'user', null=False)
class Meta:
resource_name = 'languages'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Languages.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'files': ALL,
'language_type': ALL_WITH_RELATIONS,
'product': ALL_WITH_RELATIONS,
'user': ALL,
'blank': ALL,
'comment': ALL,
'code': ALL
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=LanguagesTypeForm, resource=LanguagesResource)
"""
/api/v1/tool_product_settings/
GET [/id/], DELETE [/id/]
Expects: no params or id
Returns ToolProductSettingsResource
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class ToolProductSettingsResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
tool_configuration = fields.ForeignKey(Tool_ConfigurationResource, 'tool_configuration', full=False, null=False)
class Meta:
resource_name = 'tool_product_settings'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Tool_Product_Settings.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'product': ALL_WITH_RELATIONS,
'tool_configuration': ALL_WITH_RELATIONS,
'tool_project_id': ALL,
'url': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=ToolProductSettingsForm, resource=ToolProductSettingsResource)
"""
/api/v1/endpoints/
GET [/id/], DELETE [/id/]
Expects: no params or endpoint id
Returns endpoint
Relevant apply filter ?test_type=?, ?id=?
POST, PUT, DLETE [/id/]
"""
class EndpointResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
class Meta:
resource_name = 'endpoints'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Endpoint.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'host': ALL,
'product': ALL_WITH_RELATIONS,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=EditEndpointForm, resource=EndpointResource)
"""
/api/v1/JIRA_Issues/
GET [/id/], DELETE [/id/]
Expects: no params or JIRA_Project
Returns jira configuration: ALL or by JIRA_Project
POST, PUT [/id/]
"""
class JIRA_IssueResource(BaseModelResource):
class Meta:
resource_name = 'jira_finding_mappings'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = JIRA_Issue.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'jira_id': ALL,
'jira_key': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=JIRA_IssueForm, resource=JIRA_IssueResource)
"""
/api/v1/jira_configurations/
GET [/id/], DELETE [/id/]
Expects: no params or JIRA_Project
Returns jira configuration: ALL or by JIRA_Project
POST, PUT [/id/]
"""
class JIRA_ConfResource(BaseModelResource):
class Meta:
resource_name = 'JIRA_Configurations'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = JIRA_Instance.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'url': ALL
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
excludes = ['password']
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=JIRAForm, resource=JIRA_ConfResource)
"""
/api/v1/jira/
GET [/id/], DELETE [/id/]
Expects: no params or jira product key
POST, PUT, DELETE [/id/]
"""
class JiraResource(BaseModelResource):
product = fields.ForeignKey(ProductResource, 'product',
full=False, null=False)
conf = fields.ForeignKey(JIRA_ConfResource, 'conf',
full=False, null=True)
class Meta:
resource_name = 'jira_product_configurations'
list_allowed_methods = ['get', 'post', 'put', 'delete']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = JIRA_Project.objects.all()
include_resource_uri = True
filtering = {
'id': ALL,
'conf': ALL,
'product': ALL_WITH_RELATIONS,
'component': ALL,
'project_key': ALL,
'push_all_issues': ALL,
'enable_engagement_epic_mapping': ALL,
'push_notes': ALL
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=JIRAProjectForm, resource=JiraResource)
"""
/api/v1/environments/
GET [/id/]
Expects: no params
Returns environments: ALL
Relevant apply filter ?id=?
POST, PUT [/id/]
Expects *name
"""
class DevelopmentEnvironmentResource(BaseModelResource):
class Meta:
resource_name = 'development_environments'
list_allowed_methods = ['get', 'post']
# disabled delete. Should not be allowed without fine authorization.
detail_allowed_methods = ['get', 'post', 'put']
queryset = Development_Environment.objects.all().order_by('id')
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=Development_EnvironmentForm, resource=DevelopmentEnvironmentResource)
"""
/api/v1/test_types/
GET [/id/]
Expects: no params
Returns environments: ALL
Relevant apply filter ?id=?
POST, PUT [/id/]
Expects *name
"""
class TestTypeResource(BaseModelResource):
class Meta:
resource_name = 'test_types'
list_allowed_methods = ['get', 'post']
# disabled delete. Should not be allowed without fine authorization.
detail_allowed_methods = ['get', 'post', 'put']
queryset = Test_Type.objects.all().order_by('id')
include_resource_uri = True
filtering = {
'id': ALL,
'name': ALL,
'title': ALL,
'engagement': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=Test_TypeForm, resource=TestTypeResource)
"""
/api/v1/tests/
GET [/id/], DELETE [/id/]
Expects: no params or engagement_id
Returns test: ALL or by engagement_id
Relevant apply filter ?test_type=?, ?id=?
POST, PUT [/id/]
Expects *test_type, *engagement, *target_start, *target_end,
estimated_time, actual_time, percent_complete, notes
"""
class TestResource(BaseModelResource):
engagement = fields.ForeignKey(EngagementResource, 'engagement',
full=False, null=False)
class Meta:
resource_name = 'tests'
list_allowed_methods = ['get', 'post']
# disabled delete. Should not be allowed without fine authorization.
detail_allowed_methods = ['get', 'post', 'put']
queryset = Test.objects.all().order_by('target_end')
include_resource_uri = True
filtering = {
'id': ALL,
'title': ALL,
'test_type': ALL,
'target_start': ALL,
'target_end': ALL,
'notes': ALL,
'percent_complete': ALL,
'actual_time': ALL,
'engagement': ALL,
}
authentication = DojoApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = Serializer(formats=['json'])
@property
def validation(self):
return ModelFormValidation(form_class=TestForm, resource=TestResource)
def dehydrate(self, bundle):
bundle.data['test_type'] = bundle.obj.test_type
return bundle
class RiskAcceptanceResource(BaseModelResource):
class Meta:
resource_name = 'risk_acceptances'
list_allowed_methods = ['get']
detail_allowed_methods = ['get']
queryset = Risk_Acceptance.objects.all().order_by('created')
"""
/api/v1/findings/
GET [/id/], DELETE [/id/]
Expects: no params or test_id