socketdev 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,888 @@
1
+ import json
2
+ import logging
3
+ from enum import Enum
4
+ from typing import Any, Dict, List, Optional, Union
5
+ from dataclasses import dataclass, asdict, field
6
+ import urllib.parse
7
+ from ..core.dedupe import Dedupe
8
+ from ..utils import IntegrationType, Utils
9
+
10
+ log = logging.getLogger("socketdev")
11
+
12
+
13
+ class SocketPURL_Type(str, Enum):
14
+ UNKNOWN = "unknown"
15
+ NPM = "npm"
16
+ PYPI = "pypi"
17
+ GOLANG = "golang"
18
+
19
+
20
+ class SocketIssueSeverity(str, Enum):
21
+ LOW = "low"
22
+ MIDDLE = "middle"
23
+ HIGH = "high"
24
+ CRITICAL = "critical"
25
+
26
+
27
+ class SocketCategory(str, Enum):
28
+ SUPPLY_CHAIN_RISK = "supplyChainRisk"
29
+ QUALITY = "quality"
30
+ MAINTENANCE = "maintenance"
31
+ VULNERABILITY = "vulnerability"
32
+ LICENSE = "license"
33
+ MISCELLANEOUS = "miscellaneous"
34
+
35
+
36
+ class DiffType(str, Enum):
37
+ ADDED = "added"
38
+ REMOVED = "removed"
39
+ UNCHANGED = "unchanged"
40
+ REPLACED = "replaced"
41
+ UPDATED = "updated"
42
+
43
+
44
+ @dataclass(kw_only=True)
45
+ class SocketPURL:
46
+ type: SocketPURL_Type
47
+ name: Optional[str] = None
48
+ namespace: Optional[str] = None
49
+ release: Optional[str] = None
50
+ subpath: Optional[str] = None
51
+ version: Optional[str] = None
52
+
53
+ def __getitem__(self, key):
54
+ return getattr(self, key)
55
+
56
+ def to_dict(self):
57
+ return asdict(self)
58
+
59
+ @classmethod
60
+ def from_dict(cls, data: dict) -> "SocketPURL":
61
+ return cls(
62
+ type=SocketPURL_Type(data["type"]),
63
+ name=data.get("name"),
64
+ namespace=data.get("namespace"),
65
+ release=data.get("release"),
66
+ subpath=data.get("subpath"),
67
+ version=data.get("version"),
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class SocketManifestReference:
73
+ file: str
74
+ start: Optional[int] = None
75
+ end: Optional[int] = None
76
+
77
+ def __getitem__(self, key):
78
+ return getattr(self, key)
79
+
80
+ def to_dict(self):
81
+ return asdict(self)
82
+
83
+ @classmethod
84
+ def from_dict(cls, data: dict) -> "SocketManifestReference":
85
+ return cls(file=data["file"], start=data.get("start"), end=data.get("end"))
86
+
87
+
88
+ @dataclass
89
+ class FullScanParams:
90
+ repo: str
91
+ org_slug: Optional[str] = None
92
+ branch: Optional[str] = None
93
+ commit_message: Optional[str] = None
94
+ commit_hash: Optional[str] = None
95
+ pull_request: Optional[int] = None
96
+ committers: Optional[List[str]] = None
97
+ integration_type: Optional[IntegrationType] = None
98
+ integration_org_slug: Optional[str] = None
99
+ make_default_branch: Optional[bool] = None
100
+ set_as_pending_head: Optional[bool] = None
101
+ tmp: Optional[bool] = None
102
+
103
+ def __getitem__(self, key):
104
+ return getattr(self, key)
105
+
106
+ def to_dict(self):
107
+ return asdict(self)
108
+
109
+ @classmethod
110
+ def from_dict(cls, data: dict) -> "FullScanParams":
111
+ integration_type = data.get("integration_type")
112
+ return cls(
113
+ repo=data["repo"],
114
+ org_slug=data.get("org_slug"),
115
+ branch=data.get("branch"),
116
+ commit_message=data.get("commit_message"),
117
+ commit_hash=data.get("commit_hash"),
118
+ pull_request=data.get("pull_request"),
119
+ committers=data.get("committers"),
120
+ integration_type=IntegrationType(integration_type) if integration_type else None,
121
+ integration_org_slug=data.get("integration_org_slug"),
122
+ make_default_branch=data.get("make_default_branch"),
123
+ set_as_pending_head=data.get("set_as_pending_head"),
124
+ tmp=data.get("tmp"),
125
+ )
126
+
127
+
128
+ @dataclass
129
+ class FullScanMetadata:
130
+ id: str
131
+ created_at: str
132
+ updated_at: str
133
+ organization_id: str
134
+ repository_id: str
135
+ branch: str
136
+ html_report_url: str
137
+ repo: Optional[str] = None
138
+ organization_slug: Optional[str] = None
139
+ committers: Optional[List[str]] = None
140
+ commit_message: Optional[str] = None
141
+ commit_hash: Optional[str] = None
142
+ pull_request: Optional[int] = None
143
+
144
+ def __getitem__(self, key):
145
+ return getattr(self, key)
146
+
147
+ def to_dict(self):
148
+ return asdict(self)
149
+
150
+ @classmethod
151
+ def from_dict(cls, data: dict) -> "FullScanMetadata":
152
+ return cls(
153
+ id=data["id"],
154
+ created_at=data["created_at"],
155
+ updated_at=data["updated_at"],
156
+ organization_id=data["organization_id"],
157
+ repository_id=data["repository_id"],
158
+ branch=data["branch"],
159
+ html_report_url=data["html_report_url"],
160
+ repo=data.get("repo"),
161
+ organization_slug=data.get("organization_slug"),
162
+ committers=data.get("committers"),
163
+ commit_message=data.get("commit_message"),
164
+ commit_hash=data.get("commit_hash"),
165
+ pull_request=data.get("pull_request"),
166
+ )
167
+
168
+
169
+ @dataclass
170
+ class CreateFullScanResponse:
171
+ success: bool
172
+ status: int
173
+ data: Optional[FullScanMetadata] = None
174
+ message: Optional[str] = None
175
+
176
+ def __getitem__(self, key):
177
+ return getattr(self, key)
178
+
179
+ def to_dict(self):
180
+ return asdict(self)
181
+
182
+ @classmethod
183
+ def from_dict(cls, data: dict) -> "CreateFullScanResponse":
184
+ return cls(
185
+ success=data["success"],
186
+ status=data["status"],
187
+ message=data.get("message"),
188
+ data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") else None,
189
+ )
190
+
191
+
192
+ @dataclass
193
+ class GetFullScanMetadataResponse:
194
+ success: bool
195
+ status: int
196
+ data: Optional[FullScanMetadata] = None
197
+ message: Optional[str] = None
198
+
199
+ def __getitem__(self, key):
200
+ return getattr(self, key)
201
+
202
+ def to_dict(self):
203
+ return asdict(self)
204
+
205
+ @classmethod
206
+ def from_dict(cls, data: dict) -> "GetFullScanMetadataResponse":
207
+ return cls(
208
+ success=data["success"],
209
+ status=data["status"],
210
+ message=data.get("message"),
211
+ data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") else None,
212
+ )
213
+
214
+
215
+ @dataclass(kw_only=True)
216
+ class SocketArtifactLink:
217
+ topLevelAncestors: List[str]
218
+ direct: bool = False
219
+ artifact: Optional[Dict] = None
220
+ dependencies: Optional[List[str]] = None
221
+ manifestFiles: Optional[List[SocketManifestReference]] = None
222
+
223
+ def __getitem__(self, key):
224
+ return getattr(self, key)
225
+
226
+ def to_dict(self):
227
+ return asdict(self)
228
+
229
+ @classmethod
230
+ def from_dict(cls, data: dict) -> "SocketArtifactLink":
231
+ manifest_files = data.get("manifestFiles")
232
+ direct_val = data.get("direct", False)
233
+ return cls(
234
+ topLevelAncestors=data["topLevelAncestors"],
235
+ direct=direct_val if isinstance(direct_val, bool) else direct_val.lower() == "true",
236
+ artifact=data.get("artifact"),
237
+ dependencies=data.get("dependencies"),
238
+ manifestFiles=[SocketManifestReference.from_dict(m) for m in manifest_files] if manifest_files else None,
239
+ )
240
+
241
+
242
+ @dataclass
243
+ class SocketScore:
244
+ supplyChain: float
245
+ quality: float
246
+ maintenance: float
247
+ vulnerability: float
248
+ license: float
249
+ overall: float
250
+
251
+ def __getitem__(self, key):
252
+ return getattr(self, key)
253
+
254
+ def to_dict(self):
255
+ return asdict(self)
256
+
257
+ @classmethod
258
+ def from_dict(cls, data: dict) -> "SocketScore":
259
+ return cls(
260
+ supplyChain=data["supplyChain"],
261
+ quality=data["quality"],
262
+ maintenance=data["maintenance"],
263
+ vulnerability=data["vulnerability"],
264
+ license=data["license"],
265
+ overall=data["overall"],
266
+ )
267
+
268
+
269
+ @dataclass
270
+ class SecurityCapabilities:
271
+ env: bool
272
+ eval: bool
273
+ fs: bool
274
+ net: bool
275
+ shell: bool
276
+ unsafe: bool
277
+
278
+ def __getitem__(self, key):
279
+ return getattr(self, key)
280
+
281
+ def to_dict(self):
282
+ return asdict(self)
283
+
284
+ @classmethod
285
+ def from_dict(cls, data: dict) -> "SecurityCapabilities":
286
+ return cls(
287
+ env=data["env"],
288
+ eval=data["eval"],
289
+ fs=data["fs"],
290
+ net=data["net"],
291
+ shell=data["shell"],
292
+ unsafe=data["unsafe"],
293
+ )
294
+
295
+
296
+ @dataclass
297
+ class Alert:
298
+ key: str
299
+ type: int
300
+ file: str
301
+ start: int
302
+ end: int
303
+ props: Dict[str, Any]
304
+ action: str
305
+ actionPolicyIndex: int
306
+
307
+ def __getitem__(self, key):
308
+ return getattr(self, key)
309
+
310
+ def to_dict(self):
311
+ return asdict(self)
312
+
313
+ @classmethod
314
+ def from_dict(cls, data: dict) -> "Alert":
315
+ return cls(
316
+ key=data["key"],
317
+ type=data["type"],
318
+ file=data["file"],
319
+ start=data["start"],
320
+ end=data["end"],
321
+ props=data["props"],
322
+ action=data["action"],
323
+ actionPolicyIndex=data["actionPolicyIndex"],
324
+ )
325
+
326
+
327
+ @dataclass
328
+ class LicenseMatch:
329
+ licenseId: str
330
+ licenseExceptionId: str
331
+
332
+ def __getitem__(self, key):
333
+ return getattr(self, key)
334
+
335
+ def to_dict(self):
336
+ return asdict(self)
337
+
338
+ @classmethod
339
+ def from_dict(cls, data: dict) -> "LicenseMatch":
340
+ return cls(licenseId=data["licenseId"], licenseExceptionId=data["licenseExceptionId"])
341
+
342
+
343
+ @dataclass
344
+ class LicenseDetail:
345
+ authors: List[str]
346
+ errorData: str
347
+ filepath: str
348
+ match_strength: int
349
+ provenance: str
350
+ spdxDisj: List[List[LicenseMatch]]
351
+
352
+ def __getitem__(self, key):
353
+ return getattr(self, key)
354
+
355
+ def to_dict(self):
356
+ return asdict(self)
357
+
358
+ @classmethod
359
+ def from_dict(cls, data: dict) -> "LicenseDetail":
360
+ return cls(
361
+ spdxDisj=data["spdxDisj"],
362
+ authors=data["authors"],
363
+ errorData=data["errorData"],
364
+ provenance=data["provenance"],
365
+ filepath=data["filepath"],
366
+ match_strength=data["match_strength"],
367
+
368
+ )
369
+
370
+
371
+ @dataclass
372
+ class AttributionData:
373
+ purl: str
374
+ foundAuthors: List[str]
375
+ foundInFilepath: Optional[str] = None
376
+ spdxExpr: Optional[str] = None
377
+
378
+ def __getitem__(self, key):
379
+ return getattr(self, key)
380
+
381
+ def to_dict(self):
382
+ return asdict(self)
383
+
384
+ @classmethod
385
+ def from_dict(cls, data: dict) -> "AttributionData":
386
+ return cls(
387
+ purl=data["purl"],
388
+ foundAuthors=data["foundAuthors"],
389
+ foundInFilepath=data.get("foundInFilepath"),
390
+ spdxExpr=data.get("spdxExpr"),
391
+ )
392
+
393
+
394
+ @dataclass
395
+ class LicenseAttribution:
396
+ attribText: str
397
+ attribData: List[AttributionData]
398
+
399
+ def __getitem__(self, key):
400
+ return getattr(self, key)
401
+
402
+ def to_dict(self):
403
+ return asdict(self)
404
+
405
+ @classmethod
406
+ def from_dict(cls, data: dict) -> "LicenseAttribution":
407
+ return cls(
408
+ attribText=data["attribText"], attribData=[AttributionData.from_dict(item) for item in data["attribData"]]
409
+ )
410
+
411
+
412
+ @dataclass
413
+ class SocketAlert:
414
+ key: str
415
+ type: str
416
+ severity: SocketIssueSeverity
417
+ category: SocketCategory
418
+ file: Optional[str] = None
419
+ start: Optional[int] = None
420
+ end: Optional[int] = None
421
+ props: Optional[Dict[str, Any]] = None
422
+ action: Optional[str] = None
423
+ actionPolicyIndex: Optional[int] = None
424
+
425
+ def __getitem__(self, key):
426
+ return getattr(self, key)
427
+
428
+ def to_dict(self):
429
+ return asdict(self)
430
+
431
+ @classmethod
432
+ def from_dict(cls, data: dict) -> "SocketAlert":
433
+ return cls(
434
+ key=data["key"],
435
+ type=data["type"],
436
+ severity=SocketIssueSeverity(data["severity"]),
437
+ category=SocketCategory(data["category"]),
438
+ file=data.get("file"),
439
+ start=data.get("start"),
440
+ end=data.get("end"),
441
+ props=data.get("props"),
442
+ action=data.get("action"),
443
+ actionPolicyIndex=data.get("actionPolicyIndex"),
444
+ )
445
+
446
+
447
+ @dataclass
448
+ class DiffArtifact:
449
+ diffType: DiffType
450
+ id: str
451
+ type: str
452
+ name: str
453
+ version: str
454
+ licenseDetails: List[LicenseDetail]
455
+ score: Optional[SocketScore] = None
456
+ author: List[str] = field(default_factory=list)
457
+ alerts: List[SocketAlert] = field(default_factory=list)
458
+ license: Optional[str] = None
459
+ files: Optional[str] = None
460
+ capabilities: Optional[SecurityCapabilities] = None
461
+ base: Optional[List[SocketArtifactLink]] = None
462
+ head: Optional[List[SocketArtifactLink]] = None
463
+ namespace: Optional[str] = None
464
+ subpath: Optional[str] = None
465
+ artifact_id: Optional[str] = None
466
+ artifactId: Optional[str] = None
467
+ qualifiers: Optional[Dict[str, Any]] = None
468
+ size: Optional[int] = None
469
+ state: Optional[str] = None
470
+ error: Optional[str] = None
471
+ licenseAttrib: Optional[List[LicenseAttribution]] = None
472
+
473
+ def __getitem__(self, key):
474
+ return getattr(self, key)
475
+
476
+ def to_dict(self):
477
+ return asdict(self)
478
+
479
+ @classmethod
480
+ def from_dict(cls, data: dict) -> "DiffArtifact":
481
+ base_data = data.get("base")
482
+ head_data = data.get("head")
483
+
484
+ score_data = data.get("score") or data.get("scores")
485
+ score = SocketScore.from_dict(score_data) if score_data else None
486
+ license_details_source = data.get("licenseDetails")
487
+ if license_details_source:
488
+ license_details = [LicenseDetail.from_dict(detail) for detail in license_details_source]
489
+ else:
490
+ license_details = []
491
+ license_attrib_source = data.get("licenseAttrib")
492
+ if license_attrib_source:
493
+ license_attrib = [LicenseAttribution.from_dict(attrib) for attrib in license_attrib_source]
494
+ else:
495
+ license_attrib = []
496
+
497
+ return cls(
498
+ diffType=DiffType(data["diffType"]),
499
+ id=data["id"],
500
+ type=data["type"],
501
+ name=data["name"],
502
+ score=score,
503
+ version=data["version"],
504
+ alerts=[SocketAlert.from_dict(alert) for alert in data.get("alerts", [])],
505
+ licenseDetails=license_details,
506
+ files=data.get("files"),
507
+ license=data.get("license"),
508
+ capabilities=SecurityCapabilities.from_dict(data["capabilities"]) if data.get("capabilities") else None,
509
+ base=[SocketArtifactLink.from_dict(b) for b in base_data] if base_data else None,
510
+ head=[SocketArtifactLink.from_dict(h) for h in head_data] if head_data else None,
511
+ namespace=data.get("namespace"),
512
+ subpath=data.get("subpath"),
513
+ artifact_id=data.get("artifact_id"),
514
+ artifactId=data.get("artifactId"),
515
+ qualifiers=data.get("qualifiers"),
516
+ size=data.get("size"),
517
+ author=data.get("author", []),
518
+ state=data.get("state"),
519
+ error=data.get("error"),
520
+ licenseAttrib=license_attrib
521
+ if data.get("licenseAttrib")
522
+ else None,
523
+ )
524
+
525
+
526
+ @dataclass
527
+ class DiffArtifacts:
528
+ added: List[DiffArtifact]
529
+ removed: List[DiffArtifact]
530
+ unchanged: List[DiffArtifact]
531
+ replaced: List[DiffArtifact]
532
+ updated: List[DiffArtifact]
533
+
534
+ def __getitem__(self, key):
535
+ return getattr(self, key)
536
+
537
+ def to_dict(self):
538
+ return asdict(self)
539
+
540
+ @classmethod
541
+ def from_dict(cls, data: dict) -> "DiffArtifacts":
542
+ return cls(
543
+ added=[DiffArtifact.from_dict(a) for a in data["added"]],
544
+ removed=[DiffArtifact.from_dict(a) for a in data["removed"]],
545
+ unchanged=[DiffArtifact.from_dict(a) for a in data["unchanged"]],
546
+ replaced=[DiffArtifact.from_dict(a) for a in data["replaced"]],
547
+ updated=[DiffArtifact.from_dict(a) for a in data["updated"]],
548
+ )
549
+
550
+
551
+ @dataclass
552
+ class CommitInfo:
553
+ repository_id: str
554
+ branch: str
555
+ id: str
556
+ organization_id: str
557
+ committers: List[str]
558
+ commit_message: Optional[str] = None
559
+ commit_hash: Optional[str] = None
560
+ pull_request: Optional[int] = None
561
+
562
+ def __getitem__(self, key):
563
+ return getattr(self, key)
564
+
565
+ def to_dict(self):
566
+ return asdict(self)
567
+
568
+ @classmethod
569
+ def from_dict(cls, data: dict) -> "CommitInfo":
570
+ return cls(
571
+ repository_id=data["repository_id"],
572
+ branch=data["branch"],
573
+ id=data["id"],
574
+ organization_id=data["organization_id"],
575
+ committers=data["committers"],
576
+ commit_message=data.get("commit_message"),
577
+ commit_hash=data.get("commit_hash"),
578
+ pull_request=data.get("pull_request"),
579
+ )
580
+
581
+
582
+ @dataclass
583
+ class FullScanDiffReport:
584
+ before: CommitInfo
585
+ after: CommitInfo
586
+ diff_report_url: str
587
+ artifacts: DiffArtifacts
588
+ directDependenciesChanged: bool = False
589
+
590
+ def __getitem__(self, key):
591
+ return getattr(self, key)
592
+
593
+ def to_dict(self):
594
+ return asdict(self)
595
+
596
+ @classmethod
597
+ def from_dict(cls, data: dict) -> "FullScanDiffReport":
598
+ return cls(
599
+ before=CommitInfo.from_dict(data["before"]),
600
+ after=CommitInfo.from_dict(data["after"]),
601
+ directDependenciesChanged=data.get("directDependenciesChanged", False),
602
+ diff_report_url=data["diff_report_url"],
603
+ artifacts=DiffArtifacts.from_dict(data["artifacts"]),
604
+ )
605
+
606
+
607
+ @dataclass
608
+ class StreamDiffResponse:
609
+ success: bool
610
+ status: int
611
+ data: Optional[FullScanDiffReport] = None
612
+ message: Optional[str] = None
613
+
614
+ def __getitem__(self, key):
615
+ return getattr(self, key)
616
+
617
+ def to_dict(self):
618
+ return asdict(self)
619
+
620
+ @classmethod
621
+ def from_dict(cls, data: dict) -> "StreamDiffResponse":
622
+ return cls(
623
+ success=data["success"],
624
+ status=data["status"],
625
+ message=data.get("message"),
626
+ data=FullScanDiffReport.from_dict(data.get("data")) if data.get("data") else None,
627
+ )
628
+
629
+
630
+ @dataclass(kw_only=True)
631
+ class SocketArtifact(SocketPURL, SocketArtifactLink):
632
+ id: str
633
+ alerts: List[SocketAlert]
634
+ score: SocketScore
635
+ author: Optional[List[str]] = field(default_factory=list)
636
+ batchIndex: Optional[int] = None
637
+ license: Optional[str] = None
638
+ licenseAttrib: Optional[List[LicenseAttribution]] = field(default_factory=list)
639
+ licenseDetails: Optional[List[LicenseDetail]] = field(default_factory=list)
640
+ size: Optional[int] = None
641
+
642
+ def __getitem__(self, key):
643
+ return getattr(self, key)
644
+
645
+ def to_dict(self):
646
+ return asdict(self)
647
+
648
+ @classmethod
649
+ def from_dict(cls, data: dict) -> "SocketArtifact":
650
+ purl_data = {k: data.get(k) for k in SocketPURL.__dataclass_fields__}
651
+ link_data = {k: data.get(k) for k in SocketArtifactLink.__dataclass_fields__}
652
+
653
+ alerts = data.get("alerts")
654
+ license_attrib = data.get("licenseAttrib")
655
+ license_details = data.get("licenseDetails")
656
+ score = data.get("score")
657
+
658
+ return cls(
659
+ **purl_data,
660
+ **link_data,
661
+ id=data["id"],
662
+ alerts=[SocketAlert.from_dict(a) for a in alerts] if alerts is not None else [],
663
+ author=data.get("author"),
664
+ batchIndex=data.get("batchIndex"),
665
+ license=data.get("license"),
666
+ licenseAttrib=[LicenseAttribution.from_dict(la) for la in license_attrib] if license_attrib else None,
667
+ licenseDetails=[LicenseDetail.from_dict(ld) for ld in license_details] if license_details else None,
668
+ score=SocketScore.from_dict(score) if score else None,
669
+ size=data.get("size"),
670
+ )
671
+
672
+
673
+ @dataclass
674
+ class FullScanStreamResponse:
675
+ success: bool
676
+ status: int
677
+ artifacts: Optional[Dict[str, SocketArtifact]] = None
678
+ message: Optional[str] = None
679
+
680
+ def __getitem__(self, key):
681
+ return getattr(self, key)
682
+
683
+ def to_dict(self):
684
+ return asdict(self)
685
+
686
+ @classmethod
687
+ def from_dict(cls, data: dict) -> "FullScanStreamResponse":
688
+ return cls(
689
+ success=data["success"],
690
+ status=data["status"],
691
+ message=data.get("message"),
692
+ artifacts={k: SocketArtifact.from_dict(v) for k, v in data["artifacts"].items()}
693
+ if data.get("artifacts")
694
+ else None,
695
+ )
696
+
697
+
698
+ class FullScans:
699
+ def __init__(self, api):
700
+ self.api = api
701
+
702
+
703
+ def get(self, org_slug: str, params: dict, use_types: bool = False) -> Union[dict, GetFullScanMetadataResponse]:
704
+ params_arg = urllib.parse.urlencode(params)
705
+ path = "orgs/" + org_slug + "/full-scans?" + str(params_arg)
706
+ response = self.api.do_request(path=path)
707
+
708
+ if response.status_code == 200:
709
+ result = response.json()
710
+ if use_types:
711
+ return GetFullScanMetadataResponse.from_dict({"success": True, "status": 200, "data": result})
712
+
713
+ return result
714
+
715
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
716
+ log.error(f"Error getting full scan metadata: {response.status_code}, message: {error_message}")
717
+ if use_types:
718
+ return GetFullScanMetadataResponse.from_dict(
719
+ {"success": False, "status": response.status_code, "message": error_message}
720
+ )
721
+ return {}
722
+
723
+ def post(self, files: list, params: FullScanParams, use_types: bool = False, use_lazy_loading: bool = False, workspace: str = None, max_open_files: int = 100) -> Union[dict, CreateFullScanResponse]:
724
+ """
725
+ Create a new full scan by uploading manifest files.
726
+
727
+ Args:
728
+ files: List of file paths to upload for scanning
729
+ params: FullScanParams object containing scan configuration
730
+ use_types: Whether to return typed response objects (default: False)
731
+ use_lazy_loading: Whether to use lazy file loading to prevent "too many open files"
732
+ errors when uploading large numbers of files (default: False)
733
+ NOTE: In version 3.0, this will default to True for better performance
734
+ workspace: Base directory path to make file paths relative to
735
+ max_open_files: Maximum number of files to keep open simultaneously when using
736
+ lazy loading. Useful for systems with low ulimit values (default: 100)
737
+
738
+ Returns:
739
+ dict or CreateFullScanResponse: API response containing scan results
740
+
741
+ Note:
742
+ When use_lazy_loading=True, files are opened only when needed during upload,
743
+ preventing file descriptor exhaustion. The max_open_files parameter controls how many
744
+ files can be open simultaneously - set this lower on systems with restrictive ulimits.
745
+
746
+ For large file uploads (>100 files), it's recommended to set use_lazy_loading=True.
747
+ """
748
+ Utils.validate_integration_type(params.integration_type if params.integration_type else "api")
749
+ org_slug = str(params.org_slug)
750
+ params_dict = params.to_dict()
751
+ params_dict.pop("org_slug")
752
+ params_arg = urllib.parse.urlencode(params_dict)
753
+ path = "orgs/" + org_slug + "/full-scans?" + str(params_arg)
754
+
755
+ # Use lazy loading if requested
756
+ if use_lazy_loading:
757
+ prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files)
758
+ else:
759
+ prepared_files = files
760
+
761
+ response = self.api.do_request(path=path, method="POST", files=prepared_files)
762
+
763
+ if response.status_code == 201:
764
+ result = response.json()
765
+ if use_types:
766
+ return CreateFullScanResponse.from_dict({"success": True, "status": 201, "data": result})
767
+ return result
768
+
769
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
770
+ log.error(f"Error posting {files} to the Fullscans API: {response.status_code}, message: {error_message}")
771
+ if use_types:
772
+ return CreateFullScanResponse.from_dict(
773
+ {"success": False, "status": response.status_code, "message": error_message}
774
+ )
775
+ return {}
776
+
777
+ def delete(self, org_slug: str, full_scan_id: str) -> dict:
778
+ path = "orgs/" + org_slug + "/full-scans/" + full_scan_id
779
+
780
+ response = self.api.do_request(path=path, method="DELETE")
781
+
782
+ if response.status_code == 200:
783
+ result = response.json()
784
+ return result
785
+
786
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
787
+ log.error(f"Error deleting full scan: {response.status_code}, message: {error_message}")
788
+ return {}
789
+
790
+ def stream_diff(
791
+ self,
792
+ org_slug: str,
793
+ before: str,
794
+ after: str,
795
+ use_types: bool = True,
796
+ include_license_details: str = "true",
797
+ **kwargs,
798
+ ) -> Union[dict, StreamDiffResponse]:
799
+ path = f"orgs/{org_slug}/full-scans/diff?before={before}&after={after}&include_license_details={include_license_details}"
800
+ if kwargs:
801
+ for key, value in kwargs.items():
802
+ path += f"&{key}={value}"
803
+
804
+ response = self.api.do_request(path=path, method="GET")
805
+
806
+ if response.status_code == 200:
807
+ result = response.json()
808
+ if use_types:
809
+ return StreamDiffResponse.from_dict({"success": True, "status": 200, "data": result})
810
+ return result
811
+
812
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
813
+ log.error(f"Error streaming diff: {response.status_code}, message: {error_message}")
814
+ if use_types:
815
+ return StreamDiffResponse.from_dict(
816
+ {"success": False, "status": response.status_code, "message": error_message}
817
+ )
818
+ return {}
819
+
820
+ def stream(self, org_slug: str, full_scan_id: str, use_types: bool = False) -> Union[dict, FullScanStreamResponse]:
821
+ path = "orgs/" + org_slug + "/full-scans/" + full_scan_id
822
+ response = self.api.do_request(path=path, method="GET")
823
+
824
+ if response.status_code == 200:
825
+ try:
826
+ stream_str = []
827
+ artifacts = {}
828
+ result = response.text
829
+ result = result.strip('"').strip()
830
+ for line in result.split("\n"):
831
+ if line != '"' and line != "" and line is not None:
832
+ item = json.loads(line)
833
+ stream_str.append(item)
834
+ stream_deduped = Dedupe.dedupe(stream_str, batched=False)
835
+ for batch in stream_deduped:
836
+ artifacts[batch["id"]] = batch
837
+ if use_types:
838
+ return FullScanStreamResponse.from_dict({"success": True, "status": 200, "artifacts": artifacts})
839
+ return artifacts
840
+
841
+ except Exception as e:
842
+ error_message = f"Error parsing stream response: {str(e)}"
843
+ log.error(error_message)
844
+ if use_types:
845
+ return FullScanStreamResponse.from_dict(
846
+ {"success": False, "status": response.status_code, "message": error_message}
847
+ )
848
+ return {}
849
+
850
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
851
+ log.error(f"Error streaming full scan: {response.status_code}, message: {error_message}")
852
+ if use_types:
853
+ return FullScanStreamResponse.from_dict(
854
+ {"success": False, "status": response.status_code, "message": error_message}
855
+ )
856
+ return {}
857
+
858
+ def metadata(
859
+ self, org_slug: str, full_scan_id: str, use_types: bool = False
860
+ ) -> Union[dict, GetFullScanMetadataResponse]:
861
+ path = "orgs/" + org_slug + "/full-scans/" + full_scan_id + "/metadata"
862
+
863
+ response = self.api.do_request(path=path, method="GET")
864
+
865
+ if response.status_code == 200:
866
+ result = response.json()
867
+ if use_types:
868
+ return GetFullScanMetadataResponse.from_dict({"success": True, "status": 200, "data": result})
869
+ return result
870
+
871
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
872
+ log.error(f"Error getting metadata: {response.status_code}, message: {error_message}")
873
+ if use_types:
874
+ return GetFullScanMetadataResponse.from_dict(
875
+ {"success": False, "status": response.status_code, "message": error_message}
876
+ )
877
+ return {}
878
+
879
+ def gfm(self, org_slug: str, before: str, after: str) -> dict:
880
+ path = "orgs/" + org_slug + f"/full-scans/diff/gfm?before={before}&after={after}"
881
+ response = self.api.do_request(path=path, method="GET")
882
+ if response.status_code == 200:
883
+ result = response.json()
884
+ return result
885
+
886
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
887
+ log.error(f"Error getting diff scan results: {response.status_code}, message: {error_message}")
888
+ return {}