-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
1097 lines (903 loc) · 36.5 KB
/
__init__.py
File metadata and controls
1097 lines (903 loc) · 36.5 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
import json
import logging
from enum import Enum
from typing import Any, Dict, List, Optional, Union
from dataclasses import dataclass, asdict, field
import urllib.parse
from ..core.dedupe import Dedupe
from ..utils import IntegrationType, Utils
log = logging.getLogger("socketdev")
class SocketPURL_Type(str, Enum):
UNKNOWN = "unknown"
NPM = "npm"
PYPI = "pypi"
GOLANG = "golang"
class SocketIssueSeverity(str, Enum):
LOW = "low"
MIDDLE = "middle"
HIGH = "high"
CRITICAL = "critical"
class SocketCategory(str, Enum):
SUPPLY_CHAIN_RISK = "supplyChainRisk"
QUALITY = "quality"
MAINTENANCE = "maintenance"
VULNERABILITY = "vulnerability"
LICENSE = "license"
MISCELLANEOUS = "miscellaneous"
class DiffType(str, Enum):
ADDED = "added"
REMOVED = "removed"
UNCHANGED = "unchanged"
REPLACED = "replaced"
UPDATED = "updated"
class ScanType(str, Enum):
SOCKET = "socket"
SOCKET_TIER1 = "socket_tier1"
SOCKET_BASICS = "socket_basics"
@dataclass(kw_only=True)
class SocketPURL:
type: SocketPURL_Type
name: Optional[str] = None
namespace: Optional[str] = None
release: Optional[str] = None
subpath: Optional[str] = None
version: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketPURL":
return cls(
type=SocketPURL_Type(data["type"]),
name=data.get("name"),
namespace=data.get("namespace"),
release=data.get("release"),
subpath=data.get("subpath"),
version=data.get("version"),
)
@dataclass
class SocketManifestReference:
file: str
start: Optional[int] = None
end: Optional[int] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketManifestReference":
return cls(file=data["file"], start=data.get("start"), end=data.get("end"))
@dataclass
class FullScanParams:
repo: str
org_slug: Optional[str] = None
branch: Optional[str] = None
commit_message: Optional[str] = None
commit_hash: Optional[str] = None
pull_request: Optional[int] = None
committers: Optional[List[str]] = None
integration_type: Optional[IntegrationType] = None
integration_org_slug: Optional[str] = None
make_default_branch: Optional[bool] = None
set_as_pending_head: Optional[bool] = None
tmp: Optional[bool] = None
scan_type: Optional[ScanType] = None
workspace: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "FullScanParams":
integration_type = data.get("integration_type")
scan_type = data.get("scan_type")
return cls(
repo=data["repo"],
org_slug=data.get("org_slug"),
branch=data.get("branch"),
commit_message=data.get("commit_message"),
commit_hash=data.get("commit_hash"),
pull_request=data.get("pull_request"),
committers=data.get("committers"),
integration_type=integration_type if integration_type is not None else None,
integration_org_slug=data.get("integration_org_slug"),
make_default_branch=data.get("make_default_branch"),
set_as_pending_head=data.get("set_as_pending_head"),
tmp=data.get("tmp"),
scan_type=ScanType(scan_type) if scan_type is not None else None,
workspace=data.get("workspace"),
)
@dataclass
class FullScanMetadata:
id: str
created_at: str
updated_at: str
organization_id: str
repository_id: str
branch: str
html_report_url: str
repo: Optional[str] = None
organization_slug: Optional[str] = None
committers: Optional[List[str]] = None
commit_message: Optional[str] = None
commit_hash: Optional[str] = None
pull_request: Optional[int] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "FullScanMetadata":
return cls(
id=data["id"],
created_at=data["created_at"],
updated_at=data["updated_at"],
organization_id=data["organization_id"],
repository_id=data["repository_id"],
branch=data["branch"],
html_report_url=data["html_report_url"],
repo=data.get("repo"),
organization_slug=data.get("organization_slug"),
committers=data.get("committers"),
commit_message=data.get("commit_message"),
commit_hash=data.get("commit_hash"),
pull_request=data.get("pull_request"),
)
@dataclass
class CreateFullScanResponse:
success: bool
status: int
data: Optional[FullScanMetadata] = None
message: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "CreateFullScanResponse":
data_value = data.get("data")
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanMetadata.from_dict(data_value) if data_value else None,
)
@dataclass
class GetFullScanMetadataResponse:
success: bool
status: int
data: Optional[FullScanMetadata] = None
message: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "GetFullScanMetadataResponse":
data_value = data.get("data")
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanMetadata.from_dict(data_value) if data_value else None,
)
@dataclass(kw_only=True)
class SocketArtifactLink:
topLevelAncestors: List[str]
direct: bool = False
artifact: Optional[Dict] = None
dependencies: Optional[List[str]] = None
manifestFiles: Optional[List[SocketManifestReference]] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketArtifactLink":
manifest_files = data.get("manifestFiles")
direct_val = data.get("direct", False)
return cls(
topLevelAncestors=data["topLevelAncestors"],
direct=direct_val if isinstance(direct_val, bool) else direct_val.lower() == "true",
artifact=data.get("artifact"),
dependencies=data.get("dependencies"),
manifestFiles=[SocketManifestReference.from_dict(m) for m in manifest_files] if manifest_files else None,
)
@dataclass
class SocketScore:
supplyChain: float
quality: float
maintenance: float
vulnerability: float
license: float
overall: float
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketScore":
return cls(
supplyChain=data["supplyChain"],
quality=data["quality"],
maintenance=data["maintenance"],
vulnerability=data["vulnerability"],
license=data["license"],
overall=data["overall"],
)
@dataclass
class SecurityCapabilities:
env: bool
eval: bool
fs: bool
net: bool
shell: bool
unsafe: bool
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SecurityCapabilities":
return cls(
env=data["env"],
eval=data["eval"],
fs=data["fs"],
net=data["net"],
shell=data["shell"],
unsafe=data["unsafe"],
)
@dataclass
class Alert:
key: str
type: int
file: str
start: int
end: int
props: Dict[str, Any]
action: str
actionPolicyIndex: int
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "Alert":
return cls(
key=data["key"],
type=data["type"],
file=data["file"],
start=data["start"],
end=data["end"],
props=data["props"],
action=data["action"],
actionPolicyIndex=data["actionPolicyIndex"],
)
@dataclass
class LicenseMatch:
licenseId: str
licenseExceptionId: str
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "LicenseMatch":
return cls(licenseId=data["licenseId"], licenseExceptionId=data["licenseExceptionId"])
@dataclass
class LicenseDetail:
authors: List[str]
errorData: str
filepath: str
match_strength: int
provenance: str
spdxDisj: List[List[LicenseMatch]]
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "LicenseDetail":
return cls(
spdxDisj=data["spdxDisj"],
authors=data["authors"],
errorData=data["errorData"],
provenance=data["provenance"],
filepath=data["filepath"],
match_strength=data["match_strength"],
)
@dataclass
class AttributionData:
purl: str
foundAuthors: List[str]
foundInFilepath: Optional[str] = None
spdxExpr: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "AttributionData":
return cls(
purl=data["purl"],
foundAuthors=data["foundAuthors"],
foundInFilepath=data.get("foundInFilepath"),
spdxExpr=data.get("spdxExpr"),
)
@dataclass
class LicenseAttribution:
attribText: str
attribData: List[AttributionData]
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "LicenseAttribution":
return cls(
attribText=data["attribText"], attribData=[AttributionData.from_dict(item) for item in data["attribData"]]
)
@dataclass
class SocketAlert:
key: str
type: str
severity: SocketIssueSeverity
category: SocketCategory
file: Optional[str] = None
start: Optional[int] = None
end: Optional[int] = None
props: Optional[Dict[str, Any]] = None
action: Optional[str] = None
actionPolicyIndex: Optional[int] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketAlert":
return cls(
key=data["key"],
type=data["type"],
severity=SocketIssueSeverity(data["severity"]),
category=SocketCategory(data["category"]),
file=data.get("file"),
start=data.get("start"),
end=data.get("end"),
props=data.get("props"),
action=data.get("action"),
actionPolicyIndex=data.get("actionPolicyIndex"),
)
@dataclass
class DiffArtifact:
diffType: DiffType
id: str
type: str
name: str
licenseDetails: List[LicenseDetail]
version: Optional[str] = None
score: Optional[SocketScore] = None
author: List[str] = field(default_factory=list)
alerts: List[SocketAlert] = field(default_factory=list)
license: Optional[str] = None
files: Optional[str] = None
capabilities: Optional[SecurityCapabilities] = None
base: Optional[List[SocketArtifactLink]] = None
head: Optional[List[SocketArtifactLink]] = None
namespace: Optional[str] = None
subpath: Optional[str] = None
artifact_id: Optional[str] = None
artifactId: Optional[str] = None
qualifiers: Optional[Dict[str, Any]] = None
size: Optional[int] = None
state: Optional[str] = None
error: Optional[str] = None
licenseAttrib: Optional[List[LicenseAttribution]] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "DiffArtifact":
base_data = data.get("base")
head_data = data.get("head")
score_data = data.get("score") or data.get("scores")
score = SocketScore.from_dict(score_data) if score_data else None
license_details_source = data.get("licenseDetails")
if license_details_source:
license_details = [LicenseDetail.from_dict(detail) for detail in license_details_source]
else:
license_details = []
license_attrib_source = data.get("licenseAttrib")
if license_attrib_source:
license_attrib = [LicenseAttribution.from_dict(attrib) for attrib in license_attrib_source]
else:
license_attrib = []
return cls(
diffType=DiffType(data["diffType"]),
id=data["id"],
type=data["type"],
name=data["name"],
score=score,
version=data.get("version"),
alerts=[SocketAlert.from_dict(alert) for alert in data.get("alerts", [])],
licenseDetails=license_details,
files=data.get("files"),
license=data.get("license"),
capabilities=SecurityCapabilities.from_dict(data["capabilities"]) if data.get("capabilities") else None,
base=[SocketArtifactLink.from_dict(b) for b in base_data] if base_data else None,
head=[SocketArtifactLink.from_dict(h) for h in head_data] if head_data else None,
namespace=data.get("namespace"),
subpath=data.get("subpath"),
artifact_id=data.get("artifact_id"),
artifactId=data.get("artifactId"),
qualifiers=data.get("qualifiers"),
size=data.get("size"),
author=data.get("author", []),
state=data.get("state"),
error=data.get("error"),
licenseAttrib=license_attrib
if data.get("licenseAttrib")
else None,
)
@dataclass
class DiffArtifacts:
added: List[DiffArtifact]
removed: List[DiffArtifact]
unchanged: List[DiffArtifact]
replaced: List[DiffArtifact]
updated: List[DiffArtifact]
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "DiffArtifacts":
return cls(
added=[DiffArtifact.from_dict(a) for a in data["added"]],
removed=[DiffArtifact.from_dict(a) for a in data["removed"]],
unchanged=[DiffArtifact.from_dict(a) for a in data["unchanged"]],
replaced=[DiffArtifact.from_dict(a) for a in data["replaced"]],
updated=[DiffArtifact.from_dict(a) for a in data["updated"]],
)
@dataclass
class CommitInfo:
repository_id: str
branch: str
id: str
organization_id: str
committers: List[str]
commit_message: Optional[str] = None
commit_hash: Optional[str] = None
pull_request: Optional[int] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "CommitInfo":
return cls(
repository_id=data["repository_id"],
branch=data["branch"],
id=data["id"],
organization_id=data["organization_id"],
committers=data["committers"],
commit_message=data.get("commit_message"),
commit_hash=data.get("commit_hash"),
pull_request=data.get("pull_request"),
)
@dataclass
class FullScanDiffReport:
before: CommitInfo
after: CommitInfo
diff_report_url: str
artifacts: DiffArtifacts
directDependenciesChanged: bool = False
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "FullScanDiffReport":
return cls(
before=CommitInfo.from_dict(data["before"]),
after=CommitInfo.from_dict(data["after"]),
directDependenciesChanged=data.get("directDependenciesChanged", False),
diff_report_url=data["diff_report_url"],
artifacts=DiffArtifacts.from_dict(data["artifacts"]),
)
@dataclass
class StreamDiffResponse:
success: bool
status: int
data: Optional[FullScanDiffReport] = None
message: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "StreamDiffResponse":
data_value = data.get("data")
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanDiffReport.from_dict(data_value) if data_value else None,
)
@dataclass(kw_only=True)
class SocketArtifact(SocketPURL, SocketArtifactLink):
id: str
alerts: List[SocketAlert]
score: Optional[SocketScore] = None
author: Optional[List[str]] = field(default_factory=list)
batchIndex: Optional[int] = None
license: Optional[str] = None
licenseAttrib: Optional[List[LicenseAttribution]] = field(default_factory=list)
licenseDetails: Optional[List[LicenseDetail]] = field(default_factory=list)
size: Optional[int] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "SocketArtifact":
# Extract PURL fields
purl_type = data.get("type")
purl_data = {
"type": SocketPURL_Type(purl_type) if purl_type else SocketPURL_Type.UNKNOWN,
"name": data.get("name"),
"namespace": data.get("namespace"),
"release": data.get("release"),
"subpath": data.get("subpath"),
"version": data.get("version"),
}
# Extract Link fields
link_data = {
"topLevelAncestors": data.get("topLevelAncestors", []),
"direct": data.get("direct", False),
"artifact": data.get("artifact"),
"dependencies": data.get("dependencies"),
"manifestFiles": [SocketManifestReference.from_dict(m) for m in data["manifestFiles"]] if data.get("manifestFiles") else None,
}
alerts = data.get("alerts")
license_attrib = data.get("licenseAttrib")
license_details = data.get("licenseDetails")
score = data.get("score")
return cls(
**purl_data,
**link_data,
id=data["id"],
alerts=[SocketAlert.from_dict(a) for a in alerts] if alerts is not None else [],
author=data.get("author"),
batchIndex=data.get("batchIndex"),
license=data.get("license"),
licenseAttrib=[LicenseAttribution.from_dict(la) for la in license_attrib] if license_attrib else None,
licenseDetails=[LicenseDetail.from_dict(ld) for ld in license_details] if license_details else None,
score=SocketScore.from_dict(score) if score else None,
size=data.get("size"),
)
@dataclass
class FullScanStreamResponse:
success: bool
status: int
artifacts: Optional[Dict[str, SocketArtifact]] = None
message: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "FullScanStreamResponse":
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
artifacts={k: SocketArtifact.from_dict(v) for k, v in data["artifacts"].items()}
if data.get("artifacts")
else None,
)
class FullScans:
def __init__(self, api):
self.api = api
def get(self, org_slug: str, params: dict, use_types: bool = False) -> Union[dict, GetFullScanMetadataResponse]:
# Check if this is a request for a specific scan by ID
if 'id' in params and len(params) == 1:
# Get specific scan by ID: /orgs/{org_slug}/full-scans/{full_scan_id}
scan_id = params['id']
path = f"orgs/{org_slug}/full-scans/{scan_id}"
else:
# List scans with query parameters: /orgs/{org_slug}/full-scans?params
params_arg = urllib.parse.urlencode(params)
path = "orgs/" + org_slug + "/full-scans?" + str(params_arg)
response = self.api.do_request(path=path)
if response.status_code == 200:
result = response.json()
if use_types:
return GetFullScanMetadataResponse.from_dict({"success": True, "status": 200, "data": result})
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error getting full scan metadata: {response.status_code}, message: {error_message}")
if use_types:
return GetFullScanMetadataResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def post(
self,
files: list,
params: FullScanParams,
use_types: bool = False,
use_lazy_loading: bool = False,
workspace: Optional[str] = None,
max_open_files: int = 100,
base_path: Optional[str] = None,
base_paths: Optional[List[str]] = None
) -> Union[dict, CreateFullScanResponse]:
"""
Create a new full scan by uploading manifest files.
Args:
files: List of file paths to upload for scanning
params: FullScanParams object containing scan configuration
use_types: Whether to return typed response objects (default: False)
use_lazy_loading: Whether to use lazy file loading to prevent "too many open files"
errors when uploading large numbers of files (default: False)
NOTE: In version 3.0, this will default to True for better performance
workspace: Base directory path to make file paths relative to
max_open_files: Maximum number of files to keep open simultaneously when using
lazy loading. Useful for systems with low ulimit values (default: 100)
base_path: Optional base path to strip from key names for cleaner file organization
base_paths: Optional list of base paths to strip from key names (takes precedence over base_path)
Returns:
dict or CreateFullScanResponse: API response containing scan results
Note:
When use_lazy_loading=True, files are opened only when needed during upload,
preventing file descriptor exhaustion. The max_open_files parameter controls how many
files can be open simultaneously - set this lower on systems with restrictive ulimits.
For large file uploads (>100 files), it's recommended to set use_lazy_loading=True.
"""
Utils.validate_integration_type(params.integration_type if params.integration_type else "api")
org_slug = str(params.org_slug)
params_dict = params.to_dict()
params_dict.pop("org_slug")
# Remove pull_request param if it's None, 0, or not an integer
if hasattr(params, 'pull_request') and (
params.pull_request is None or
not isinstance(params.pull_request, int) or
params.pull_request == 0
):
print("Removing pull_request param from FullScanParams as it is None, 0, or not an integer")
params_dict.pop("pull_request")
if hasattr(params, 'workspace') and params.workspace is None:
print("Removing workspace param from FullScanParams as it is None")
params_dict.pop("workspace")
params_arg = urllib.parse.urlencode(params_dict)
path = "orgs/" + org_slug + "/full-scans?" + str(params_arg)
# Use lazy loading if requested
if use_lazy_loading:
prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files, base_path, base_paths)
else:
prepared_files = files
response = self.api.do_request(path=path, method="POST", files=prepared_files)
if response.status_code == 201:
result = response.json()
if use_types:
return CreateFullScanResponse.from_dict({"success": True, "status": 201, "data": result})
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error posting {files} to the Fullscans API: {response.status_code}, message: {error_message}")
if use_types:
return CreateFullScanResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def delete(self, org_slug: str, full_scan_id: str) -> dict:
path = "orgs/" + org_slug + "/full-scans/" + full_scan_id
response = self.api.do_request(path=path, method="DELETE")
if response.status_code == 200:
result = response.json()
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error deleting full scan: {response.status_code}, message: {error_message}")
return {}
def stream_diff(
self,
org_slug: str,
before: str,
after: str,
use_types: bool = True,
include_license_details: str = "true",
**kwargs,
) -> Union[dict, StreamDiffResponse]:
path = f"orgs/{org_slug}/full-scans/diff?before={before}&after={after}&include_license_details={include_license_details}"
if kwargs:
for key, value in kwargs.items():
path += f"&{key}={value}"
response = self.api.do_request(path=path, method="GET")
if response.status_code == 200:
result = response.json()
if use_types:
return StreamDiffResponse.from_dict({"success": True, "status": 200, "data": result})
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error streaming diff: {response.status_code}, message: {error_message}")
if use_types:
return StreamDiffResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def stream(self, org_slug: str, full_scan_id: str, use_types: bool = False) -> Union[dict, FullScanStreamResponse]:
path = "orgs/" + org_slug + "/full-scans/" + full_scan_id
response = self.api.do_request(path=path, method="GET")
if response.status_code == 200:
try:
stream_str = []
artifacts = {}
result = response.text
result = result.strip('"').strip()
for line in result.split("\n"):
if line != '"' and line != "" and line is not None:
item = json.loads(line)
stream_str.append(item)
stream_deduped = Dedupe.dedupe(stream_str, batched=False)
for batch in stream_deduped:
artifacts[batch["id"]] = batch
if use_types:
return FullScanStreamResponse.from_dict({"success": True, "status": 200, "artifacts": artifacts})
return artifacts
except Exception as e:
error_message = f"Error parsing stream response: {str(e)}"
log.error(error_message)
if use_types:
return FullScanStreamResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error streaming full scan: {response.status_code}, message: {error_message}")
if use_types:
return FullScanStreamResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def metadata(
self, org_slug: str, full_scan_id: str, use_types: bool = False
) -> Union[dict, GetFullScanMetadataResponse]:
path = "orgs/" + org_slug + "/full-scans/" + full_scan_id + "/metadata"
response = self.api.do_request(path=path, method="GET")
if response.status_code == 200:
result = response.json()
if use_types:
return GetFullScanMetadataResponse.from_dict({"success": True, "status": 200, "data": result})
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error getting metadata: {response.status_code}, message: {error_message}")
if use_types:
return GetFullScanMetadataResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def gfm(self, org_slug: str, before: str, after: str) -> dict:
path = "orgs/" + org_slug + f"/full-scans/diff/gfm?before={before}&after={after}"
response = self.api.do_request(path=path, method="GET")
if response.status_code == 200:
result = response.json()
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error getting diff scan results: {response.status_code}, message: {error_message}")
return {}
def finalize_tier1(
self,
full_scan_id: str,
tier1_reachability_scan_id: str,
) -> bool:
"""
Finalize a tier 1 reachability scan by associating it with a full scan.
Args:
full_scan_id: The ID of the full scan to associate with the tier 1 scan
tier1_reachability_scan_id: The tier 1 reachability scan ID from the facts file
Returns:
True if successful, False otherwise
"""
path = "tier1-reachability-scan/finalize"
payload = json.dumps({
"tier1_reachability_scan_id": tier1_reachability_scan_id,
"report_run_id": full_scan_id
})
response = self.api.do_request(
path=path,
method="POST",
payload=payload
)
if response.status_code in (200, 201, 204):
return True
return False
def archive(self, tar_files: Optional[Union[str, List[str]]] = None, files: Optional[List[str]] = None, workspace: Optional[str] = None, use_lazy_loading: bool = True, params: Optional[FullScanParams] = None) -> dict:
"""
Create a full scan by uploading one or more archives.
Supported archive formats include .tar, .tar.gz/.tgz, and .zip.
Args:
tar_files: Path(s) to archive file(s) to upload (.tar, .tar.gz, .tgz, or .zip)
Can be a single string or a list of strings
files: List of files to bundle into a .tar.gz and upload (alternative to tar_files)
workspace: Base directory path to make file paths relative to when creating tar.gz
use_lazy_loading: Whether to use lazy file loading (default: True)
params: FullScanParams object containing scan configuration (repo, org_slug, branch,
commit_message, commit_hash, pull_request, committers, integration_type,
integration_org_slug, make_default_branch, set_as_pending_head, tmp)