-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.py
1637 lines (1338 loc) · 54.5 KB
/
main.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) 2021 Linux Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=E0401,E0611
# pyright: reportMissingImports=false,reportMissingModuleSource=false
import json
import logging
import os
import re
import socket
import subprocess # nosec B404
import tempfile
import threading
import urllib.parse
import warnings
from pprint import pprint
from time import sleep
import requests
import uvicorn
from cvss import CVSS2, CVSS3, CVSS4
from defusedxml import ElementTree as ET
from fastapi import FastAPI, HTTPException, Request, Response, status
from packageurl import PackageURL
from pydantic import BaseModel # pylint: disable=E0611
from sqlalchemy import create_engine
from sqlalchemy.exc import InterfaceError, OperationalError
# Init Globals
service_name = "ortelius-ms-dep-pkg-cud" # pylint: disable=C0103
db_conn_retry = 3 # pylint: disable=C0103
tags_metadata = [
{
"name": "health",
"description": "health check end point",
},
{
"name": "cyclonedx",
"description": "CycloneDX Upload end point",
},
{
"name": "spdx",
"description": "SPDX Upload end point",
},
{
"name": "safety",
"description": "Python Safety Upload end point",
},
]
dhurl = ""
cookies = {} # type: ignore
warnings.filterwarnings("ignore", message="Invalid HTTP request received", category=UserWarning)
desc = """
RestAPI endpoint for adding SBOM data to a component
![Release](https://img.shields.io/github/v/release/ortelius/ms-dep-pkg-cud?sort=semver)
![license](https://img.shields.io/github/license/ortelius/ms-dep-pkg-cud)
![Build](https://img.shields.io/github/actions/workflow/status/ortelius/ms-dep-pkg-cud/build-push-chart.yml)
[![MegaLinter](https://github.com/ortelius/ms-dep-pkg-cud/workflows/MegaLinter/badge.svg?branch=main)](https://github.com/ortelius/ms-dep-pkg-cud/actions?query=workflow%3AMegaLinter+branch%3Amain)
![CodeQL](https://github.com/ortelius/ms-dep-pkg-cud/workflows/CodeQL/badge.svg)
[![OpenSSF
-Scorecard](https://api.securityscorecards.dev/projects/github.com/ortelius/ms-dep-pkg-cud/badge)](https://api.securityscorecards.dev/projects/github.com/ortelius/ms-dep-pkg-cud)
![Discord](https://img.shields.io/discord/722468819091849316)
"""
# Init FastAPI
app = FastAPI(
title=service_name,
description=desc,
version="10.0.0",
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
servers=[{"url": "http://localhost:5003", "description": "Local Server"}],
contact={
"name": "Ortelius Open Source Project",
"url": "https://github.com/ortelius/ortelius/issues",
"email": "[email protected]",
},
openapi_tags=tags_metadata,
)
# Init db connection
db_host = os.getenv("DB_HOST", "localhost")
db_name = os.getenv("DB_NAME", "postgres")
db_user = os.getenv("DB_USER", "postgres")
db_pass = os.getenv("DB_PASS", "postgres")
db_port = os.getenv("DB_PORT", "5432")
validateuser_url = os.getenv("VALIDATEUSER_URL", "")
safety_db = None
if len(validateuser_url) == 0:
validateuser_host = os.getenv("MS_VALIDATE_USER_SERVICE_HOST", "127.0.0.1")
host = socket.gethostbyaddr(validateuser_host)[0]
validateuser_url = "http://" + host + ":" + str(os.getenv("MS_VALIDATE_USER_SERVICE_PORT", "80"))
engine = create_engine(
"postgresql+psycopg2://" + db_user + ":" + db_pass + "@" + db_host + ":" + db_port + "/" + db_name,
pool_pre_ping=True,
)
def is_empty(my_string):
"""
Is the string empty.
Args:
my_string (string): string to check emptyness on
Returns:
boolean: True if the string is None or blank, otherwise False.
"""
if isinstance(my_string, int):
my_string = str(my_string)
return not (my_string and my_string.strip())
def is_not_empty(my_string):
"""
Is the string NOT empty.
Args:
my_string (string): string to check emptyness on
Returns:
boolean: False if the string is None or blank, otherwise True.
"""
if isinstance(my_string, int):
my_string = str(my_string)
return bool(my_string and my_string.strip())
def get_json(url, cookies):
"""
Get URL as json string.
Args:
url (string): url to server
cookies (string) - login cookies
Returns:
string: The json string.
"""
try:
res = requests.get(url, cookies=cookies, timeout=300)
if res is None:
return None
if res.status_code != 200:
return None
return res.json()
except requests.exceptions.ConnectionError as conn_error:
print(str(conn_error))
except Exception as err:
print(f"Other error occurred: {err}")
return None
def post_json(url, payload, cookies):
"""
Post URL as json string.
Args:
url (string): url to server
payload (string): json payload to post
cookies (string): login cookies
Returns:
string: The json string.
"""
try:
if "/import" in url:
res = requests.post(
url,
data=payload,
cookies=cookies,
headers={"Content-Type": "application/json"},
timeout=1800,
)
else:
res = requests.post(
url,
data=payload,
cookies=cookies,
headers={
"Content-Type": "application/json",
"host": "console.deployhub.com",
},
timeout=300,
)
if res is None:
return None
if res.status_code < 200 and res.status_code > 299:
return None
return res.json()
except requests.exceptions.ConnectionError as conn_error:
print(str(conn_error))
return None
def get_component(dhurl, cookies, compname, compvariant, compversion, id_only, latest):
"""
Get the component json string.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain name
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
id_only (boolean): return just the id and not the whole json string
latest (boolean): return the latest version
Returns:
int: if id_only = True
string: if id_only = False. If latest = True then latest version json is returned otherwise current version json string is returned.
"""
compvariant = clean_name(compvariant)
compversion = clean_name(compversion)
if (compvariant == "" or compvariant is None) and compversion is not None and compversion != "":
compvariant = compversion
compversion = None
component = ""
if compvariant is not None and compvariant != "" and compversion is not None and compversion != "":
component = compname + ";" + compvariant + ";" + compversion
elif compvariant is not None and compvariant != "":
component = compname + ";" + compvariant
else:
component = compname
check_compname = ""
short_compname = ""
if "." in compname:
short_compname = compname.split(".")[-1]
if compvariant is not None and compvariant != "" and compversion is not None and compversion != "":
check_compname = short_compname + ";" + compvariant + ";" + compversion
elif compvariant is not None and compvariant != "":
check_compname = short_compname + ";" + compvariant
else:
check_compname = short_compname
param = ""
if id_only:
param = "&idonly=Y"
if latest:
param = param + "&latest=Y"
data = get_json(
dhurl + "/dmadminweb/API/component/?name=" + urllib.parse.quote(component) + param,
cookies,
)
if data is None:
return [-1, ""]
if data["success"]:
compid = data["result"]["id"]
name = data["result"]["name"]
if name != check_compname and "versions" in data["result"]:
vers = data["result"]["versions"]
for ver in vers:
if ver["name"] == check_compname:
compid = ver["id"]
name = ver["name"]
break
return [compid, name]
return [-1, ""]
def new_component_version(
dhurl,
cookies,
compname,
compvariant,
compversion,
kind,
component_items,
compautoinc,
):
"""
Create a new component version and base version if needed.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
kind (string): docker or file
component_items (list): component items for the file type
compautoinc (boolean): auto increment an existing version to the new version
Returns:
int: id of the new component, -1 if an error occurred.
"""
compvariant = clean_name(compvariant)
compversion = clean_name(compversion)
if (compvariant == "" or compvariant is None) and compversion is not None and compversion != "":
compvariant = compversion
compversion = None
compname = compname.rstrip(";")
compvariant = compvariant.rstrip(";")
if compversion is not None:
compversion = compversion.rstrip(";")
# Get latest version of compnent variant
data = get_component(dhurl, cookies, compname, compvariant, compversion, False, True)
if data[0] == -1:
data = get_component(dhurl, cookies, compname, compvariant, None, False, True)
if data[0] == -1:
data = get_component(dhurl, cookies, compname, "", None, False, True)
latest_compid = data[0]
found_compname = data[1]
check_compname = ""
compid = latest_compid
short_compname = ""
if "." in compname:
short_compname = compname.split(".")[-1]
if compvariant is not None and compvariant != "" and compversion is not None and compversion != "":
check_compname = short_compname + ";" + compvariant + ";" + compversion
elif compvariant is not None and compvariant != "":
check_compname = short_compname + ";" + compvariant
else:
check_compname = short_compname
# Create base component variant
# if one is not found
# Get the new compid of the new component variant
if compvariant is None:
compvariant = ""
if compversion is None:
compversion = ""
if latest_compid < 0:
if kind.lower() == "docker":
compid = new_docker_component(dhurl, cookies, compname, compvariant, compversion, -1)
else:
compid = new_file_component(dhurl, cookies, compname, compvariant, compversion, -1, None)
else:
# Create component items for the component
if compautoinc is None:
if found_compname == "" or found_compname != check_compname:
if kind.lower() == "docker":
compid = new_docker_component(dhurl, cookies, compname, compvariant, compversion, compid)
else:
compid = new_file_component(
dhurl,
cookies,
compname,
compvariant,
compversion,
compid,
component_items,
)
if compid > 0:
if kind.lower() == "docker":
new_component_item(dhurl, cookies, compid, "docker", None)
else:
new_component_item(dhurl, cookies, compid, "file", component_items)
return compid
def new_docker_component(dhurl, cookies, compname, compvariant, compversion, parent_compid):
"""
Create a new docker component.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
parent_compid (int): parent component version for the new component
Returns:
int: id of the new component, -1 if an error occurred.
"""
compvariant = clean_name(compvariant)
compversion = clean_name(compversion)
if (compvariant is None or compvariant == "") and compversion is not None and compversion != "":
compvariant = compversion
compversion = None
compid = 0
# Create base version
if parent_compid < 0:
if is_empty(compvariant):
data = get_json(
dhurl + "/dmadminweb/API/new/compver/?name=" + urllib.parse.quote(compname),
cookies,
)
else:
data = get_json(
dhurl + "/dmadminweb/API/new/compver/?name=" + urllib.parse.quote(compname + ";" + compvariant),
cookies,
)
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", "0"))
else:
data = get_json(dhurl + "/dmadminweb/API/new/compver/" + str(parent_compid), cookies)
if data is not None:
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", "0"))
update_name(dhurl, cookies, compname, compvariant, compversion, compid)
new_component_item(dhurl, cookies, compid, "docker", None)
return compid
def new_file_component(dhurl, cookies, compname, compvariant, compversion, parent_compid, component_items):
"""
Create a new file component.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
parent_compid (int): parent component version for the new component
component_items (list): list of items for the component
Returns:
int: id of the new component, -1 if an error occurred.
"""
compvariant = clean_name(compvariant)
compversion = clean_name(compversion)
if (compvariant is None or compvariant == "") and compversion is not None and compversion != "":
compvariant = compversion
compversion = None
compid = 0
# Create base version
if parent_compid < 0:
if is_empty(compvariant):
data = get_json(
dhurl + "/dmadminweb/API/new/compver/?name=" + urllib.parse.quote(compname),
cookies,
)
else:
data = get_json(
dhurl + "/dmadminweb/API/new/compver/?name=" + urllib.parse.quote(compname + ";" + compvariant),
cookies,
)
if data is not None:
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", "0"))
else:
data = get_json(dhurl + "/dmadminweb/API/new/compver/" + str(parent_compid), cookies)
if data is not None:
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", "0"))
update_name(dhurl, cookies, compname, compvariant, compversion, compid)
new_component_item(dhurl, cookies, compid, "file", component_items)
return compid
def new_component_item(dhurl, cookies, compid, kind, component_items):
"""
Create a new component item for the component.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
kind (string): docker or file for the component kind
Returns:
int: id of the new component item, -1 if an error occurred.
"""
data = None
# Get compId
if kind.lower() == "docker" or component_items is None:
data = get_json(
dhurl + "/dmadminweb/UpdateAttrs?f=inv&c=" + str(compid) + "&xpos=100&ypos=100&kind=" + kind + "&removeall=Y",
cookies,
)
else:
ypos = 100
i = 0
parent_item = -1
for item in component_items:
tmpstr = ""
ciname = ""
for entry in item:
if entry["key"].lower() == "name":
ciname = entry["value"]
else:
tmpstr = tmpstr + "&" + urllib.parse.quote(entry["key"]) + "=" + urllib.parse.quote(entry["value"])
if i == 0:
tmpstr = tmpstr + "&removeall=Y"
data = get_json(
dhurl + "/dmadminweb/API/new/compitem/" + urllib.parse.quote(ciname) + "?component=" + str(compid) + "&xpos=100&ypos=" + str(ypos) + "&kind=" + kind + tmpstr,
cookies,
)
if data is not None:
if data.get("result", None) is not None:
result = data.get("result", {})
workid = result.get("id", -1)
if parent_item > 0:
get_json(
dhurl + "/dmadminweb/UpdateAttrs?f=iad&c=" + str(compid) + "&fn=" + str(parent_item) + "&tn=" + str(workid),
cookies,
)
parent_item = workid
ypos = ypos + 100
i = i + 1
return data
def clean_name(name):
"""
Remove periods and dashes from the name.
Args:
name (string): string to clean
Returns:
string: the name with periods and dashes changed to userscores.
"""
if name is None:
return name
name = name.replace(".", "_")
name = name.replace("-", "_")
name = name.replace("/", ".")
name = name.replace("+", "_")
name = name.replace(":", "_")
name = name.replace("~", "_")
name = name.replace("(", "")
name = name.replace(")", "")
name = name.replace("#", "_")
name = name.replace("@", "")
return name
def update_name(dhurl, cookies, compname, compvariant, compversion, compid):
"""
Update the name of the component for the compid to the new name.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
compid (int): id to the component to update the name of
Returns:
string: json string of the component update.
"""
compvariant = clean_name(compvariant)
compversion = clean_name(compversion)
if (compvariant is None or compvariant == "") and compversion is not None and compversion != "":
compvariant = compversion
compversion = None
if "." in compname:
compname = compname.split(".")[-1]
if compvariant is not None and compvariant != "" and compversion is not None and compversion != "":
data = get_json(
dhurl + "/dmadminweb/UpdateSummaryData?objtype=23&id=" + str(compid) + "&change_1=" + urllib.parse.quote(compname + ";" + compvariant + ";" + compversion),
cookies,
)
elif compvariant is not None and compvariant != "":
data = get_json(
dhurl + "/dmadminweb/UpdateSummaryData?objtype=23&id=" + str(compid) + "&change_1=" + urllib.parse.quote(compname + ";" + compvariant),
cookies,
)
else:
data = get_json(
dhurl + "/dmadminweb/UpdateSummaryData?objtype=23&id=" + str(compid) + "&change_1=" + urllib.parse.quote(compname),
cookies,
)
return data
def new_component(dhurl, cookies, compname, compvariant, compversion, kind, parent_compid):
"""
Create the component object based on the component name and variant.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
kind (string): docker or file for the kind of component
parent_compid: id of the parent component version
Returns:
int: component id of the new component otherwise None.
"""
compid = -1
# Create base version
if parent_compid is None:
data = get_json(
dhurl + "/dmadminweb/API/new/compver/?name=" + urllib.parse.quote(compname + ";" + compvariant),
cookies,
)
if data is not None:
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", -1))
else:
data = get_json(dhurl + "/dmadminweb/API/new/compver/" + str(parent_compid), cookies)
if data is not None:
if data is not None:
result = data.get("result", {})
compid = int(result.get("id", -1))
update_name(dhurl, cookies, compname, compvariant, compversion, compid)
if kind is not None:
new_component_item(dhurl, cookies, compid, kind, None)
return compid
def get_component_name(dhurl, cookies, compid):
"""
Get the full component name.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compid (int): id of the component
Returns:
string: full name of the component
"""
name = ""
data = get_json(dhurl + "/dmadminweb/API/component/" + str(compid) + "?idonly=Y", cookies)
if data is None:
return name
if data["success"]:
name = data["result"]["domain"] + "." + data["result"]["name"]
return name
def update_component_attrs(dhurl, cookies, compname, compvariant, compversion, attrs):
"""
Update the attributes, key/value pairs, for the component and CR list.
Args:
dhurl (string): url to the server
cookies (string): cookies from login
compname (string): name of the component including domain
compvariant (string): variant of the component, optional
compversion (string): version of the component, optional
attrs (dict): key/value dictionary
Returns:
list: [True for success, otherwise False, json string of update, url for update].
"""
# Get latest version of compnent variant
data = get_component(dhurl, cookies, compname, compvariant, compversion, True, False)
compid = data[0]
if compid < 0:
return
payload = json.dumps(attrs)
data = post_json(dhurl + "/dmadminweb/API/setvar/component/" + str(compid), payload, cookies)
if data is None:
return [False, "Could not update attributes on '" + compname + "'"]
return [True, data, dhurl + "/dmadminweb/API/setvar/component/" + str(compid)]
def create_compver(dhurl, cookies, purl):
if purl is None or purl.strip() == "":
return
purl_parts = PackageURL.from_string(purl)
domain = ""
if purl_parts.namespace is None:
domain = "GLOBAL.Open Source." + purl_parts.type
else:
domain = "GLOBAL.Open Source." + purl_parts.type + "." + purl_parts.namespace.replace(".", "_")
domain = domain.replace("/", ".").replace("-", "_").replace("+", "_").replace("@", "")
compname = ""
version = ""
if purl_parts.version is None:
compname = clean_name(purl_parts.name.replace(".", "_"))
else:
compname = clean_name(purl_parts.name.replace(".", "_") + ";" + purl_parts.version)
version = clean_name(purl_parts.version)
package = clean_name(purl_parts.name).replace(".", "_")
try:
with engine.connect() as connection:
conn = connection.connection
cursor = conn.cursor()
params = tuple([domain, compname])
cursor.execute(
"select count(*) from dm.dm_component a, dm.dm_domain b where a.domainid = b.id and b.fullname = %s and a.name = %s",
params,
)
count_result = cursor.fetchone()[0]
cursor.close
if count_result == 0:
compvariant = ""
compautoinc = None
kind = "file"
compname = domain + "." + package
compversion = version
data = get_component(dhurl, cookies, compname, "", "", True, True)
parent_compid = data[0]
# create component version
if parent_compid < 0:
print("Creating Parent Component")
parent_compid = new_component_version(
dhurl,
cookies,
compname,
compvariant,
"",
kind,
None,
compautoinc,
)
print("Creating Component")
shortname = compname
if "." in shortname:
shortname = shortname.split(".")[-1]
compid = new_component_version(dhurl, cookies, compname, compversion, "", kind, None, compautoinc)
else:
compvariant = ""
compautoinc = None
kind = "file"
compname = domain + "." + package
compversion = version
compid = get_component(dhurl, cookies, compname, compvariant, compversion, True, False)
compname = get_component_name(dhurl, cookies, compid)
compversion = ""
compvariant = ""
print("Creation Done: " + compname)
attrs = {}
org = ""
repo_project = ""
gitcommit = None
giturl = None
results = getCommitFromPurl(
purl_parts.type,
purl_parts.namespace,
purl_parts.name,
purl_parts.version,
purl,
)
giturl = results.get("repo_url", None)
gitcommit = results.get("commit_sha", None)
print(f"Purl: {purl}, Url: {giturl}, Commit: {gitcommit}")
if gitcommit is not None:
attrs["GitCommit"] = gitcommit
if giturl is not None and giturl != "":
giturl = giturl.replace(".git", "")
path_segments = giturl.strip("/").replace("https://", "").replace("http://", "").split("/")
# Extract org and repo from the path segments
if len(path_segments) >= 3:
org = path_segments[1]
repo_project = path_segments[2]
attrs["Purl"] = purl
attrs["GitUrl"] = giturl
attrs["GitOrg"] = org
attrs["GitRepo"] = org + "/" + repo_project
attrs["GitRepoProject"] = repo_project
if purl_parts.version is not None:
attrs["GitTag"] = purl_parts.version
data = update_component_attrs(dhurl, cookies, compname, compvariant, compversion, attrs)
print("Attribute Update Done")
return
except Exception as err:
print(str(err))
return
def get_commit_sha(repo_url, package_version):
if repo_url is None:
return None
cwd = os.getcwd()
# Create a temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
repo_url = repo_url.replace("http://github.com", "https://github.com")
repo_url = repo_url.replace("git://github.com", "https://github.com")
repo_url = repo_url.replace("git+https://", "https://github.com")
repo_url = repo_url.replace("git+ssh://git@", "https://")
repo_url = repo_url.replace("git+", "")
# Clone the repository without checking out the files
# print(f"Clone {repo_url}")
try:
subprocess.run(
["git", "clone", repo_url, "--no-checkout", temp_dir],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
) # nosec B602, B603, B607
except subprocess.TimeoutExpired:
os.chdir(cwd)
return None
# Change into the cloned repository directory
os.chdir(temp_dir)
if not os.path.exists(".git"):
os.chdir(cwd)
return None
commit_sha = None
try:
commit_sha = subprocess.check_output(
["git", "rev-list", "-n", "1", package_version],
stderr=subprocess.DEVNULL,
text=True,
).strip() # nosec B602, B603, B607
except subprocess.CalledProcessError:
pass
if commit_sha is None:
try:
commit_sha = subprocess.check_output(
["git", "rev-list", "-n", "1", "v" + package_version],
stderr=subprocess.DEVNULL,
text=True,
).strip() # nosec B602, B603, B607
except subprocess.CalledProcessError:
pass
# print(f"Commit {commit_sha}")
os.chdir(cwd)
return commit_sha
def get_deb_info(package_name, version):
repo_url = None
dscfile = f"https://launchpad.net/ubuntu/+archive/primary/+sourcefiles/{package_name}/{version}/{package_name}_{version}.dsc"
response = requests.get(dscfile, allow_redirects=True, timeout=2)
# Check if the request was successful (status code 200)
if response.status_code == 200:
dsc_content = response.text
# Find the value for vcs-git using regular expression
vcs_git_match = re.search(r"^Vcs-Git:\s*(.*)", dsc_content, re.MULTILINE)
repo_url = vcs_git_match.group(1) if vcs_git_match else None
if repo_url is None:
return "", None
if "git://git.debian.org/git" in repo_url:
repo_url = repo_url.replace("git://git.debian.org/git", "https://salsa.debian.org").replace(".git", "")
if "git://git.debian.org/users" in repo_url:
repo_url = repo_url.replace("git://git.debian.org/users", "https://salsa.debian.org").replace(".git", "")
if "git://anonscm.debian.org/users" in repo_url:
repo_url = repo_url.replace("git://anonscm.debian.org/users", "https://salsa.debian.org").replace(".git", "")
if "git://git.debian.org" in repo_url:
repo_url = repo_url.replace("git://git.debian.org", "https://salsa.debian.org").replace(".git", "")
if "git://anonscm.debian.org" in repo_url:
repo_url = repo_url.replace("git://anonscm.debian.org", "https://salsa.debian.org").replace(".git", "")
# Define the pattern to match "pkg-*"
pattern = re.compile(r"pkg-(\w+)")
# Use a lambda function in the sub method to transpose "pkg-*" to "*-team"
repo_url = pattern.sub(lambda match: f"{match.group(1)}-team", repo_url)
print(f"DSC: {repo_url}")
commit_sha = get_commit_sha(repo_url, version)
return repo_url, commit_sha
def get_pypi_info(package_name, version):
url = f"https://pypi.org/pypi/{package_name}/{version}/json"
response = requests.get(url, timeout=2)
data = response.json()
info = data.get("info", {})
project_urls = info.get("project_urls", {})
repo_url = None
for key, value in project_urls.items():
if "source" in key.lower():
repo_url = value
break
commit_sha = get_commit_sha(repo_url, version)
return repo_url, commit_sha
def get_npm_info(package_name, version):
url = f"https://registry.npmjs.org/{package_name}/{version}"
response = requests.get(url, timeout=2)
if response.status_code == 200:
data = response.json()
repo_url = data.get("repository", {}).get("url", "")
else:
return "", None
commit_sha = get_commit_sha(repo_url, version)
return repo_url, commit_sha
def get_golang_info(domain, module_name, version):
repo_url = ""
commit_sha = None
url = f"https://proxy.golang.org/{domain}/{module_name}/@v/{version}.info"
print("Version URL: " + url)
response = requests.get(url, timeout=2)
if response.status_code == 200:
data = response.json()
origin = data.get("Origin", None)
if origin is not None:
repo_url = origin.get("URL", None)