-
-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtest_api.py
More file actions
1343 lines (1180 loc) · 56 KB
/
test_api.py
File metadata and controls
1343 lines (1180 loc) · 56 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.
# VulnerableCode 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/vulnerablecode for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import json
import os
from urllib.parse import quote
from django.test import TestCase
from django.test import TransactionTestCase
from django.test.client import RequestFactory
from rest_framework import status
from rest_framework.test import APIClient
from vulnerabilities.api import PackageSerializer
from vulnerabilities.api import VulnerabilityReferenceSerializer
from vulnerabilities.models import AffectedByPackageRelatedVulnerability
from vulnerabilities.models import Alias
from vulnerabilities.models import ApiUser
from vulnerabilities.models import FixingPackageRelatedVulnerability
from vulnerabilities.models import Package
from vulnerabilities.models import Vulnerability
from vulnerabilities.models import VulnerabilityReference
from vulnerabilities.models import VulnerabilityRelatedReference
from vulnerabilities.models import VulnerabilitySeverity
from vulnerabilities.models import Weakness
from vulnerabilities.severity_systems import EPSS
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DATA = os.path.join(BASE_DIR, "test_data")
TEST_DIR = os.path.join(TEST_DATA, "api")
def cleaned_response(response):
"""
Return a cleaned response suitable for comparison in tests in particular:
- sort lists with a stable order
"""
cleaned_response = []
response_copy = sorted(response, key=lambda x: x.get("purl", ""))
for package_data in response_copy:
package_data["unresolved_vulnerabilities"] = sorted(
package_data["unresolved_vulnerabilities"], key=lambda x: x["vulnerability_id"]
)
for index, vulnerability in enumerate(package_data["unresolved_vulnerabilities"]):
package_data["unresolved_vulnerabilities"][index]["references"] = sorted(
vulnerability["references"], key=lambda x: (x["reference_id"], x["url"])
)
for index2, reference in enumerate(
package_data["unresolved_vulnerabilities"][index]["references"]
):
reference["scores"] = sorted(
reference["scores"], key=lambda x: (x["value"], x["scoring_system"])
)
package_data["unresolved_vulnerabilities"][index]["references"][index2][
"scores"
] = reference["scores"]
package_data["resolved_vulnerabilities"] = sorted(
package_data["resolved_vulnerabilities"], key=lambda x: x["vulnerability_id"]
)
for index, vulnerability in enumerate(package_data["resolved_vulnerabilities"]):
package_data["resolved_vulnerabilities"][index]["references"] = sorted(
vulnerability["references"], key=lambda x: (x["reference_id"], x["url"])
)
for index2, reference in enumerate(
package_data["resolved_vulnerabilities"][index]["references"]
):
reference["scores"] = sorted(
reference["scores"], key=lambda x: (x["value"], x["scoring_system"])
)
package_data["resolved_vulnerabilities"][index]["references"][index2][
"scores"
] = reference["scores"]
cleaned_response.append(package_data)
return cleaned_response
class TestDebianResponse(TransactionTestCase):
def setUp(self):
# create one non-debian package called "mimetex" to verify filtering
Package.objects.create(name="mimetex", version="1.50-1.1", type="deb", namespace="ubuntu")
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.client = APIClient(enforce_csrf_checks=True)
self.client.credentials(HTTP_AUTHORIZATION=self.auth)
def test_query_qualifier_filtering(self):
# packages to check filtering with single/multiple and unordered qualifier filtering
pk_multi_qf = Package.objects.create(
name="vlc", version="1.50-1.1", type="deb", qualifiers={"foo": "bar", "tar": "ball"}
)
pk_single_qf = Package.objects.create(
name="vlc", version="1.50-1.1", type="deb", qualifiers={"foo": "bar"}
)
# check filtering when qualifiers are not normalized
test_purl = quote("pkg:deb/vlc@1.50-1.1?foo=bar&tar=ball")
response = self.client.get(f"/api/packages/?purl={test_purl}", format="json").data
self.assertEqual(2, response["count"])
test_purl = quote("pkg:deb/vlc@1.50-1.1?tar=ball&foo=bar")
response = self.client.get(f"/api/packages/?purl={test_purl}", format="json").data
self.assertEqual(2, response["count"])
# check filtering when there is intersection of qualifiers between packages
test_purl = quote("pkg:deb/vlc@1.50-1.1?foo=bar")
response = self.client.get(f"/api/packages/?purl={test_purl}", format="json").data
self.assertEqual(2, response["count"])
def test_query_by_name(self):
response = self.client.get("/api/packages/?name=mimetex", format="json").data
self.assertEqual(1, response["count"])
first_result = response["results"][0]
self.assertEqual("mimetex", first_result["name"])
versions = {r["version"] for r in response["results"]}
self.assertIn("1.50-1.1", versions)
purls = {r["purl"] for r in response["results"]}
self.assertIn("pkg:deb/ubuntu/mimetex@1.50-1.1", purls)
def test_query_by_invalid_package_url(self):
url = "/api/packages/?purl=invalid_purl"
response = self.client.get(url, format="json")
self.assertEqual(400, response.status_code)
self.assertIn("error", response.data)
error = response.data["error"]
self.assertIn("invalid_purl", error)
def test_query_by_package_url_without_namespace(self):
url = "/api/packages/?purl=pkg:deb/mimetex@1.50-1.1"
response = self.client.get(url, format="json").data
self.assertEqual(1, response["count"])
first_result = response["results"][0]
self.assertEqual("mimetex", first_result["name"])
purls = {r["purl"] for r in response["results"]}
self.assertIn("pkg:deb/ubuntu/mimetex@1.50-1.1", purls)
class TestSerializers(TransactionTestCase):
def setUp(self):
Package.objects.create(
name="mimetex",
version="1.50-1.1",
type="deb",
namespace="ubuntu",
qualifiers={"distro": "jessie"},
)
self.ref = VulnerabilityReference.objects.create(
reference_type="advisory", reference_id="CVE-xxx-xxx", url="https://example.com"
)
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.client = APIClient(enforce_csrf_checks=True)
self.client.credentials(HTTP_AUTHORIZATION=self.auth)
def test_package_serializer(self):
pk = Package.objects.filter(name="mimetex").with_is_vulnerable()
mock_request = RequestFactory().get("/api")
response = PackageSerializer(pk, many=True, context={"request": mock_request}).data
self.assertEqual(1, len(response))
first_result = response[0]
self.assertEqual("mimetex", first_result["name"])
versions = {r["version"] for r in response}
self.assertIn("1.50-1.1", versions)
purls = {r["purl"] for r in response}
self.assertIn("pkg:deb/ubuntu/mimetex@1.50-1.1?distro=jessie", purls)
def test_vulnerability_reference_serializer(self):
response = VulnerabilityReferenceSerializer(instance=self.ref).data
assert response == {
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [],
"url": "https://example.com",
}
class APITestCaseVulnerability(TransactionTestCase):
def setUp(self):
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth)
for i in range(0, 200):
Vulnerability.objects.create(
summary=str(i),
)
self.vulnerability = Vulnerability.objects.create(summary="test")
self.pkg1 = Package.objects.create(name="flask", type="pypi", version="0.1.2")
self.pkg2 = Package.objects.create(name="flask", type="deb", version="0.1.2")
for pkg in [self.pkg1, self.pkg2]:
FixingPackageRelatedVulnerability.objects.create(
package=pkg, vulnerability=self.vulnerability
)
self.reference1 = VulnerabilityReference.objects.create(
reference_id="",
url="https://.com",
)
severity = VulnerabilitySeverity.objects.create(
url="https://.com",
scoring_system=EPSS.identifier,
scoring_elements=".0016",
value="0.526",
)
VulnerabilityRelatedReference.objects.create(
reference=self.reference1, vulnerability=self.vulnerability
)
self.weaknesses = Weakness.objects.create(cwe_id=119)
self.weaknesses.vulnerabilities.add(self.vulnerability)
self.invalid_weaknesses = Weakness.objects.create(
cwe_id=10000
) # cwe not present in weaknesses_db
self.invalid_weaknesses.vulnerabilities.add(self.vulnerability)
self.vulnerability.severities.add(severity)
def test_api_status(self):
response = self.csrf_client.get("/api/vulnerabilities/")
self.assertEqual(status.HTTP_200_OK, response.status_code)
def test_api_response(self):
response = self.csrf_client.get("/api/vulnerabilities/").data
self.assertEqual(response["count"], 201)
def test_api_with_single_vulnerability(self):
response = self.csrf_client.get(
f"/api/vulnerabilities/{self.vulnerability.id}", format="json"
).data
assert response == {
"url": f"http://testserver/api/vulnerabilities/{self.vulnerability.id}",
"vulnerability_id": self.vulnerability.vulnerability_id,
"summary": "test",
"severity_range_score": None,
"aliases": [],
"resource_url": f"http://testserver/vulnerabilities/{self.vulnerability.vulnerability_id}",
"fixed_packages": [
{
"url": f"http://testserver/api/packages/{self.pkg2.id}",
"purl": "pkg:deb/flask@0.1.2",
"is_vulnerable": False,
"affected_by_vulnerabilities": [],
"resource_url": f"http://testserver/packages/{self.pkg2.purl}",
},
{
"url": f"http://testserver/api/packages/{self.pkg1.id}",
"purl": "pkg:pypi/flask@0.1.2",
"is_vulnerable": False,
"affected_by_vulnerabilities": [],
"resource_url": f"http://testserver/packages/{self.pkg1.purl}",
},
],
"affected_packages": [],
"references": [
{
"reference_url": "https://.com",
"reference_id": "",
"reference_type": "",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://.com",
}
],
"weaknesses": [
{
"cwe_id": 119,
"name": "Improper Restriction of Operations within the Bounds of a Memory Buffer",
"description": "The product performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.",
},
],
"exploits": [],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
}
def test_api_with_single_vulnerability_with_filters(self):
response = self.csrf_client.get(
f"/api/vulnerabilities/{self.vulnerability.id}?type=pypi", format="json"
).data
assert response == {
"url": f"http://testserver/api/vulnerabilities/{self.vulnerability.id}",
"vulnerability_id": self.vulnerability.vulnerability_id,
"summary": "test",
"severity_range_score": None,
"aliases": [],
"resource_url": f"http://testserver/vulnerabilities/{self.vulnerability.vulnerability_id}",
"fixed_packages": [
{
"url": f"http://testserver/api/packages/{self.pkg1.id}",
"purl": "pkg:pypi/flask@0.1.2",
"is_vulnerable": False,
"resource_url": f"http://testserver/packages/{self.pkg1.purl}",
"affected_by_vulnerabilities": [],
},
],
"affected_packages": [],
"references": [
{
"reference_url": "https://.com",
"reference_id": "",
"reference_type": "",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://.com",
}
],
"weaknesses": [
{
"cwe_id": 119,
"name": "Improper Restriction of Operations within the Bounds of a Memory Buffer",
"description": "The product performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.",
},
],
"exploits": [],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
}
def test_api_with_single_vulnerability_no_ghost_fix(self):
self.pkg2.is_ghost = True
self.pkg1.is_ghost = True
self.pkg2.save()
self.pkg1.save()
response = self.csrf_client.get(
f"/api/vulnerabilities/{self.vulnerability.id}", format="json"
).data
expected = {
"url": f"http://testserver/api/vulnerabilities/{self.vulnerability.id}",
"vulnerability_id": self.vulnerability.vulnerability_id,
"summary": "test",
"severity_range_score": None,
"aliases": [],
"resource_url": f"http://testserver/vulnerabilities/{self.vulnerability.vulnerability_id}",
"fixed_packages": [],
"affected_packages": [],
"references": [
{
"reference_url": "https://.com",
"reference_id": "",
"reference_type": "",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://.com",
}
],
"weaknesses": [
{
"cwe_id": 119,
"name": "Improper Restriction of Operations within the Bounds of a Memory Buffer",
"description": "The product performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.",
},
],
"exploits": [],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
}
assert expected == response
def set_as_affected_by(package, vulnerability):
"""
Set the ``package`` Package as affected by the ``vulnerability`` Vulnerability.
"""
_set_pkg_as(package, vulnerability, fixing=False)
def set_as_fixing(package, vulnerability):
"""
Set the ``package`` Package as fixing the ``vulnerability`` Vulnerability.
"""
_set_pkg_as(package, vulnerability, fixing=True)
def _set_pkg_as(package, vulnerability, fixing=False):
"""
Set the ``package`` Package as affected or fixing the ``vulnerability`` Vulnerability.
"""
if fixing:
FixingPackageRelatedVulnerability.objects.create(
package=package,
vulnerability=vulnerability,
)
else:
AffectedByPackageRelatedVulnerability.objects.create(
package=package,
vulnerability=vulnerability,
)
def create_vuln(vcid, aliases=()):
"""
Return a test Vulnerability using the ``vcid`` string as VCID, using optional aliases.
"""
vuln = Vulnerability.objects.create(summary=f"This is {vcid}", vulnerability_id=vcid)
add_aliases(vuln, aliases)
return vuln
def add_aliases(vuln, aliases):
"""
Add aliases to ``vuln`` Vulnerability.
"""
for alias in aliases:
Alias.objects.create(alias=alias, vulnerability=vuln)
class APIPerformanceTest(TestCase):
def setUp(self):
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth)
# This setup creates the following data:
# vulnerabilities: vul1, vul2, vul3
# pkg:maven/com.fasterxml.jackson.core/jackson-databind
# with these versions:
# pkg_2_12_6: @ 2.12.6 affected by fixing vul3
# pkg_2_12_6_1: @ 2.12.6.1 affected by vul2 fixing vul1
# pkg_2_13_1: @ 2.13.1 affected by vul1 fixing vul3
# pkg_2_13_2: @ 2.13.2 affected by vul2 fixing vul1
# pkg_2_14_0_rc1: @ 2.14.0-rc1 affected by fixing
# searched-for pkg's vuln
self.vul1 = create_vuln("VCID-vul1-vul1-vul1", ["CVE-2020-36518", "GHSA-57j2-w4cx-62h2"])
self.vul2 = create_vuln("VCID-vul2-vul2-vul2")
# This is the vuln fixed by the searched-for pkg -- and by a lesser version (created below),
# which WILL be included in the API
self.vul3 = create_vuln("VCID-vul3-vul3-vul3", ["CVE-2021-46877", "GHSA-3x8x-79m2-3w2w"])
from_purl = Package.objects.from_purl
# lesser-version pkg that also fixes the vuln fixed by the searched-for pkg
self.pkg_2_12_6 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6")
# this is a lesser version omitted from the API that fixes searched-for pkg's vuln
self.pkg_2_12_6_1 = from_purl(
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6.1"
)
# searched-for pkg
self.pkg_2_13_1 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1")
# this is a greater version that fixes searched-for pkg's vuln
self.pkg_2_13_2 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2")
# This addresses both next and latest non-vulnerable pkg
self.pkg_2_14_0_rc1 = from_purl(
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.14.0-rc1"
)
set_as_fixing(package=self.pkg_2_12_6, vulnerability=self.vul3)
set_as_affected_by(package=self.pkg_2_12_6_1, vulnerability=self.vul2)
set_as_fixing(package=self.pkg_2_12_6_1, vulnerability=self.vul1)
set_as_affected_by(package=self.pkg_2_13_1, vulnerability=self.vul1)
set_as_fixing(package=self.pkg_2_13_1, vulnerability=self.vul3)
set_as_affected_by(package=self.pkg_2_13_2, vulnerability=self.vul2)
set_as_fixing(package=self.pkg_2_13_2, vulnerability=self.vul1)
def test_api_packages_all_num_queries(self):
with self.assertNumQueries(4):
# There are 4 queries:
# 1. SAVEPOINT
# 2. Authenticating user
# 3. Get all vulnerable packages
# 4. RELEASE SAVEPOINT
response = self.csrf_client.get(f"/api/packages/all", format="json").data
assert len(response) == 3
assert list(response) == [
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6.1",
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
]
def test_api_packages_single_num_queries(self):
with self.assertNumQueries(8):
self.csrf_client.get(f"/api/packages/{self.pkg_2_14_0_rc1.id}", format="json")
def test_api_packages_single_with_purl_in_query_num_queries(self):
with self.assertNumQueries(9):
self.csrf_client.get(f"/api/packages/?purl={self.pkg_2_14_0_rc1.purl}", format="json")
def test_api_packages_single_with_purl_no_version_in_query_num_queries(self):
with self.assertNumQueries(64):
self.csrf_client.get(
f"/api/packages/?purl=pkg:maven/com.fasterxml.jackson.core/jackson-databind",
format="json",
)
def test_api_packages_bulk_search(self):
with self.assertNumQueries(45):
packages = [self.pkg_2_12_6, self.pkg_2_12_6_1, self.pkg_2_13_1]
purls = [p.purl for p in packages]
data = {"purls": purls, "purl_only": False, "plain_purl": True}
resp = self.csrf_client.post(
f"/api/packages/bulk_search",
data=json.dumps(data),
content_type="application/json",
).json()
def test_api_packages_with_lookup(self):
with self.assertNumQueries(14):
data = {"purl": self.pkg_2_12_6.purl}
resp = self.csrf_client.post(
f"/api/packages/lookup",
data=json.dumps(data),
content_type="application/json",
).json()
def test_api_packages_bulk_lookup(self):
with self.assertNumQueries(45):
packages = [self.pkg_2_12_6, self.pkg_2_12_6_1, self.pkg_2_13_1]
purls = [p.purl for p in packages]
data = {"purls": purls}
resp = self.csrf_client.post(
f"/api/packages/bulk_lookup",
data=json.dumps(data),
content_type="application/json",
).json()
class APITestCasePackage(TestCase):
def setUp(self):
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth)
# This setup creates the following data:
# vulnerabilities: vul1, vul2, vul3
# pkg:maven/com.fasterxml.jackson.core/jackson-databind
# with these versions:
# pkg_2_12_6: @ 2.12.6 affected by fixing vul3
# pkg_2_12_6_1: @ 2.12.6.1 affected by vul2 fixing vul1
# pkg_2_13_1: @ 2.13.1 affected by vul1 fixing vul3
# pkg_2_13_2: @ 2.13.2 affected by vul2 fixing vul1
# pkg_2_14_0_rc1: @ 2.14.0-rc1 affected by fixing
# searched-for pkg's vuln
self.vul1 = create_vuln("VCID-vul1-vul1-vul1", ["CVE-2020-36518", "GHSA-57j2-w4cx-62h2"])
self.vul2 = create_vuln("VCID-vul2-vul2-vul2")
# This is the vuln fixed by the searched-for pkg -- and by a lesser version (created below),
# which WILL be included in the API
self.vul3 = create_vuln("VCID-vul3-vul3-vul3", ["CVE-2021-46877", "GHSA-3x8x-79m2-3w2w"])
from_purl = Package.objects.from_purl
# lesser-version pkg that also fixes the vuln fixed by the searched-for pkg
self.pkg_2_12_6 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6")
# this is a lesser version omitted from the API that fixes searched-for pkg's vuln
self.pkg_2_12_6_1 = from_purl(
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6.1"
)
# searched-for pkg
self.pkg_2_13_1 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1")
# this is a greater version that fixes searched-for pkg's vuln
self.pkg_2_13_2 = from_purl("pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2")
# This addresses both next and latest non-vulnerable pkg
self.pkg_2_14_0_rc1 = from_purl(
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.14.0-rc1"
)
self.ref = VulnerabilityReference.objects.create(
reference_type="advisory", reference_id="CVE-xxx-xxx", url="https://example.com"
)
self.severity = VulnerabilitySeverity.objects.create(
url="https://example.com",
scoring_system=EPSS.identifier,
scoring_elements=".0016",
value="0.526",
)
self.vul1.references.add(self.ref)
self.vul1.severities.add(self.severity)
self.vul3.references.add(self.ref)
self.vul3.severities.add(self.severity)
set_as_fixing(package=self.pkg_2_12_6, vulnerability=self.vul3)
set_as_affected_by(package=self.pkg_2_12_6_1, vulnerability=self.vul2)
set_as_fixing(package=self.pkg_2_12_6_1, vulnerability=self.vul1)
set_as_affected_by(package=self.pkg_2_13_1, vulnerability=self.vul1)
set_as_fixing(package=self.pkg_2_13_1, vulnerability=self.vul3)
set_as_affected_by(package=self.pkg_2_13_2, vulnerability=self.vul2)
set_as_fixing(package=self.pkg_2_13_2, vulnerability=self.vul1)
def test_api_with_lesser_and_greater_fixed_by_packages(self):
response = self.csrf_client.get(f"/api/packages/{self.pkg_2_13_1.id}", format="json").data
expected = {
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_1.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"type": "maven",
"namespace": "com.fasterxml.jackson.core",
"name": "jackson-databind",
"version": "2.13.1",
"qualifiers": {},
"subpath": "",
"is_vulnerable": True,
"next_non_vulnerable_version": "2.14.0-rc1",
"latest_non_vulnerable_version": "2.14.0-rc1",
"affected_by_vulnerabilities": [
{
"url": "http://testserver/api/vulnerabilities/{0}".format(self.vul1.id),
"vulnerability_id": "VCID-vul1-vul1-vul1",
"summary": "This is VCID-vul1-vul1-vul1",
"references": [
{
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://example.com",
}
],
"fixed_packages": [
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_2.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
"is_vulnerable": True,
"affected_by_vulnerabilities": [
{"vulnerability": "VCID-vul2-vul2-vul2"}
],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
}
],
"aliases": ["CVE-2020-36518", "GHSA-57j2-w4cx-62h2"],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
"resource_url": "http://testserver/vulnerabilities/VCID-vul1-vul1-vul1",
}
],
"fixing_vulnerabilities": [
{
"url": "http://testserver/api/vulnerabilities/{0}".format(self.vul3.id),
"vulnerability_id": "VCID-vul3-vul3-vul3",
"summary": "This is VCID-vul3-vul3-vul3",
"references": [
{
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://example.com",
}
],
"fixed_packages": [
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_12_6.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6",
"is_vulnerable": False,
"affected_by_vulnerabilities": [],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6",
},
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_1.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"is_vulnerable": True,
"affected_by_vulnerabilities": [
{"vulnerability": "VCID-vul1-vul1-vul1"}
],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
},
],
"aliases": ["CVE-2021-46877", "GHSA-3x8x-79m2-3w2w"],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
"resource_url": "http://testserver/vulnerabilities/VCID-vul3-vul3-vul3",
}
],
"risk_score": None,
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
}
assert response == expected
def test_is_vulnerable_attribute_only_exists_on_queryset(self):
assert not hasattr(self.pkg_2_13_1, "is_vulnerable")
pkgs = Package.objects.filter(pk=self.pkg_2_13_1.pk).with_is_vulnerable()
assert all(hasattr(p, "is_vulnerable") for p in pkgs)
def test_api_status(self):
response = self.csrf_client.get("/api/packages/", format="json")
self.assertEqual(status.HTTP_200_OK, response.status_code)
def test_api_response(self):
response = self.csrf_client.get("/api/packages/", format="json").data
self.assertEqual(response["count"], 5)
def test_api_with_namespace_filter(self):
response = self.csrf_client.get(
"/api/packages/?namespace=com.fasterxml.jackson.core", format="json"
).data
self.assertEqual(response["count"], 5)
def test_api_with_wrong_namespace_filter(self):
response = self.csrf_client.get("/api/packages/?namespace=foo-bar", format="json").data
self.assertEqual(response["count"], 0)
def test_api_with_all_vulnerable_packages(self):
with self.assertNumQueries(4):
# There are 4 queries:
# 1. SAVEPOINT
# 2. Authenticating user
# 3. Get all vulnerable packages
# 4. RELEASE SAVEPOINT
response = self.csrf_client.get(f"/api/packages/all", format="json").data
assert len(response) == 3
assert list(response) == [
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6.1",
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
]
def test_api_with_ignorning_qualifiers(self):
response = self.csrf_client.get(
f"/api/packages/?purl=pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.14.0-rc1?foo=bar",
format="json",
).data
assert response["count"] == 1
assert (
response["results"][0]["purl"]
== "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.14.0-rc1"
)
def test_api_with_ghost_package_no_fixing_vulnerabilities(self):
self.pkg_2_13_1.is_ghost = True
self.pkg_2_13_1.save()
response = self.csrf_client.get(f"/api/packages/{self.pkg_2_13_1.id}", format="json").data
expected = {
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_1.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"type": "maven",
"namespace": "com.fasterxml.jackson.core",
"name": "jackson-databind",
"version": "2.13.1",
"qualifiers": {},
"subpath": "",
"is_vulnerable": True,
"next_non_vulnerable_version": "2.14.0-rc1",
"latest_non_vulnerable_version": "2.14.0-rc1",
"affected_by_vulnerabilities": [
{
"url": "http://testserver/api/vulnerabilities/{0}".format(self.vul1.id),
"vulnerability_id": "VCID-vul1-vul1-vul1",
"summary": "This is VCID-vul1-vul1-vul1",
"references": [
{
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://example.com",
}
],
"fixed_packages": [
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_2.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
"is_vulnerable": True,
"affected_by_vulnerabilities": [
{"vulnerability": "VCID-vul2-vul2-vul2"}
],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
}
],
"aliases": ["CVE-2020-36518", "GHSA-57j2-w4cx-62h2"],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
"resource_url": "http://testserver/vulnerabilities/VCID-vul1-vul1-vul1",
}
],
"fixing_vulnerabilities": [],
"risk_score": None,
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
}
assert response == expected
def test_api_with_ghost_package_no_next_latest_non_vulnerabilities(self):
self.pkg_2_14_0_rc1.is_ghost = True
self.pkg_2_14_0_rc1.save()
response = self.csrf_client.get(f"/api/packages/{self.pkg_2_13_1.id}", format="json").data
expected = {
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_1.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"type": "maven",
"namespace": "com.fasterxml.jackson.core",
"name": "jackson-databind",
"version": "2.13.1",
"qualifiers": {},
"subpath": "",
"is_vulnerable": True,
"next_non_vulnerable_version": None,
"latest_non_vulnerable_version": None,
"affected_by_vulnerabilities": [
{
"url": "http://testserver/api/vulnerabilities/{0}".format(self.vul1.id),
"vulnerability_id": "VCID-vul1-vul1-vul1",
"summary": "This is VCID-vul1-vul1-vul1",
"references": [
{
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://example.com",
}
],
"fixed_packages": [
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_2.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
"is_vulnerable": True,
"affected_by_vulnerabilities": [
{"vulnerability": "VCID-vul2-vul2-vul2"}
],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.2",
}
],
"aliases": ["CVE-2020-36518", "GHSA-57j2-w4cx-62h2"],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
"resource_url": "http://testserver/vulnerabilities/VCID-vul1-vul1-vul1",
}
],
"fixing_vulnerabilities": [
{
"url": "http://testserver/api/vulnerabilities/{0}".format(self.vul3.id),
"vulnerability_id": "VCID-vul3-vul3-vul3",
"summary": "This is VCID-vul3-vul3-vul3",
"references": [
{
"reference_url": "https://example.com",
"reference_id": "CVE-xxx-xxx",
"reference_type": "advisory",
"scores": [
{
"value": "0.526",
"scoring_system": "epss",
"scoring_elements": ".0016",
}
],
"url": "https://example.com",
}
],
"fixed_packages": [
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_12_6.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6",
"is_vulnerable": False,
"affected_by_vulnerabilities": [],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.12.6",
},
{
"url": "http://testserver/api/packages/{0}".format(self.pkg_2_13_1.id),
"purl": "pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
"is_vulnerable": True,
"affected_by_vulnerabilities": [
{"vulnerability": "VCID-vul1-vul1-vul1"}
],
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
},
],
"aliases": ["CVE-2021-46877", "GHSA-3x8x-79m2-3w2w"],
"risk_score": None,
"exploitability": None,
"weighted_severity": None,
"resource_url": "http://testserver/vulnerabilities/VCID-vul3-vul3-vul3",
}
],
"risk_score": None,
"resource_url": "http://testserver/packages/pkg:maven/com.fasterxml.jackson.core/jackson-databind@2.13.1",
}
assert response == expected
class CPEApi(TestCase):
def setUp(self):
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth)
self.vulnerability = Vulnerability.objects.create(summary="test")
for i in range(0, 10):
ref, _ = VulnerabilityReference.objects.get_or_create(
reference_id=f"cpe:/a:nginx:{i}",
url=f"https://nvd.nist.gov/vuln/search/results?adv_search=true&isCpeNameSearch=true&query=cpe:/a:nginx:{i}",
)
VulnerabilityRelatedReference.objects.create(
reference=ref, vulnerability=self.vulnerability
)
def test_api_status(self):
response = self.csrf_client.get("/api/cpes/", format="json")
self.assertEqual(status.HTTP_200_OK, response.status_code)
def test_api_response(self):
response = self.csrf_client.get("/api/cpes/?cpe=cpe:/a:nginx:9", format="json").data
self.assertEqual(response["count"], 1)
class TestCPEApiWithPackageVulnerabilityRelation(TestCase):
def setUp(self):
self.user = ApiUser.objects.create_api_user(username="e@mail.com")
self.auth = f"Token {self.user.auth_token.key}"
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.csrf_client.credentials(HTTP_AUTHORIZATION=self.auth)
self.vulnerability = Vulnerability.objects.create(summary="test")
self.affected_package, _ = Package.objects.get_or_create_from_purl(
purl="pkg:nginx/nginx@v3.4"
)
self.fixed_package, _ = Package.objects.get_or_create_from_purl(purl="pkg:nginx/nginx@v4.0")
AffectedByPackageRelatedVulnerability.objects.create(