-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathapi.py
More file actions
1189 lines (1082 loc) · 36 KB
/
api.py
File metadata and controls
1189 lines (1082 loc) · 36 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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# DejaCode is a trademark of nexB Inc.
# SPDX-License-Identifier: AGPL-3.0-only
# See https://github.com/aboutcode-org/dejacode for support or download.
# See https://aboutcode.org for more information about AboutCode FOSS projects.
#
from collections import defaultdict
from django.db import transaction
from django.forms.widgets import HiddenInput
from django.http import FileResponse
from django.http.response import StreamingHttpResponse
import django_filters
import requests
from packageurl.contrib import url2purl
from packageurl.contrib.django.filters import PackageURLFilter
from rest_framework import serializers
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.fields import ListField
from rest_framework.response import Response
from component_catalog.admin import ComponentAdmin
from component_catalog.admin import PackageAdmin
from component_catalog.filters import IsVulnerableFilter
from component_catalog.fuzzy import FuzzyPackageNameSearch
from component_catalog.license_expression_dje import get_license_objects
from component_catalog.license_expression_dje import normalize_and_validate_expression
from component_catalog.models import Component
from component_catalog.models import ComponentKeyword
from component_catalog.models import Package
from component_catalog.models import Subcomponent
from dejacode_toolkit.download import DataCollectionException
from dejacode_toolkit.download import collect_package_data
from dejacode_toolkit.scancodeio import ScanCodeIO
from dje import tasks
from dje.api import AboutCodeFilesActionMixin
from dje.api import CreateRetrieveUpdateListViewSet
from dje.api import CycloneDXSOMActionMixin
from dje.api import DataspacedAPIFilterSet
from dje.api import DataspacedHyperlinkedRelatedField
from dje.api import DataspacedSerializer
from dje.api import DataspacedSlugRelatedField
from dje.api import ExternalReferenceSerializer
from dje.api import NameVersionHyperlinkedRelatedField
from dje.api import SPDXDocumentActionMixin
from dje.filters import LastModifiedDateFilter
from dje.filters import MultipleCharFilter
from dje.filters import MultipleUUIDFilter
from dje.filters import NameVersionFilter
from dje.models import History
from dje.models import external_references_prefetch
from dje.views import SendAboutFilesMixin
from license_library.models import License
from organization.api import OwnerEmbeddedSerializer
from vulnerabilities.api import VulnerabilitySerializer
from vulnerabilities.filters import ScoreRangeFilter
from vulnerabilities.models import RISK_SCORE_RANGES
class LicenseSummaryMixin:
def get_licenses_summary(self, obj):
licenses = obj.licenses.all()
primary_license = obj.primary_license
return [
{
"key": license.key,
"short_name": license.short_name,
"name": license.name,
"category": license.category.label if license.category else None,
"type": license.category.license_type if license.category else None,
"is_primary": bool(len(licenses) == 1 or license.key == primary_license),
}
for license in licenses
]
class ValidateLicenseExpressionMixin:
def validate_license_expression(self, value):
"""
Validate and return a normalized license expression string.
Raise a Django ValidationError exception on errors.
The expression is validated against all the dataspace licenses.
"""
if not value:
return value # Prevent from converting empty string '' into `None`
licenses = License.objects.scope(self.dataspace).for_expression()
return normalize_and_validate_expression(
value, licenses, validate_known=True, include_available=False
)
class LicenseChoicesExpressionMixin:
def get_license_choices_expression(self, obj):
if obj.has_license_choices:
return obj.license_choices_expression
def get_license_choices(self, obj):
if not obj.has_license_choices:
return []
all_licenses = License.objects.scope(obj.dataspace)
choice_licenses = get_license_objects(obj.license_choices_expression, all_licenses)
return [
{"key": license.key, "short_name": license.short_name} for license in choice_licenses
]
class PackageEmbeddedSerializer(DataspacedSerializer):
"""
Warning: Ideally, we should extend from `PackageSerializer` to avoid
code duplication, but we cannot here because of circular import issues.
"""
absolute_url = serializers.SerializerMethodField()
class Meta:
model = Package
fields = (
"api_url",
"absolute_url",
"download_url",
"uuid",
"filename",
"md5",
"sha1",
"sha256",
"sha512",
"size",
"release_date",
"primary_language",
"cpe",
"description",
"keywords",
"project",
"notes",
"dependencies",
"copyright",
"holder",
"author",
"license_expression",
"declared_license_expression",
"other_license_expression",
"reference_notes",
"homepage_url",
"vcs_url",
"code_view_url",
"bug_tracking_url",
"repository_homepage_url",
"repository_download_url",
"api_data_url",
"notice_text",
"package_url",
"type",
"namespace",
"name",
"version",
"qualifiers",
"subpath",
"created_date",
"last_modified_date",
)
extra_kwargs = {
"api_url": {
"view_name": "api_v2:package-detail",
"lookup_field": "uuid",
},
}
class KeywordsField(ListField):
"""Create the provided Keyword value if non existing."""
def create_missing_keywords(self, keywords):
user = self.context["request"].user
dataspace = user.dataspace
qs = ComponentKeyword.objects.scope(dataspace).filter(label__in=keywords)
existing_labels = qs.values_list("label", flat=True)
for label in keywords:
if label not in existing_labels:
keyword = ComponentKeyword.objects.create(
label=label,
dataspace=dataspace,
)
History.log_addition(user, keyword)
def run_child_validation(self, data):
result = super().run_child_validation(data)
if result:
result = [value for value in result if value != ""] # Clean empty string
self.create_missing_keywords(keywords=result)
return result
class ComponentSerializer(
LicenseSummaryMixin,
LicenseChoicesExpressionMixin,
ValidateLicenseExpressionMixin,
DataspacedSerializer,
):
display_name = serializers.ReadOnlyField(source="__str__")
absolute_url = serializers.SerializerMethodField()
owner = DataspacedHyperlinkedRelatedField(
view_name="api_v2:owner-detail",
lookup_field="uuid",
allow_null=True,
required=False,
html_cutoff=10,
slug_field="name",
)
owner_name = serializers.SerializerMethodField()
owner_abcd = OwnerEmbeddedSerializer(
source="owner",
read_only=True,
)
type = DataspacedSlugRelatedField(
slug_field="label",
allow_null=True,
required=False,
)
configuration_status = DataspacedSlugRelatedField(
slug_field="label",
allow_null=True,
required=False,
)
usage_policy = DataspacedSlugRelatedField(
slug_field="label",
allow_null=True,
required=False,
scope_content_type=True,
)
keywords = KeywordsField(
required=False,
)
packages = DataspacedHyperlinkedRelatedField(
many=True,
view_name="api_v2:package-detail",
lookup_field="uuid",
required=False,
slug_field="uuid",
)
packages_abcd = PackageEmbeddedSerializer(
source="packages",
many=True,
read_only=True,
)
external_references = ExternalReferenceSerializer(
many=True,
read_only=True,
)
licenses_summary = serializers.SerializerMethodField(source="get_licenses_summary")
license_choices_expression = serializers.SerializerMethodField(
source="get_license_choices_expression"
)
license_choices = serializers.SerializerMethodField(source="get_license_choices")
class Meta:
model = Component
fields = (
"display_name",
"api_url",
"absolute_url",
"id",
"uuid",
"name",
"version",
"owner",
"owner_name",
"owner_abcd",
"copyright",
"holder",
"license_expression",
"reference_notes",
"release_date",
"description",
"homepage_url",
"vcs_url",
"code_view_url",
"bug_tracking_url",
"primary_language",
"cpe",
"project",
"codescan_identifier",
"type",
"notice_text",
"is_license_notice",
"is_copyright_notice",
"is_notice_in_codebase",
"notice_filename",
"notice_url",
"website_terms_of_use",
"dependencies",
"configuration_status",
"is_active",
"usage_policy",
"curation_level",
"completion_level",
"guidance",
"admin_notes",
"keywords",
"packages",
"packages_abcd",
"external_references",
"ip_sensitivity_approved",
"affiliate_obligations",
"affiliate_obligation_triggers",
"legal_comments",
"sublicense_allowed",
"express_patent_grant",
"covenant_not_to_assert",
"indemnification",
"legal_reviewed",
"approval_reference",
"distribution_formats_allowed",
"acceptable_linkages",
"export_restrictions",
"approved_download_location",
"approved_community_interaction",
"urn",
"licenses",
"licenses_summary",
"license_choices_expression",
"license_choices",
"declared_license_expression",
"other_license_expression",
"created_date",
"last_modified_date",
)
extra_kwargs = {
# The `default` value set on the model field is not accounted by DRF
# https://github.com/encode/django-rest-framework/issues/7469
"is_active": {"default": True},
"api_url": {
"view_name": "api_v2:component-detail",
"lookup_field": "uuid",
},
"owner": {
"view_name": "api_v2:owner-detail",
"lookup_field": "uuid",
},
"licenses": {
"view_name": "api_v2:license-detail",
"lookup_field": "uuid",
},
"packages": {
"view_name": "api_v2:package-detail",
"lookup_field": "uuid",
},
}
def get_fields(self):
fields = super().get_fields()
if "completion_level" in fields:
fields["completion_level"].read_only = True
return fields
def save(self, **kwargs):
instance = super().save(**kwargs)
instance.update_completion_level()
return instance
def get_owner_name(self, obj):
if obj.owner:
return obj.owner.name
class ComponentFilterSet(DataspacedAPIFilterSet):
id = django_filters.NumberFilter(
help_text="Exact id.",
)
uuid = MultipleUUIDFilter()
name = MultipleCharFilter(
help_text="Exact name. Multi-value supported.",
)
version = django_filters.CharFilter(
help_text="Exact version.",
)
version__lt = django_filters.CharFilter(
field_name="version",
lookup_expr="lt",
help_text="Version is lower than.",
)
version__gt = django_filters.CharFilter(
field_name="version",
lookup_expr="gt",
help_text="Version is greater than.",
)
primary_language = django_filters.CharFilter(
help_text="Exact primary language.",
)
project = django_filters.CharFilter(
help_text="Exact project.",
)
owner = MultipleCharFilter(
field_name="owner__name",
help_text="Exact owner name. Multi-value supported.",
)
type = django_filters.CharFilter(
field_name="type__label",
help_text="Exact type label.",
)
configuration_status = django_filters.CharFilter(
field_name="configuration_status__label",
help_text="Exact configuration status label.",
)
usage_policy = django_filters.CharFilter(
field_name="usage_policy__label",
help_text="Exact usage policy label.",
)
curation_level = django_filters.NumberFilter(
lookup_expr="gte",
help_text="Curation level is greater than or equal to",
)
license_expression = django_filters.CharFilter(
lookup_expr="icontains",
help_text="License expression contains (case-insensitive).",
)
keywords = django_filters.CharFilter(
lookup_expr="icontains",
help_text="Keyword label contains (case-insensitive)",
)
last_modified_date = LastModifiedDateFilter()
name_version = NameVersionFilter(
label="Name:Version",
)
is_vulnerable = IsVulnerableFilter(
field_name="affected_by_vulnerabilities",
)
affected_by = django_filters.CharFilter(
field_name="affected_by_vulnerabilities__vulnerability_id",
label="Affected by (vulnerability_id)",
)
class Meta:
model = Component
fields = (
# id is required for the add_to_product and license_expression builder features
"id",
"uuid",
"name",
"version",
"version__lt",
"version__gt",
"primary_language",
"project",
"owner",
"type",
"configuration_status",
"usage_policy",
"license_expression",
"is_active",
"legal_reviewed",
"curation_level",
"last_modified_date",
"name_version",
"keywords",
"is_vulnerable",
"affected_by",
)
class ComponentViewSet(
SPDXDocumentActionMixin, CycloneDXSOMActionMixin, CreateRetrieveUpdateListViewSet
):
queryset = Component.objects.all()
serializer_class = ComponentSerializer
filterset_class = ComponentFilterSet
lookup_field = "uuid"
search_fields = (
"name",
"version",
"copyright",
"homepage_url",
"project",
)
search_fields_autocomplete = (
"name",
"version",
)
ordering_fields = (
"name",
"version",
"copyright",
"license_expression",
"primary_language",
"project",
"codescan_identifier",
"type",
"configuration_status",
"usage_policy",
"curation_level",
"completion_level",
"created_date",
"last_modified_date",
)
email_notification_on = ComponentAdmin.email_notification_on
allow_reference_access = True
def get_queryset(self):
return (
super()
.get_queryset()
.select_related(
"type",
"owner__dataspace",
"configuration_status",
)
.prefetch_related(
"licenses__category",
"packages",
external_references_prefetch,
)
)
class ComponentEmbeddedSerializer(ComponentSerializer):
"""
All Component fields without the relation ones,
except for Owner that is included in PackageViewSet.queryset
prefetch_related for this purpose.
"""
class Meta(ComponentSerializer.Meta):
fields = (
"display_name",
"api_url",
"absolute_url",
"uuid",
"name",
"version",
"owner",
"owner_name",
"copyright",
"holder",
"license_expression",
"declared_license_expression",
"other_license_expression",
"reference_notes",
"release_date",
"description",
"homepage_url",
"vcs_url",
"code_view_url",
"bug_tracking_url",
"primary_language",
"cpe",
"project",
"codescan_identifier",
"notice_text",
"is_license_notice",
"is_copyright_notice",
"is_notice_in_codebase",
"notice_filename",
"notice_url",
"website_terms_of_use",
"dependencies",
"is_active",
"curation_level",
"completion_level",
"guidance",
"admin_notes",
"ip_sensitivity_approved",
"affiliate_obligations",
"affiliate_obligation_triggers",
"legal_comments",
"sublicense_allowed",
"express_patent_grant",
"covenant_not_to_assert",
"indemnification",
"legal_reviewed",
"approval_reference",
"distribution_formats_allowed",
"acceptable_linkages",
"export_restrictions",
"approved_download_location",
"approved_community_interaction",
"urn",
"created_date",
"last_modified_date",
)
class PackageSerializer(
LicenseSummaryMixin,
ValidateLicenseExpressionMixin,
LicenseChoicesExpressionMixin,
DataspacedSerializer,
):
display_name = serializers.ReadOnlyField(source="__str__")
absolute_url = serializers.SerializerMethodField()
components = ComponentEmbeddedSerializer(
source="component_set",
many=True,
read_only=True,
)
external_references = ExternalReferenceSerializer(
many=True,
read_only=True,
)
keywords = KeywordsField(
required=False,
)
licenses_summary = serializers.SerializerMethodField(source="get_licenses_summary")
license_choices_expression = serializers.SerializerMethodField(
source="get_license_choices_expression"
)
license_choices = serializers.SerializerMethodField(source="get_license_choices")
usage_policy = DataspacedSlugRelatedField(
slug_field="label",
allow_null=True,
required=False,
scope_content_type=True,
)
package_content = serializers.ReadOnlyField(source="get_package_content_display")
collect_data = serializers.BooleanField(
write_only=True,
required=False,
allow_null=True,
)
affected_by_vulnerabilities = VulnerabilitySerializer(
read_only=True,
many=True,
fields=[
"vulnerability_id",
"api_url",
"uuid",
],
)
class Meta:
model = Package
fields = (
"display_name",
"api_url",
"absolute_url",
"id",
"download_url",
"uuid",
"filename",
"md5",
"sha1",
"sha256",
"sha512",
"size",
"release_date",
"primary_language",
"cpe",
"description",
"keywords",
"project",
"notes",
"usage_policy",
"dependencies",
"copyright",
"holder",
"author",
"license_expression",
"licenses",
"licenses_summary",
"license_choices_expression",
"license_choices",
"declared_license_expression",
"other_license_expression",
"reference_notes",
"homepage_url",
"vcs_url",
"code_view_url",
"bug_tracking_url",
"repository_homepage_url",
"repository_download_url",
"api_data_url",
"notice_text",
"components",
"package_url",
"type",
"namespace",
"name",
"version",
"qualifiers",
"subpath",
"parties",
"datasource_id",
"file_references",
"package_content",
"external_references",
"created_date",
"last_modified_date",
"collect_data",
"risk_score",
"affected_by_vulnerabilities",
)
extra_kwargs = {
"api_url": {
"view_name": "api_v2:package-detail",
"lookup_field": "uuid",
},
"licenses": {
"view_name": "api_v2:license-detail",
"lookup_field": "uuid",
},
}
exclude_from_validate = [
"collect_data",
]
def create(self, validated_data):
"""Collect data, purl, and submit scan if `collect_data` is provided."""
user = self.context["request"].user
dataspace = user.dataspace
collect_data = validated_data.pop("collect_data", None)
download_url = validated_data.get("download_url")
if collect_data and download_url:
try:
collected_data = collect_package_data(download_url)
except DataCollectionException:
collected_data = {}
package_url = url2purl.get_purl(download_url)
if package_url:
collected_data.update(package_url.to_dict(encode=True, empty=""))
validated_data.update(collected_data)
package = super().create(validated_data)
# Submit the scan if Package was properly created
scancodeio = ScanCodeIO(dataspace)
if scancodeio.is_configured() and dataspace.enable_package_scanning:
# Ensure the task is executed after the transaction is successfully committed
transaction.on_commit(
lambda: tasks.scancodeio_submit_scan.delay(
uris=download_url,
user_uuid=user.uuid,
dataspace_uuid=dataspace.uuid,
)
)
return package
class PackageAPIFilterSet(DataspacedAPIFilterSet):
id = django_filters.NumberFilter(
help_text="Exact id.",
)
uuid = MultipleUUIDFilter()
download_url = django_filters.CharFilter(
help_text="Exact Download URL.",
)
filename = MultipleCharFilter(
help_text="Exact filename. Multi-value supported.",
)
type = django_filters.CharFilter(
lookup_expr="iexact",
help_text="Exact type. (case-insensitive)",
)
namespace = django_filters.CharFilter(
lookup_expr="iexact",
help_text="Exact namespace. (case-insensitive)",
)
name = MultipleCharFilter(
lookup_expr="iexact",
help_text="Exact name. Multi-value supported. (case-insensitive)",
)
version = MultipleCharFilter(
help_text="Exact version. Multi-value supported.",
)
md5 = MultipleCharFilter(
help_text="Exact MD5. Multi-value supported.",
)
sha1 = MultipleCharFilter(
help_text="Exact SHA1. Multi-value supported.",
)
size = django_filters.NumberFilter(
help_text="Exact size in bytes.",
)
primary_language = django_filters.CharFilter(
help_text="Exact primary language.",
)
license_expression = django_filters.CharFilter(
lookup_expr="icontains",
help_text="License expression contains (case-insensitive).",
)
keywords = django_filters.CharFilter(
lookup_expr="icontains",
help_text="Keyword label contains (case-insensitive)",
)
project = django_filters.CharFilter(
help_text="Exact project.",
)
usage_policy = django_filters.CharFilter(
field_name="usage_policy__label",
help_text="Exact usage policy label.",
)
last_modified_date = LastModifiedDateFilter()
fuzzy = FuzzyPackageNameSearch(widget=HiddenInput)
purl = PackageURLFilter(label="Package URL")
is_vulnerable = IsVulnerableFilter(
field_name="affected_by_vulnerabilities",
)
affected_by = django_filters.CharFilter(
field_name="affected_by_vulnerabilities__vulnerability_id",
label="Affected by (vulnerability_id)",
)
risk_score = ScoreRangeFilter(score_ranges=RISK_SCORE_RANGES)
class Meta:
model = Package
fields = (
# id is required for the add_to_product and license_expression builder features
"id",
"uuid",
"download_url",
"filename",
"type",
"namespace",
"name",
"version",
"sha1",
"md5",
"size",
"primary_language",
"keywords",
"project",
"license_expression",
"usage_policy",
"last_modified_date",
"fuzzy",
"purl",
"is_vulnerable",
"affected_by",
"risk_score",
)
def collect_create_scan(download_url, user):
dataspace = user.dataspace
package_qs = Package.objects.filter(download_url=download_url, dataspace=dataspace)
if package_qs.exists():
return False
try:
package_data = collect_package_data(download_url)
except DataCollectionException:
return False
package_url = url2purl.get_purl(download_url)
if package_url:
package_data.update(package_url.to_dict(encode=True, empty=""))
package = Package.create_from_data(user, package_data)
scancodeio = ScanCodeIO(dataspace)
if scancodeio.is_configured() and dataspace.enable_package_scanning:
tasks.scancodeio_submit_scan.delay(
uris=download_url,
user_uuid=user.uuid,
dataspace_uuid=dataspace.uuid,
)
return package
class ScanCodeUnavailable(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "The ScanCode.io service is not available"
class ScanDataUnavailable(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "Scan data is not available"
class ScanFetchError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "Could not fetch scan data"
class PackageViewSet(
SendAboutFilesMixin,
AboutCodeFilesActionMixin,
SPDXDocumentActionMixin,
CycloneDXSOMActionMixin,
CreateRetrieveUpdateListViewSet,
):
queryset = Package.objects.all()
serializer_class = PackageSerializer
filterset_class = PackageAPIFilterSet
lookup_field = "uuid"
search_fields = (
"filename",
"project",
)
search_fields_autocomplete = (
"type",
"namespace",
"name",
"version",
"filename",
)
ordering_fields = (
"download_url",
"filename",
"size",
"release_date",
"primary_language",
"project",
"copyright",
"license_expression",
"usage_policy",
"created_date",
"last_modified_date",
)
email_notification_on = PackageAdmin.email_notification_on
allow_reference_access = True
def get_queryset(self):
return (
super()
.get_queryset()
.prefetch_related(
"component_set__owner",
"licenses__category",
"affected_by_vulnerabilities",
external_references_prefetch,
)
)
@action(detail=True)
def about(self, request, uuid):
package = self.get_object()
return Response({"about_data": package.as_about_yaml()})
def _get_scancodeio_project_info(self, scancodeio, package):
if not scancodeio.is_available():
raise ScanCodeUnavailable()
project_info = scancodeio.get_project_info(download_url=package.download_url)
if not project_info:
raise ScanDataUnavailable()
return project_info
@action(detail=True, name="Scan informations")
def scan_info(self, request, uuid):
"""Return information about the scan from ScanCode.io."""
package = self.get_object()
dataspace = request.user.dataspace
scancodeio = ScanCodeIO(dataspace)
project_info = self._get_scancodeio_project_info(scancodeio, package)
return Response(project_info)
@action(detail=True, name="Scan results")
def scan_results(self, request, uuid):
"""
Stream scan results directly from ScanCode.io back to the client.
The response body is not loaded in memory but proxied chunk by chunk,
making it suitable for large scan result payloads.
"""
package = self.get_object()
dataspace = request.user.dataspace
scancodeio = ScanCodeIO(dataspace)
project_info = self._get_scancodeio_project_info(scancodeio, package)
project_uuid = project_info.get("uuid")
scan_results_url = scancodeio.get_scan_action_url(project_uuid, "results")
try:
scan_response = scancodeio.stream_scan_data(scan_results_url)
except requests.RequestException:
raise ScanFetchError()
return StreamingHttpResponse(
scan_response.iter_content(chunk_size=8192),
content_type=scan_response.headers.get("Content-Type", "application/json"),
)
@action(detail=True, name="Scan summary")
def scan_summary(self, request, uuid):
"""Return the scan summary from ScanCode.io."""
package = self.get_object()
dataspace = request.user.dataspace
scancodeio = ScanCodeIO(dataspace)
project_info = self._get_scancodeio_project_info(scancodeio, package)
project_uuid = project_info.get("uuid")
scan_summary_url = scancodeio.get_scan_action_url(project_uuid, "summary")
scan_summary = scancodeio.fetch_scan_data(scan_summary_url)