-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__init__.py
850 lines (700 loc) · 26 KB
/
__init__.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
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"
@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
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")
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=IntegrationType(integration_type) if integration_type 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"),
)
@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":
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") 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":
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") 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]
charEnd: int
charStart: int
filepath: str
match_strength: int
filehash: str
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(
authors=data["authors"],
charEnd=data["charEnd"],
charStart=data["charStart"],
filepath=data["filepath"],
match_strength=data["match_strength"],
filehash=data["filehash"],
provenance=data["provenance"],
spdxDisj=[[LicenseMatch.from_dict(match) for match in group] for group in data["spdxDisj"]],
)
@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
version: str
licenseDetails: List[LicenseDetail]
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["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":
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=FullScanDiffReport.from_dict(data.get("data")) if data.get("data") else None,
)
@dataclass(kw_only=True)
class SocketArtifact(SocketPURL, SocketArtifactLink):
id: str
alerts: List[SocketAlert]
score: SocketScore
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":
purl_data = {k: data.get(k) for k in SocketPURL.__dataclass_fields__}
link_data = {k: data.get(k) for k in SocketArtifactLink.__dataclass_fields__}
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]:
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) -> Union[dict, CreateFullScanResponse]:
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")
params_arg = urllib.parse.urlencode(params_dict)
path = "orgs/" + org_slug + "/full-scans?" + str(params_arg)
response = self.api.do_request(path=path, method="POST", files=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: bool = False,
**kwargs,
) -> Union[dict, StreamDiffResponse]:
path = f"orgs/{org_slug}/full-scans/diff?before={before}&after={after}&{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 {}