generated from aboutcode-org/skeleton
-
Notifications
You must be signed in to change notification settings - Fork 23
/
api.py
1405 lines (1164 loc) · 48.8 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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# purldb is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/aboutcode-org/purldb for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import logging
from django.core.exceptions import ValidationError
from django.db.models import OuterRef
from django.db.models import Q
from django.db.models import Subquery
from django.forms import widgets
from django.forms.fields import MultipleChoiceField
import django_filters
from django_filters.filters import Filter
from django_filters.filters import MultipleChoiceFilter
from django_filters.filters import OrderingFilter
from django_filters.rest_framework import FilterSet
from drf_spectacular.plumbing import build_array_type
from drf_spectacular.plumbing import build_basic_type
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from drf_spectacular.utils import extend_schema
from packageurl import PackageURL
from packageurl.contrib.django.utils import purl_to_lookups
from rest_framework import mixins
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.throttling import AnonRateThrottle
from univers.version_constraint import InvalidConstraintsError
from univers.version_range import RANGE_CLASS_BY_SCHEMES
from univers.version_range import VersionRange
from univers.versions import InvalidVersion
from minecode import collectors # NOQA
# UnusedImport here!
# But importing the collectors module triggers routes registration
from minecode import priority_router
from minecode.models import PriorityResourceURI
from minecode.route import NoRouteAvailable
from packagedb.filters import PackageSearchFilter
from packagedb.models import Package
from packagedb.models import PackageContentType
from packagedb.models import PackageSet
from packagedb.models import PackageWatch
from packagedb.models import Resource
from packagedb.package_managers import VERSION_API_CLASSES_BY_PACKAGE_TYPE
from packagedb.package_managers import get_api_package_name
from packagedb.package_managers import get_version_fetcher
from packagedb.serializers import CollectPackageSerializer
from packagedb.serializers import DependentPackageSerializer
from packagedb.serializers import IndexPackagesResponseSerializer
from packagedb.serializers import IndexPackagesSerializer
from packagedb.serializers import PackageAPISerializer
from packagedb.serializers import PackageSetAPISerializer
from packagedb.serializers import PackageWatchAPISerializer
from packagedb.serializers import PackageWatchCreateSerializer
from packagedb.serializers import PackageWatchUpdateSerializer
from packagedb.serializers import PartySerializer
from packagedb.serializers import PurlUpdateResponseSerializer
from packagedb.serializers import PurlValidateResponseSerializer
from packagedb.serializers import PurlValidateSerializer
from packagedb.serializers import ResourceAPISerializer
from packagedb.serializers import UpdatePackagesSerializer
from packagedb.serializers import is_supported_addon_pipeline
from packagedb.throttling import StaffUserRateThrottle
from purl2vcs.find_source_repo import get_source_package_and_add_to_package_set
logger = logging.getLogger(__name__)
class CharMultipleWidget(widgets.TextInput):
"""
Enables the support for `MultiValueDict` `?field=a&field=b`
reusing the `SelectMultiple.value_from_datadict()` but render as a `TextInput`.
"""
def value_from_datadict(self, data, files, name):
value = widgets.SelectMultiple().value_from_datadict(data, files, name)
if not value or value == [""]:
return ""
return value
def format_value(self, value):
"""Return a value as it should appear when rendered in a template."""
return ", ".join(value)
class MultipleCharField(MultipleChoiceField):
"""Overrides `MultipleChoiceField` to fit in `MultipleCharFilter`."""
widget = CharMultipleWidget
def valid_value(self, value):
return True
class MultipleCharFilter(MultipleChoiceFilter):
"""Filters on multiple values for a CharField type using `?field=a&field=b` URL syntax."""
field_class = MultipleCharField
class MultipleCharInFilter(MultipleCharFilter):
"""Does a <field>__in = [value] filter instead of field=value filter"""
def filter(self, qs, value):
if not value:
# Even though not a noop, no point filtering if empty.
return qs
if self.is_noop(qs, value):
return qs
predicate = self.get_filter_predicate(value)
old_field_name = next(iter(predicate))
new_field_name = f"{old_field_name}__in"
predicate[new_field_name] = predicate[old_field_name]
predicate.pop(old_field_name)
q = Q(**predicate)
qs = self.get_method(qs)(q)
return qs.distinct() if self.distinct else qs
class CreateListRetrieveUpdateViewSetMixin(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet,
):
"""
A viewset that provides `create`, `list, `retrieve`, and `update` actions.
To use it, override the class and set the `.queryset` and
`.serializer_class` attributes.
"""
pass
class PackageResourcePurlFilter(Filter):
def filter(self, qs, value):
if not value:
return qs
lookups = purl_to_lookups(value)
if not lookups:
return qs
try:
package = Package.objects.get(**lookups)
except Package.DoesNotExist:
return qs.none()
return qs.filter(package=package)
class PackageResourceUUIDFilter(Filter):
def filter(self, qs, value):
if not value:
return qs
try:
package = Package.objects.get(uuid=value)
except (Package.DoesNotExist, ValidationError):
return qs.none()
return qs.filter(package=package)
class ResourceFilterSet(FilterSet):
package = PackageResourceUUIDFilter(label="Package UUID")
purl = PackageResourcePurlFilter(label="Package pURL")
md5 = MultipleCharInFilter(
help_text="Exact MD5. Multi-value supported.",
)
sha1 = MultipleCharInFilter(
help_text="Exact SHA1. Multi-value supported.",
)
class ResourceViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Resource.objects.select_related("package")
serializer_class = ResourceAPISerializer
filterset_class = ResourceFilterSet
throttle_classes = [StaffUserRateThrottle, AnonRateThrottle]
lookup_field = "sha1"
@action(detail=False, methods=["post"])
def filter_by_checksums(self, request, *args, **kwargs):
"""
Take a mapping, where the keys are the names of the checksum algorthm
and the values is a list of checksum values and query those values
against the packagedb.
Supported checksum fields are:
- md5
- sha1
Example:
-------
{
"sha1": [
"b55fd82f80cc1bd0bdabf9c6e3153788d35d7911",
"27afff2610b5a94274a2311f8b15e514446b0e76
]
}
Multiple checksums algorithms can be passed together:
{
"sha1": [
"b55fd82f80cc1bd0bdabf9c6e3153788d35d7911",
"27afff2610b5a94274a2311f8b15e514446b0e76
],
"md5": [
"e927df60b093456d4e611ae235c1aa5b"
]
}
This will return Resources whose sha1 or md5 matches those values.
"""
data = dict(request.data)
unsupported_fields = []
for field, value in data.items():
if field not in ("md5", "sha1"):
unsupported_fields.append(field)
if unsupported_fields:
unsupported_fields_str = ", ".join(unsupported_fields)
response_data = {
"status": f"Unsupported field(s) given: {unsupported_fields_str}"
}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
if not data:
response_data = {"status": "No values provided"}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
lookups = Q()
for field, value in data.items():
value = value or []
# We create this intermediate dictionary so we can modify the field
# name to have __in at the end
d = {f"{field}__in": value}
lookups |= Q(**d)
qs = Resource.objects.filter(lookups).prefetch_related("package")
paginated_qs = self.paginate_queryset(qs)
serializer = ResourceAPISerializer(
paginated_qs, many=True, context={"request": request}
)
return self.get_paginated_response(serializer.data)
class MultiplePackageURLFilter(MultipleCharFilter):
def filter(self, qs, value):
if not value:
# Even though not a noop, no point filtering if empty.
return qs
if self.is_noop(qs, value):
return qs
if all(v == "" for v in value):
return qs
q = Q()
for val in value:
lookups = purl_to_lookups(val)
if not lookups:
continue
q.add(Q(**lookups), Q.OR)
if q:
qs = self.get_method(qs)(q)
else:
qs = qs.none()
return qs.distinct() if self.distinct else qs
PACKAGE_FILTER_SORT_FIELDS = [
"type",
"namespace",
"name",
"version",
"qualifiers",
"subpath",
"download_url",
"filename",
"size",
"release_date",
]
class PackageFilterSet(FilterSet):
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 = MultipleCharInFilter(
help_text="Exact MD5. Multi-value supported.",
)
sha1 = MultipleCharInFilter(
help_text="Exact SHA1. Multi-value supported.",
)
purl = MultiplePackageURLFilter(
label="Package URL",
)
search = PackageSearchFilter(
label="Search",
field_name="name",
lookup_expr="icontains",
)
sort = OrderingFilter(fields=PACKAGE_FILTER_SORT_FIELDS)
class Meta:
model = Package
fields = (
"search",
"type",
"namespace",
"name",
"version",
"qualifiers",
"subpath",
"download_url",
"filename",
"sha1",
"sha256",
"md5",
"size",
"release_date",
)
class PackagePublicViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Package.objects.prefetch_related("dependencies", "parties")
serializer_class = PackageAPISerializer
lookup_field = "uuid"
filterset_class = PackageFilterSet
throttle_classes = [StaffUserRateThrottle, AnonRateThrottle]
@action(detail=True, methods=["get"])
def latest_version(self, request, *args, **kwargs):
"""
Return the latest version of the current Package,
which can be itself if current is the latest.
"""
package = self.get_object()
latest_version = package.get_latest_version()
if latest_version:
return Response(
PackageAPISerializer(latest_version, context={"request": request}).data
)
return Response({})
@action(detail=True, methods=["get"])
def history(self, request, *args, **kwargs):
"""Return the History field associated with the current Package."""
package = self.get_object()
return Response({"history": package.history})
@action(detail=True, methods=["get"])
def resources(self, request, *args, **kwargs):
"""Return the Resources associated with the current Package."""
package = self.get_object()
qs = Resource.objects.filter(package=package)
paginated_qs = self.paginate_queryset(qs)
serializer = ResourceAPISerializer(
paginated_qs, many=True, context={"request": request}
)
return self.get_paginated_response(serializer.data)
@action(detail=True)
def get_enhanced_package_data(self, request, *args, **kwargs):
"""Return a mapping of enhanced Package data for a given Package"""
package = self.get_object()
package_data = get_enhanced_package(package)
return Response(package_data)
@action(detail=False, methods=["post"])
def filter_by_checksums(self, request, *args, **kwargs):
"""
Take a mapping, where the keys are the names of the checksum algorthm
and the values is a list of checksum values and query those values
against the packagedb.
Supported checksum fields are:
- md5
- sha1
- sha256
- sha512
Example:
-------
{
"sha1": [
"b55fd82f80cc1bd0bdabf9c6e3153788d35d7911",
"27afff2610b5a94274a2311f8b15e514446b0e76
]
}
Multiple checksums algorithms can be passed together:
{
"sha1": [
"b55fd82f80cc1bd0bdabf9c6e3153788d35d7911",
"27afff2610b5a94274a2311f8b15e514446b0e76
],
"md5": [
"e927df60b093456d4e611ae235c1aa5b"
]
}
This will return Packages whose sha1 or md5 matches those values.
"""
data = dict(request.data)
unsupported_fields = []
supported_fields = ["md5", "sha1", "sha256", "sha512", "enhance_package_data"]
for field, value in data.items():
if field not in supported_fields:
unsupported_fields.append(field)
if unsupported_fields:
unsupported_fields_str = ", ".join(unsupported_fields)
response_data = {
"status": f"Unsupported field(s) given: {unsupported_fields_str}"
}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
enhance_package_data = data.pop("enhance_package_data", False)
if not data:
response_data = {"status": "No values provided"}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
lookups = Q()
for field, value in data.items():
# Subquery to get the ids of the Packages with the earliest release_date for each `field`
earliest_release_dates = (
Package.objects.filter(**{field: OuterRef(field)})
.order_by("release_date")
.values("id")[:1]
)
value = value or []
lookups |= Q(
**{
f"{field}__in": value,
"id__in": Subquery(earliest_release_dates),
}
)
# Query to get the full Package objects with the earliest release_date for each sha1
qs = Package.objects.filter(lookups)
paginated_qs = self.paginate_queryset(qs)
if enhance_package_data:
serialized_package_data = [
get_enhanced_package(package=package) for package in paginated_qs
]
else:
serializer = PackageAPISerializer(
paginated_qs, many=True, context={"request": request}
)
serialized_package_data = serializer.data
return self.get_paginated_response(serialized_package_data)
class PackageViewSet(PackagePublicViewSet):
@action(detail=True)
def reindex_package(self, request, *args, **kwargs):
"""Reindex this package instance"""
package = self.get_object()
package.reindex()
data = {"status": f"{package.package_url} has been queued for reindexing"}
return Response(data)
class PackageUpdateSet(viewsets.ViewSet):
"""
Take a list of `purls` (where each item is a dictionary containing PURL
and content_type).
If `uuid` is given then all purls will be added to package set if it exists
else a new set would be created and all the purls will be added to that new set.
**Note:** There is also a slight addition to the logic where a purl already exists in the database
and so there are no changes done to the purl entry it is passed as it is.
**Request example:**
{
"purls": [
{"purl": "pkg:npm/[email protected]", "content_type": "CURATION"}
],
"uuid" : "b67ceb49-1538-481f-a572-431062f382gg"
}
"""
def create(self, request):
res = []
serializer = UpdatePackagesSerializer(data=request.data)
if not serializer.is_valid():
return Response(
{"errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST
)
validated_data = serializer.validated_data
packages = validated_data.get("purls", [])
uuid = validated_data.get("uuid", None)
package_set = None
if uuid:
try:
package_set = PackageSet.objects.get(uuid=uuid)
if package_set:
package_set = package_set
except Exception:
message = {"update_status": f"No Package Set found for {uuid}"}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
for items in packages or []:
res_data = {}
purl = items.get("purl")
res_data["purl"] = purl
content_type = items.get("content_type")
content_type_val = PackageContentType.__getitem__(content_type)
lookups = purl_to_lookups(purl)
filtered_packages = Package.objects.filter(**lookups)
res_data["update_status"] = "Already Exists"
if not filtered_packages:
if package_set is None:
package_set = PackageSet.objects.create()
lookups["package_content"] = content_type_val
lookups["download_url"] = " "
cr = Package.objects.create(**lookups)
package_set.add_to_package_set(cr)
res_data["update_status"] = "Updated"
res.append(res_data)
serializer = PurlUpdateResponseSerializer(res, many=True)
return Response(serializer.data)
UPDATEABLE_FIELDS = [
"primary_language",
"copyright",
"declared_license_expression",
"declared_license_expression_spdx",
"license_detections",
"other_license_expression",
"other_license_expression_spdx",
"other_license_detections",
# TODO: update extracted license statement and other fields together
# all license fields are based off of `extracted_license_statement` and should be treated as a unit
# hold off for now
"extracted_license_statement",
"notice_text",
"api_data_url",
"bug_tracking_url",
"code_view_url",
"vcs_url",
"source_packages",
"repository_homepage_url",
"dependencies",
"parties",
"homepage_url",
"description",
]
NONUPDATEABLE_FIELDS = [
"type",
"namespace",
"name",
"version",
"qualifiers",
"subpath",
"purl",
"datasource_id",
"download_url",
"size",
"md5",
"sha1",
"sha256",
"sha512",
"package_uid",
"repository_download_url",
"file_references",
"history",
"last_modified_date",
]
def get_enhanced_package(package):
"""
Return package data from `package`, where the data has been enhanced by
other packages in the same first_package_in_set.
"""
package_content = package.package_content
in_package_sets = package.package_sets.count() > 0
if (
not in_package_sets
or not package_content
or package_content == PackageContentType.SOURCE_REPO
):
# Return unenhanced package data for packages that are not in a package
# set or are source repo packages.
# Source repo packages can't really be enhanced much further, datawise
# and we can't enhance a package that is not in a package set.
return package.to_dict()
elif package_content in [
PackageContentType.BINARY,
PackageContentType.SOURCE_ARCHIVE,
]:
# Binary packages can only be part of one set
# TODO: Can source_archive packages be part of multiple sets?
first_package_in_set = package.package_sets.first()
if first_package_in_set:
package_set_members = first_package_in_set.get_package_set_members()
if package_content == PackageContentType.SOURCE_ARCHIVE:
# Mix data from SOURCE_REPO packages for SOURCE_ARCHIVE packages
package_set_members = package_set_members.filter(
package_content=PackageContentType.SOURCE_REPO
)
# TODO: consider putting in the history field that we enhanced the data
return _get_enhanced_package(package=package, packages=package_set_members)
else:
# if not enhanced return the package as-is
return package.to_dict()
def _get_enhanced_package(package, packages):
"""
Return a mapping of package data based on `package` and Packages in
`packages`.
"""
package_data = package.to_dict()
# always default to PackageContentType.BINARY as we can have None/NULL in the model for now
# Reference: https://github.com/aboutcode-org/purldb/issues/490
package_content = (package and package.package_content) or PackageContentType.BINARY
for peer in packages:
# always default to PackageContentType.BINARY as we can have None/NULL in the model for now
# Reference: https://github.com/aboutcode-org/purldb/issues/490
peer_content = (peer and peer.package_content) or PackageContentType.BINARY
if peer_content >= package_content:
# We do not want to mix data with peers of the same package content
continue
enhanced = False
for field in UPDATEABLE_FIELDS:
package_value = package_data.get(field)
peer_value = getattr(peer, field)
if not package_value and peer_value:
if field == "parties":
peer_value = PartySerializer(peer_value, many=True).data
if field == "dependencies":
peer_value = DependentPackageSerializer(peer_value, many=True).data
package_data[field] = peer_value
enhanced = True
if enhanced:
extra_data = package_data.get("extra_data", {})
enhanced_by = extra_data.get("enhanced_by", [])
enhanced_by.append(peer.purl)
extra_data["enhanced_by"] = enhanced_by
package_data["extra_data"] = extra_data
return package_data
class PackageSetViewSet(viewsets.ReadOnlyModelViewSet):
queryset = PackageSet.objects.prefetch_related("packages")
serializer_class = PackageSetAPISerializer
class PackageWatchViewSet(CreateListRetrieveUpdateViewSetMixin):
"""
Take a `purl` and periodically watch for the new version of the package.
Add the new package version to the scan queue.
Default watch interval is 7 days.
"""
queryset = PackageWatch.objects.get_queryset().order_by("-id")
serializer_class = PackageWatchAPISerializer
lookup_field = "package_url"
lookup_value_regex = r"pkg:[a-zA-Z0-9_]+\/[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*"
http_method_names = ["get", "post", "patch"]
def get_serializer_class(self):
if self.action == "create":
return PackageWatchCreateSerializer
elif self.request.method == "PATCH":
return PackageWatchUpdateSerializer
return super().get_serializer_class()
class CollectViewSet(viewsets.ViewSet):
"""
Return Package data for a `purl` query parameter.
If the package does not exist in the database, collect, store and return the Package
metadata immediately, then run scan and indexing in the background.
Optionally, use a list of `addon_pipelines` to use for the scan.
See add-on pipelines at https://scancodeio.readthedocs.io/en/latest/built-in-pipelines.html
Paremeters:
- `purl`: (required, string) a PURL, with a version.
- `addon_pipelines`: (optional, string) a add-on pipeline names to run in addition to the
standard "scan_single_package" pipeline. Can be repeated to run multiple add-ons.
See also documentation at https://scancodeio.readthedocs.io/en/latest/built-in-pipelines.html
Available addon pipelines are:
- `collect_strings_gettext`
- `collect_symbols_ctags`
- `collect_symbols_pygments`
- `collect_symbols_tree_sitter`
- `inspect_elf_binaries`
- `scan_for_virus` - `source_purl`: (optional, string) a PURL Package URL for the source package to collect at
the same time, when this source is not derivable from the PURL, like for Debian.
- `source_purl`: (optional, string) a PURL Package URL for the compnaion source package
to collect at the same time, when this source data is not derivable from the main `purl`,
like with several Debian packages.
**Examples::**
/api/collect/?purl=pkg:npm/[email protected]&addon_pipelines=collect_symbols_ctags
/api/collect/?purl=pkg:generic/[email protected]&addon_pipelines=collect_symbols_ctags&addon_pipelines=inspect_elf_binaries
**Note:** See `Index packages` for bulk indexing/reindexing of packages.
"""
serializer_class = CollectPackageSerializer
@extend_schema(
parameters=[
OpenApiParameter(
"purl", str, "query", description="PackageURL", required=True
),
OpenApiParameter(
"source_purl", str, "query", description="Source PackageURL"
),
# There is no OpenApiTypes.LIST https://github.com/tfranzel/drf-spectacular/issues/341
OpenApiParameter(
"addon_pipelines",
build_array_type(build_basic_type(OpenApiTypes.STR)),
"query",
description="Addon pipelines",
),
],
responses={200: PackageAPISerializer()},
)
def list(self, request, format=None):
serializer = self.serializer_class(data=request.query_params)
if not serializer.is_valid():
return Response(
{"errors": serializer.errors},
status=status.HTTP_400_BAD_REQUEST,
)
validated_data = serializer.validated_data
purl = validated_data.get("purl")
sort = validated_data.get("sort") or [
"-version",
]
kwargs = dict()
# We want this request to have high priority since the user knows the
# exact package they want
kwargs["priority"] = 100
if source_purl := validated_data.get("source_purl", None):
kwargs["source_purl"] = source_purl
if addon_pipelines := validated_data.get("addon_pipelines", []):
kwargs["addon_pipelines"] = addon_pipelines
lookups = purl_to_lookups(purl)
packages = Package.objects.filter(**lookups).order_by(*sort)
if packages.count() == 0:
try:
errors = priority_router.process(purl, **kwargs)
except NoRouteAvailable:
message = {
"status": f"cannot fetch Package data for {purl}: no available handler"
}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
lookups = purl_to_lookups(purl)
packages = Package.objects.filter(**lookups).order_by(*sort)
if packages.count() == 0:
message = {}
if errors:
message = {
"status": f"error(s) occurred when fetching metadata for {purl}: {errors}"
}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
for package in packages:
get_source_package_and_add_to_package_set(package)
serializer = PackageAPISerializer(
packages, many=True, context={"request": request}
)
return Response(serializer.data)
@extend_schema(
request=IndexPackagesSerializer,
responses={
200: IndexPackagesResponseSerializer(),
},
)
@action(detail=False, methods=["post"], serializer_class=IndexPackagesSerializer)
def index_packages(self, request, *args, **kwargs):
"""
Collect and index a JSON array of `packages` objects with PURLs to process.
Each item in this `packages` array is a JSON object containing these fields:
- `purl`: (required, string) a PURL Package URL, with or without a version. If there is no
version in the purl and no vers range in the vers field, collect all the known versions
for this package. Otherwise, only collect the request version.
- `vers`: (optional, string) a VERS version range. If provided and the purl has no version,
then collect all the versions of the purl that in this versions range.
- `addon_pipelines`: (optional, strings array) an array of add-on pipeline names to run
in addition to the standard "scan_single_package" pipeline.
See also documentation at https://scancodeio.readthedocs.io/en/latest/built-in-pipelines.html
Available addon pipelines are:
- `collect_strings_gettext`
- `collect_symbols_ctags`
- `collect_symbols_pygments`
- `collect_symbols_tree_sitter`
- `inspect_elf_binaries`
- `scan_for_virus`
- `reindex`: (optional, boolean, default to false) reindexing flag. If the `reindex` flag
is true, then all pre-existing and new package versions for the requested `purl` and
`vers` will be (re)fetched, (re)scanned and (re)indexed.
- `reindex_set`: (optional, boolean, default to false) set reindexing flag.
If `reindex_set` flag is set to "true", then all the packages in the same set will be
re-indexex.
- `source_purl`: (optional, string) a PURL Package URL for the compnaion source package
to collect at the same time, when this source data is not derivable from the main `purl`,
like with several Debian packages.
**Request example**::
{
"packages": [
{
"purl": "pkg:npm/[email protected]",
"addon_pipelines": [
"collect_symbols_ctags"
]
},
{
"purl": "pkg:npm/less",
"vers": "vers:npm/>=1.1.0|<=1.1.4"
},
{
"purl": "pkg:npm/foobar",
"addon_pipelines": [
"inspect_elf_binaries",
"collect_symbols_ctags"
]
},
{
"purl": "pkg:generic/[email protected]",
"addon_pipelines": [
"inspect_elf_binaries",
"collect_symbols_ctags"
]
}
],
"reindex": true,
"reindex_set": false
}
POSTing this request will return a mapping containing this data:
- `queued_packages_count`: The number of package urls placed on the index queue.
- `queued_packages`: An array of package urls that were placed on the index queue.
- `requeued_packages_count`: The number of existing package urls placed on the rescan queue.
- `requeued_packages`: An array of existing package urls placed on the rescan queue.
- `unqueued_packages_count`: The number of package urls not placed on the index queue.
This is because the package url already exists on the index queue and has not
yet been processed.
- `unqueued_packages`: An array of package urls that were not placed on the index queue.
- `unsupported_packages_count`: The number of package urls that are not processable by the
index queue.
- `unsupported_packages`: An array of package urls that cannot be queued for indexing.
The package indexing queue can only handle certain support purl types.
- `unsupported_vers_count`: The number of vers range that are not supported by the univers
or package_manager.
- `unsupported_vers`: A list of vers range that are not supported by the univers or
package_manager.
"""
def _reindex_package(package, reindexed_packages, **kwargs):
if package in reindexed_packages:
return
package.reindex(**kwargs)
reindexed_packages.append(package)
serializer = self.serializer_class(data=request.data)
if not serializer.is_valid():
return Response(
{"errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST
)
validated_data = serializer.validated_data
packages = validated_data.get("packages", [])
reindex = validated_data.get("reindex", False)
reindex_set = validated_data.get("reindex_set", False)
queued_packages = []
unqueued_packages = []
nonexistent_packages = []
reindexed_packages = []
requeued_packages = []
supported_ecosystems = [
"maven",
"npm",
"deb",
"generic",
"gnu",
"openssl",
"github",
"conan",
]
unique_packages, unsupported_packages, unsupported_vers = get_resolved_packages(
packages, supported_ecosystems
)
if reindex:
for package in unique_packages:
purl = package["purl"]
kwargs = dict()
if addon_pipelines := package.get("addon_pipelines"):
kwargs["addon_pipelines"] = [