socketdev 3.0.21__py3-none-any.whl → 3.0.24__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.
socketdev/__init__.py CHANGED
@@ -1,3 +1,4 @@
1
+ import os
1
2
  from socketdev.core.api import API
2
3
  from socketdev.dependencies import Dependencies
3
4
  from socketdev.diffscans import DiffScans
@@ -26,7 +27,14 @@ from socketdev.analytics import Analytics
26
27
  from socketdev.alerttypes import AlertTypes
27
28
  from socketdev.basics import Basics
28
29
  from socketdev.uploadmanifests import UploadManifests
30
+ from socketdev.alertfullscansearch import AlertFullScanSearch
31
+ from socketdev.alerts import Alerts
32
+ from socketdev.fixes import Fixes
33
+ from socketdev.supportedfiles import SupportedFiles
34
+ from socketdev.webhooks import Webhooks
35
+ from socketdev.telemetry import Telemetry
29
36
  from socketdev.log import log
37
+ from typing import Optional
30
38
 
31
39
  __author__ = "socket.dev"
32
40
  __version__ = __version__
@@ -44,7 +52,22 @@ request_timeout = 1200
44
52
 
45
53
 
46
54
  class socketdev:
47
- def __init__(self, token: str, timeout: int = 1200, allow_unverified: bool = False):
55
+ def __init__(self, token: Optional[str] = None, timeout: int = 1200, allow_unverified: bool = False):
56
+ # Try to get token from environment variables if not provided
57
+ if token is None:
58
+ token = (
59
+ os.getenv("SOCKET_SECURITY_API_TOKEN") or
60
+ os.getenv("SOCKET_SECURITY_API_KEY") or
61
+ os.getenv("SOCKET_API_KEY") or
62
+ os.getenv("SOCKET_API_TOKEN")
63
+ )
64
+
65
+ if token is None:
66
+ raise ValueError(
67
+ "API token is required. Provide it as a parameter or set one of these environment variables: "
68
+ "SOCKET_SECURITY_API_TOKEN, SOCKET_SECURITY_API_KEY, SOCKET_API_KEY, SOCKET_API_TOKEN"
69
+ )
70
+
48
71
  self.api = API()
49
72
  self.token = token + ":"
50
73
  self.api.encode_key(self.token)
@@ -77,6 +100,12 @@ class socketdev:
77
100
  self.alerttypes = AlertTypes(self.api)
78
101
  self.basics = Basics(self.api)
79
102
  self.uploadmanifests = UploadManifests(self.api)
103
+ self.alertfullscansearch = AlertFullScanSearch(self.api)
104
+ self.alerts = Alerts(self.api)
105
+ self.fixes = Fixes(self.api)
106
+ self.supportedfiles = SupportedFiles(self.api)
107
+ self.webhooks = Webhooks(self.api)
108
+ self.telemetry = Telemetry(self.api)
80
109
 
81
110
  @staticmethod
82
111
  def set_timeout(timeout: int):
@@ -0,0 +1,33 @@
1
+ import logging
2
+ from urllib.parse import urlencode
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class AlertFullScanSearch:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def search(self, org_slug: str, **query_params) -> dict:
12
+ """
13
+ Search alerts across full scans.
14
+
15
+ Args:
16
+ org_slug: Organization slug
17
+ **query_params: Optional query parameters for filtering
18
+
19
+ Returns:
20
+ dict containing search results
21
+ """
22
+ path = f"orgs/{org_slug}/alert-full-scan-search"
23
+ if query_params:
24
+ path += "?" + urlencode(query_params)
25
+
26
+ response = self.api.do_request(path=path)
27
+
28
+ if response.status_code == 200:
29
+ return response.json()
30
+
31
+ log.error(f"Error searching alerts: {response.status_code}")
32
+ log.error(response.text)
33
+ return {}
@@ -0,0 +1,33 @@
1
+ import logging
2
+ from urllib.parse import urlencode
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Alerts:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def get(self, org_slug: str, **query_params) -> dict:
12
+ """
13
+ Get alerts for an organization.
14
+
15
+ Args:
16
+ org_slug: Organization slug
17
+ **query_params: Optional query parameters for filtering
18
+
19
+ Returns:
20
+ dict containing alerts data
21
+ """
22
+ path = f"orgs/{org_slug}/alerts"
23
+ if query_params:
24
+ path += "?" + urlencode(query_params)
25
+
26
+ response = self.api.do_request(path=path)
27
+
28
+ if response.status_code == 200:
29
+ return response.json()
30
+
31
+ log.error(f"Error getting alerts: {response.status_code}")
32
+ log.error(response.text)
33
+ return {}
@@ -73,3 +73,28 @@ class Export:
73
73
  log.error(f"Error exporting SPDX BOM: {response.status_code}")
74
74
  log.error(response.text)
75
75
  return {}
76
+
77
+ def openvex_bom(
78
+ self, org_slug: str, id: str, query_params: Optional[ExportQueryParams] = None, use_types: bool = False
79
+ ) -> dict:
80
+ """
81
+ Export a Socket SBOM as an OpenVEX SBOM
82
+ :param org_slug: String - The slug of the organization
83
+ :param id: String - The id of either a full scan or an sbom report
84
+ :param query_params: Optional[ExportQueryParams] - Query parameters for filtering
85
+ :param use_types: Optional[bool] - Whether to return typed responses
86
+ :return: dict
87
+ """
88
+ path = f"orgs/{org_slug}/export/openvex/{id}"
89
+ if query_params:
90
+ path += query_params.to_query_params()
91
+ response = self.api.do_request(path=path)
92
+
93
+ if response.status_code == 200:
94
+ return response.json()
95
+ # TODO: Add typed response when types are defined
96
+
97
+ log.error(f"Error exporting OpenVEX BOM: {response.status_code}")
98
+ log.error(response.text)
99
+ return {}
100
+
@@ -0,0 +1,33 @@
1
+ import logging
2
+ from urllib.parse import urlencode
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Fixes:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def get(self, org_slug: str, **query_params) -> dict:
12
+ """
13
+ Get available fixes for an organization.
14
+
15
+ Args:
16
+ org_slug: Organization slug
17
+ **query_params: Optional query parameters for filtering
18
+
19
+ Returns:
20
+ dict containing available fixes
21
+ """
22
+ path = f"orgs/{org_slug}/fixes"
23
+ if query_params:
24
+ path += "?" + urlencode(query_params)
25
+
26
+ response = self.api.do_request(path=path)
27
+
28
+ if response.status_code == 200:
29
+ return response.json()
30
+
31
+ log.error(f"Error getting fixes: {response.status_code}")
32
+ log.error(response.text)
33
+ return {}
@@ -117,7 +117,7 @@ class FullScanParams:
117
117
  commit_hash=data.get("commit_hash"),
118
118
  pull_request=data.get("pull_request"),
119
119
  committers=data.get("committers"),
120
- integration_type=IntegrationType(integration_type) if integration_type else None,
120
+ integration_type=integration_type if integration_type is not None else None,
121
121
  integration_org_slug=data.get("integration_org_slug"),
122
122
  make_default_branch=data.get("make_default_branch"),
123
123
  set_as_pending_head=data.get("set_as_pending_head"),
@@ -181,11 +181,12 @@ class CreateFullScanResponse:
181
181
 
182
182
  @classmethod
183
183
  def from_dict(cls, data: dict) -> "CreateFullScanResponse":
184
+ data_value = data.get("data")
184
185
  return cls(
185
186
  success=data["success"],
186
187
  status=data["status"],
187
188
  message=data.get("message"),
188
- data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") else None,
189
+ data=FullScanMetadata.from_dict(data_value) if data_value else None,
189
190
  )
190
191
 
191
192
 
@@ -204,11 +205,12 @@ class GetFullScanMetadataResponse:
204
205
 
205
206
  @classmethod
206
207
  def from_dict(cls, data: dict) -> "GetFullScanMetadataResponse":
208
+ data_value = data.get("data")
207
209
  return cls(
208
210
  success=data["success"],
209
211
  status=data["status"],
210
212
  message=data.get("message"),
211
- data=FullScanMetadata.from_dict(data.get("data")) if data.get("data") else None,
213
+ data=FullScanMetadata.from_dict(data_value) if data_value else None,
212
214
  )
213
215
 
214
216
 
@@ -450,8 +452,8 @@ class DiffArtifact:
450
452
  id: str
451
453
  type: str
452
454
  name: str
453
- version: str
454
455
  licenseDetails: List[LicenseDetail]
456
+ version: Optional[str] = None
455
457
  score: Optional[SocketScore] = None
456
458
  author: List[str] = field(default_factory=list)
457
459
  alerts: List[SocketAlert] = field(default_factory=list)
@@ -500,7 +502,7 @@ class DiffArtifact:
500
502
  type=data["type"],
501
503
  name=data["name"],
502
504
  score=score,
503
- version=data["version"],
505
+ version=data.get("version"),
504
506
  alerts=[SocketAlert.from_dict(alert) for alert in data.get("alerts", [])],
505
507
  licenseDetails=license_details,
506
508
  files=data.get("files"),
@@ -619,11 +621,12 @@ class StreamDiffResponse:
619
621
 
620
622
  @classmethod
621
623
  def from_dict(cls, data: dict) -> "StreamDiffResponse":
624
+ data_value = data.get("data")
622
625
  return cls(
623
626
  success=data["success"],
624
627
  status=data["status"],
625
628
  message=data.get("message"),
626
- data=FullScanDiffReport.from_dict(data.get("data")) if data.get("data") else None,
629
+ data=FullScanDiffReport.from_dict(data_value) if data_value else None,
627
630
  )
628
631
 
629
632
 
@@ -631,7 +634,7 @@ class StreamDiffResponse:
631
634
  class SocketArtifact(SocketPURL, SocketArtifactLink):
632
635
  id: str
633
636
  alerts: List[SocketAlert]
634
- score: SocketScore
637
+ score: Optional[SocketScore] = None
635
638
  author: Optional[List[str]] = field(default_factory=list)
636
639
  batchIndex: Optional[int] = None
637
640
  license: Optional[str] = None
@@ -647,8 +650,25 @@ class SocketArtifact(SocketPURL, SocketArtifactLink):
647
650
 
648
651
  @classmethod
649
652
  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__}
653
+ # Extract PURL fields
654
+ purl_type = data.get("type")
655
+ purl_data = {
656
+ "type": SocketPURL_Type(purl_type) if purl_type else SocketPURL_Type.UNKNOWN,
657
+ "name": data.get("name"),
658
+ "namespace": data.get("namespace"),
659
+ "release": data.get("release"),
660
+ "subpath": data.get("subpath"),
661
+ "version": data.get("version"),
662
+ }
663
+
664
+ # Extract Link fields
665
+ link_data = {
666
+ "topLevelAncestors": data.get("topLevelAncestors", []),
667
+ "direct": data.get("direct", False),
668
+ "artifact": data.get("artifact"),
669
+ "dependencies": data.get("dependencies"),
670
+ "manifestFiles": [SocketManifestReference.from_dict(m) for m in data["manifestFiles"]] if data.get("manifestFiles") else None,
671
+ }
652
672
 
653
673
  alerts = data.get("alerts")
654
674
  license_attrib = data.get("licenseAttrib")
@@ -728,7 +748,17 @@ class FullScans:
728
748
  )
729
749
  return {}
730
750
 
731
- def post(self, files: list, params: FullScanParams, use_types: bool = False, use_lazy_loading: bool = False, workspace: str = None, max_open_files: int = 100, base_path: str = None, base_paths: List[str] = None) -> Union[dict, CreateFullScanResponse]:
751
+ def post(
752
+ self,
753
+ files: list,
754
+ params: FullScanParams,
755
+ use_types: bool = False,
756
+ use_lazy_loading: bool = False,
757
+ workspace: Optional[str] = None,
758
+ max_open_files: int = 100,
759
+ base_path: Optional[str] = None,
760
+ base_paths: Optional[List[str]] = None
761
+ ) -> Union[dict, CreateFullScanResponse]:
732
762
  """
733
763
  Create a new full scan by uploading manifest files.
734
764
 
@@ -926,4 +956,118 @@ class FullScans:
926
956
 
927
957
  if response.status_code in (200, 201, 204):
928
958
  return True
929
- return False
959
+ return False
960
+
961
+ 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:
962
+ """
963
+ Create a full scan by uploading one or more archives.
964
+
965
+ Supported archive formats include .tar, .tar.gz/.tgz, and .zip.
966
+
967
+ Args:
968
+ tar_files: Path(s) to archive file(s) to upload (.tar, .tar.gz, .tgz, or .zip)
969
+ Can be a single string or a list of strings
970
+ files: List of files to bundle into a .tar.gz and upload (alternative to tar_files)
971
+ workspace: Base directory path to make file paths relative to when creating tar.gz
972
+ use_lazy_loading: Whether to use lazy file loading (default: True)
973
+ params: FullScanParams object containing scan configuration (repo, org_slug, branch,
974
+ commit_message, commit_hash, pull_request, committers, integration_type,
975
+ integration_org_slug, make_default_branch, set_as_pending_head, tmp)
976
+
977
+ Returns:
978
+ dict with the full scan creation response
979
+
980
+ Raises:
981
+ ValueError: If neither tar_files nor files is provided, or if both are provided,
982
+ or if params is None
983
+ """
984
+ if tar_files is None and files is None:
985
+ raise ValueError("Either tar_files or files must be provided")
986
+
987
+ if tar_files is not None and files is not None:
988
+ raise ValueError("Cannot provide both tar_files and files - choose one")
989
+
990
+ if params is None:
991
+ raise ValueError("params argument is required")
992
+
993
+ Utils.validate_integration_type(params.integration_type if params.integration_type else "api")
994
+ org_slug = str(params.org_slug)
995
+ params_dict = params.to_dict()
996
+ params_dict.pop("org_slug")
997
+ params_arg = urllib.parse.urlencode(params_dict)
998
+ path = f"orgs/{org_slug}/full-scans/archive?" + str(params_arg)
999
+
1000
+ # Prepare files for upload
1001
+ if tar_files:
1002
+ # Archive file(s) - use lazy loading to prepare them
1003
+ if use_lazy_loading:
1004
+ upload_files = Utils.prepare_archive_files_for_upload(tar_files)
1005
+ else:
1006
+ # For backward compatibility, fall back to opening files directly
1007
+ files_list = [tar_files] if isinstance(tar_files, str) else tar_files
1008
+ upload_files = []
1009
+ for file_path in files_list:
1010
+ filename = file_path.rsplit("/", 1)[-1] if "/" in file_path else file_path
1011
+ with open(file_path, 'rb') as f:
1012
+ upload_files.append(("file", (filename, f.read())))
1013
+ else:
1014
+ # Multiple files - bundle into tar.gz
1015
+ log.debug(f"Creating tar.gz archive from {len(files)} files")
1016
+ tar_buffer = Utils.create_tar_gz_from_files(files, workspace)
1017
+
1018
+ # Prepare the tar.gz for upload
1019
+ archive_name = "archive.tar.gz"
1020
+ upload_files = [("file", (archive_name, tar_buffer))]
1021
+
1022
+ response = self.api.do_request(path=path, method="POST", files=upload_files)
1023
+
1024
+ if response.status_code in (200, 201):
1025
+ return response.json()
1026
+
1027
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
1028
+ log.error(f"Error creating full scan from archive: {response.status_code}, message: {error_message}")
1029
+ return {}
1030
+
1031
+ def rescan(self, org_slug: str, full_scan_id: str) -> dict:
1032
+ """
1033
+ Trigger a rescan of an existing full scan.
1034
+
1035
+ Args:
1036
+ org_slug: Organization slug
1037
+ full_scan_id: The ID of the full scan to rescan
1038
+
1039
+ Returns:
1040
+ dict with the rescan response
1041
+ """
1042
+ path = f"orgs/{org_slug}/full-scans/{full_scan_id}/rescan"
1043
+
1044
+ response = self.api.do_request(path=path, method="POST", payload="{}")
1045
+
1046
+ if response.status_code in (200, 201):
1047
+ return response.json()
1048
+
1049
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
1050
+ log.error(f"Error rescanning full scan: {response.status_code}, message: {error_message}")
1051
+ return {}
1052
+
1053
+ def get_tar_files(self, org_slug: str, full_scan_id: str) -> bytes:
1054
+ """
1055
+ Download full scan files as a tar archive.
1056
+
1057
+ Args:
1058
+ org_slug: Organization slug
1059
+ full_scan_id: The ID of the full scan
1060
+
1061
+ Returns:
1062
+ bytes containing the tar archive, or empty bytes on error
1063
+ """
1064
+ path = f"orgs/{org_slug}/full-scans/{full_scan_id}/files/tar"
1065
+
1066
+ response = self.api.do_request(path=path, method="GET")
1067
+
1068
+ if response.status_code == 200:
1069
+ return response.content
1070
+
1071
+ error_message = response.json().get("error", {}).get("message", "Unknown error") if response.text else "Unknown error"
1072
+ log.error(f"Error downloading tar files: {response.status_code}, message: {error_message}")
1073
+ return b""
@@ -47,6 +47,25 @@ class Historical:
47
47
  log.error(response.text)
48
48
  return {}
49
49
 
50
+ def dependencies_trend(self, org_slug: str, query_params: dict = None) -> dict:
51
+ """Get historical dependency trends data for an org.
52
+
53
+ Args:
54
+ org_slug: Organization slug
55
+ query_params: Optional dictionary of query parameters
56
+ """
57
+ path = f"orgs/{org_slug}/historical/dependencies/trend"
58
+ if query_params:
59
+ path += "?" + urlencode(query_params)
60
+
61
+ response = self.api.do_request(path=path)
62
+ if response.status_code == 200:
63
+ return response.json()
64
+
65
+ log.error(f"Error getting historical dependencies trend: {response.status_code}")
66
+ log.error(response.text)
67
+ return {}
68
+
50
69
  class Snapshots:
51
70
  """Submodule for managing historical snapshots."""
52
71
 
@@ -58,11 +58,12 @@ class GetRepoResponse:
58
58
 
59
59
  @classmethod
60
60
  def from_dict(cls, data: dict) -> "GetRepoResponse":
61
+ data_field = data.get("data")
61
62
  return cls(
62
63
  success=data["success"],
63
64
  status=data["status"],
64
65
  message=data.get("message"),
65
- data=RepositoryInfo.from_dict(data.get("data")) if data.get("data") else None,
66
+ data=RepositoryInfo.from_dict(data_field) if data_field is not None else None,
66
67
  )
67
68
 
68
69
 
@@ -0,0 +1,29 @@
1
+ import logging
2
+
3
+ log = logging.getLogger("socketdev")
4
+
5
+
6
+ class SupportedFiles:
7
+ def __init__(self, api):
8
+ self.api = api
9
+
10
+ def get(self, org_slug: str) -> dict:
11
+ """
12
+ Get list of supported manifest file types.
13
+
14
+ Args:
15
+ org_slug: Organization slug
16
+
17
+ Returns:
18
+ dict containing list of supported file types
19
+ """
20
+ path = f"orgs/{org_slug}/supported-files"
21
+
22
+ response = self.api.do_request(path=path)
23
+
24
+ if response.status_code == 200:
25
+ return response.json()
26
+
27
+ log.error(f"Error getting supported files: {response.status_code}")
28
+ log.error(response.text)
29
+ return {}
@@ -0,0 +1,53 @@
1
+ import logging
2
+ import json
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Telemetry:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def get_config(self, org_slug: str) -> dict:
12
+ """
13
+ Get telemetry configuration.
14
+
15
+ Args:
16
+ org_slug: Organization slug
17
+
18
+ Returns:
19
+ dict containing telemetry configuration
20
+ """
21
+ path = f"orgs/{org_slug}/telemetry/config"
22
+
23
+ response = self.api.do_request(path=path)
24
+
25
+ if response.status_code == 200:
26
+ return response.json()
27
+
28
+ log.error(f"Error getting telemetry config: {response.status_code}")
29
+ log.error(response.text)
30
+ return {}
31
+
32
+ def update_config(self, org_slug: str, **kwargs) -> dict:
33
+ """
34
+ Update telemetry configuration.
35
+
36
+ Args:
37
+ org_slug: Organization slug
38
+ **kwargs: Configuration parameters to update
39
+
40
+ Returns:
41
+ dict containing the updated telemetry configuration
42
+ """
43
+ path = f"orgs/{org_slug}/telemetry/config"
44
+ payload = json.dumps(kwargs) if kwargs else "{}"
45
+
46
+ response = self.api.do_request(path=path, method="PUT", payload=payload)
47
+
48
+ if response.status_code == 200:
49
+ return response.json()
50
+
51
+ log.error(f"Error updating telemetry config: {response.status_code}")
52
+ log.error(response.text)
53
+ return {}
@@ -1,8 +1,11 @@
1
- from typing import Literal, List, Tuple, Optional
1
+ from typing import Literal, List, Tuple, Optional, Union
2
2
  import logging
3
3
  import os
4
4
  import weakref
5
5
  from threading import Lock
6
+ import tarfile
7
+ import tempfile
8
+ import io
6
9
 
7
10
  log = logging.getLogger("socketdev")
8
11
 
@@ -133,6 +136,7 @@ class LazyFileLoader:
133
136
  def read(self, size: int = -1):
134
137
  """Read from the file, opening it if needed."""
135
138
  self._ensure_open()
139
+ assert self._file is not None
136
140
  data = self._file.read(size)
137
141
  self._position = self._file.tell()
138
142
 
@@ -145,6 +149,7 @@ class LazyFileLoader:
145
149
  def readline(self, size: int = -1):
146
150
  """Read a line from the file."""
147
151
  self._ensure_open()
152
+ assert self._file is not None
148
153
  data = self._file.readline(size)
149
154
  self._position = self._file.tell()
150
155
  return data
@@ -162,6 +167,7 @@ class LazyFileLoader:
162
167
  elif whence == 2: # SEEK_END
163
168
  # We need to open the file to get its size
164
169
  self._ensure_open()
170
+ assert self._file is not None
165
171
  result = self._file.seek(offset, whence)
166
172
  self._position = self._file.tell()
167
173
  return result
@@ -340,3 +346,97 @@ class Utils:
340
346
 
341
347
  log.debug(f"Prepared {len(send_files)} files for lazy loading")
342
348
  return send_files
349
+
350
+ @staticmethod
351
+ def create_tar_gz_from_files(files: List[str], workspace: Optional[str] = None) -> io.BytesIO:
352
+ """
353
+ Create a tar.gz archive from a list of files.
354
+
355
+ Args:
356
+ files: List of file paths to include in the archive
357
+ workspace: Base directory path to make paths relative to
358
+
359
+ Returns:
360
+ io.BytesIO: In-memory tar.gz archive
361
+ """
362
+ tar_buffer = io.BytesIO()
363
+
364
+ # Normalize workspace path
365
+ if workspace and "\\" in workspace:
366
+ workspace = workspace.replace("\\", "/")
367
+ if workspace:
368
+ workspace = workspace.rstrip("/")
369
+
370
+ with tarfile.open(fileobj=tar_buffer, mode='w:gz') as tar:
371
+ for file_path in files:
372
+ # Normalize file path
373
+ normalized_path = file_path.replace("\\", "/") if "\\" in file_path else file_path
374
+
375
+ # Skip if file doesn't exist
376
+ if not os.path.exists(normalized_path):
377
+ log.warning(f"File not found, skipping: {normalized_path}")
378
+ continue
379
+
380
+ # Skip directories
381
+ if os.path.isdir(normalized_path):
382
+ log.debug(f"Skipping directory: {normalized_path}")
383
+ continue
384
+
385
+ # Calculate arcname (the name in the archive)
386
+ arcname = normalized_path
387
+ if workspace:
388
+ workspace_with_slash = workspace + "/"
389
+ if normalized_path.startswith(workspace_with_slash):
390
+ arcname = normalized_path[len(workspace_with_slash):]
391
+ elif normalized_path.startswith(workspace):
392
+ arcname = normalized_path[len(workspace):].lstrip("/")
393
+
394
+ # Clean up relative path prefixes
395
+ while arcname.startswith("./"):
396
+ arcname = arcname[2:]
397
+ while arcname.startswith("../"):
398
+ arcname = arcname[3:]
399
+ arcname = arcname.lstrip("/")
400
+
401
+ # Remove Windows drive letter if present
402
+ if len(arcname) > 2 and arcname[1] == ':' and (arcname[2] == '/' or arcname[2] == '\\'):
403
+ arcname = arcname[2:].lstrip("/")
404
+
405
+ log.debug(f"Adding to archive: {normalized_path} as {arcname}")
406
+ tar.add(normalized_path, arcname=arcname)
407
+
408
+ # Seek to beginning so it can be read
409
+ tar_buffer.seek(0)
410
+ log.debug(f"Created tar.gz archive with {len(files)} files")
411
+ return tar_buffer
412
+
413
+ @staticmethod
414
+ def prepare_archive_files_for_upload(tar_files: Union[str, List[str]]) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
415
+ """
416
+ Prepare archive files for upload to the API.
417
+
418
+ Args:
419
+ tar_files: Path or list of paths to archive files (.tar, .tar.gz, .tgz, .zip)
420
+
421
+ Returns:
422
+ List of tuples formatted for requests multipart upload
423
+ """
424
+ files_list = [tar_files] if isinstance(tar_files, str) else tar_files
425
+ prepared_files = []
426
+
427
+ for file_path in files_list:
428
+ # Normalize path
429
+ normalized_path = file_path.replace("\\", "/") if "\\" in file_path else file_path
430
+
431
+ # Get filename
432
+ if "/" in normalized_path:
433
+ _, filename = normalized_path.rsplit("/", 1)
434
+ else:
435
+ filename = normalized_path
436
+
437
+ # Create lazy file loader
438
+ lazy_file = LazyFileLoader(normalized_path, filename)
439
+ prepared_files.append(("file", (filename, lazy_file)))
440
+
441
+ log.debug(f"Prepared {len(prepared_files)} archive files for upload")
442
+ return prepared_files
socketdev/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "3.0.21"
1
+ __version__ = "3.0.24"
@@ -0,0 +1,125 @@
1
+ import logging
2
+ import json
3
+ from urllib.parse import urlencode
4
+
5
+ log = logging.getLogger("socketdev")
6
+
7
+
8
+ class Webhooks:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def list(self, org_slug: str, **query_params) -> dict:
13
+ """
14
+ List webhooks.
15
+
16
+ Args:
17
+ org_slug: Organization slug
18
+ **query_params: Optional query parameters
19
+
20
+ Returns:
21
+ dict containing list of webhooks
22
+ """
23
+ path = f"orgs/{org_slug}/webhooks"
24
+ if query_params:
25
+ path += "?" + urlencode(query_params)
26
+
27
+ response = self.api.do_request(path=path)
28
+
29
+ if response.status_code == 200:
30
+ return response.json()
31
+
32
+ log.error(f"Error listing webhooks: {response.status_code}")
33
+ log.error(response.text)
34
+ return {}
35
+
36
+ def create(self, org_slug: str, **kwargs) -> dict:
37
+ """
38
+ Create a new webhook.
39
+
40
+ Args:
41
+ org_slug: Organization slug
42
+ **kwargs: Webhook configuration parameters
43
+
44
+ Returns:
45
+ dict containing the created webhook
46
+ """
47
+ path = f"orgs/{org_slug}/webhooks"
48
+ payload = json.dumps(kwargs) if kwargs else "{}"
49
+
50
+ response = self.api.do_request(path=path, method="POST", payload=payload)
51
+
52
+ if response.status_code in (200, 201):
53
+ return response.json()
54
+
55
+ log.error(f"Error creating webhook: {response.status_code}")
56
+ log.error(response.text)
57
+ return {}
58
+
59
+ def get(self, org_slug: str, webhook_id: str) -> dict:
60
+ """
61
+ Get a specific webhook.
62
+
63
+ Args:
64
+ org_slug: Organization slug
65
+ webhook_id: Webhook ID
66
+
67
+ Returns:
68
+ dict containing webhook details
69
+ """
70
+ path = f"orgs/{org_slug}/webhooks/{webhook_id}"
71
+
72
+ response = self.api.do_request(path=path)
73
+
74
+ if response.status_code == 200:
75
+ return response.json()
76
+
77
+ log.error(f"Error getting webhook: {response.status_code}")
78
+ log.error(response.text)
79
+ return {}
80
+
81
+ def update(self, org_slug: str, webhook_id: str, **kwargs) -> dict:
82
+ """
83
+ Update a webhook.
84
+
85
+ Args:
86
+ org_slug: Organization slug
87
+ webhook_id: Webhook ID
88
+ **kwargs: Webhook configuration parameters to update
89
+
90
+ Returns:
91
+ dict containing the updated webhook
92
+ """
93
+ path = f"orgs/{org_slug}/webhooks/{webhook_id}"
94
+ payload = json.dumps(kwargs) if kwargs else "{}"
95
+
96
+ response = self.api.do_request(path=path, method="PUT", payload=payload)
97
+
98
+ if response.status_code == 200:
99
+ return response.json()
100
+
101
+ log.error(f"Error updating webhook: {response.status_code}")
102
+ log.error(response.text)
103
+ return {}
104
+
105
+ def delete(self, org_slug: str, webhook_id: str) -> dict:
106
+ """
107
+ Delete a webhook.
108
+
109
+ Args:
110
+ org_slug: Organization slug
111
+ webhook_id: Webhook ID
112
+
113
+ Returns:
114
+ dict containing the deletion response
115
+ """
116
+ path = f"orgs/{org_slug}/webhooks/{webhook_id}"
117
+
118
+ response = self.api.do_request(path=path, method="DELETE")
119
+
120
+ if response.status_code == 200:
121
+ return response.json()
122
+
123
+ log.error(f"Error deleting webhook: {response.status_code}")
124
+ log.error(response.text)
125
+ return {}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: socketdev
3
- Version: 3.0.21
3
+ Version: 3.0.24
4
4
  Summary: Socket Security Python SDK
5
5
  Project-URL: Homepage, https://github.com/socketdev/socketdev
6
6
  Author-email: Douglas Coburn <douglas@socket.dev>
@@ -1,7 +1,9 @@
1
- socketdev/__init__.py,sha256=huea0EKxNEolh19KXWvmlJGa_lTeYIuks8VCyezXOic,3090
1
+ socketdev/__init__.py,sha256=M_nd-5N6SOSnZWQvS3dTDtBcgbTue6WHwJledRTpuvk,4365
2
2
  socketdev/exceptions.py,sha256=SNU1EgswGwnxI_Zmm325ruP6CFg5C4MsS1qxXWwBJqs,1120
3
3
  socketdev/log.py,sha256=AgEcsPN3y9U-fze8pTFvLigVvNob2vmNC-TkOOQkkeQ,90
4
- socketdev/version.py,sha256=Rdqo30aJqqOLb1w7YCE0OyB7QElenfZV3VvB32uiczg,23
4
+ socketdev/version.py,sha256=V-wiZHBO5iSdF-Sh5dQyYQyfRPR9gqJRDwgpuHYAVvw,23
5
+ socketdev/alertfullscansearch/__init__.py,sha256=YwXrgnrI9z9rAexXFFmoXQcaQdGW47HRhQ58CQBCG3U,884
6
+ socketdev/alerts/__init__.py,sha256=kGLCNXtXTRz3vl2s_bPQ7xuds_QGwNQnah1TfHzp2MU,846
5
7
  socketdev/alerttypes/__init__.py,sha256=W-m2D9VxbepSAUELJPmWmX40zksGZbQcSzwQ1kjlB1k,1169
6
8
  socketdev/analytics/__init__.py,sha256=kQGeO67TraqvfmYjfpYCvcNRtxW2a6x5EefEl6Jnca8,2223
7
9
  socketdev/apitokens/__init__.py,sha256=Z6W9Jkh4gdDeJBivfcONZuz7jRKZtxWLTi1n9gkbYVE,4222
@@ -13,9 +15,10 @@ socketdev/core/dedupe.py,sha256=bvX92ia4anVQtEv18LaLupisuHg68eNPuLZjmLhhAGE,5493
13
15
  socketdev/core/issues.py,sha256=jIfi6h1Y-d38OgxSFhlgC74TLvY6IfUcWhQfLq8FFPo,68147
14
16
  socketdev/dependencies/__init__.py,sha256=zdAb0lMYF8tTHFWa9kGwz5dv4_Sp1UpzQseg_4_qBfY,2170
15
17
  socketdev/diffscans/__init__.py,sha256=ndsgyFmsvK29pJAEhZyBByZ9ampf1Ks6oV8y1q7mssw,5294
16
- socketdev/export/__init__.py,sha256=cDZ3Z0UTazpapiTjhHKgaJxXHh2vVruKhlWnJB-YcQU,2674
17
- socketdev/fullscans/__init__.py,sha256=H1yT6DmfAIviYzxIadi_55I0RJJEXZ0CTRtVj2sHpfs,30348
18
- socketdev/historical/__init__.py,sha256=EZ053u9L4dJgUMDjDNlUWVbbVk9OOguYrP9djejklj0,2786
18
+ socketdev/export/__init__.py,sha256=5DqVqHnaK5Aq-ueSTIAplOZJpF21W_pXysIzmMNLGPg,3667
19
+ socketdev/fixes/__init__.py,sha256=ouRSQ5FcqQcjAmrU8aAgd0ZJeo431wBOEVKLR36etik,856
20
+ socketdev/fullscans/__init__.py,sha256=QaxFUfpQLdVqLiL5mxCnU-t-ZwLvTrUwSEY69ihEn-g,36399
21
+ socketdev/historical/__init__.py,sha256=DXFmRrHLWHKbZrB8eermM4YG6j4C1S4Lz6-V63_p2gs,3472
19
22
  socketdev/labels/__init__.py,sha256=Ep19ZraKqi_a-3-eAOWGhPNQsgwGRY9N28Oyxlxrz-g,5128
20
23
  socketdev/licensemetadata/__init__.py,sha256=pDcvpkc08QtMqhsnKP1Cfjvs3m-MRPYUK-uLh8aRkrU,815
21
24
  socketdev/npm/__init__.py,sha256=FvU8z6dY3EsBNLBsKwQKT5soNb6ous1o63aphmbBHh4,906
@@ -24,16 +27,19 @@ socketdev/org/__init__.py,sha256=2e9fe9jF8V_zb2V-qtmkQZUzJv6qbfpbb1p4Hdgsx9A,903
24
27
  socketdev/purl/__init__.py,sha256=_ybmj-taH2eArwMPwYX-dO3UA4xoK-TMSgEEvI9Adzg,1345
25
28
  socketdev/quota/__init__.py,sha256=IblVMP3M7HwXtHs2wnr72GlcNIQtykOKsZKLSehEC8c,487
26
29
  socketdev/report/__init__.py,sha256=L1EuvUnatxWAwQdLiTQwdRNIVglWYoyWqSISuZB0RTE,3454
27
- socketdev/repos/__init__.py,sha256=dM8GrjIiHUBsPJeBRKLm9QJDRCgx5F-N2iN7GDCHTIg,5603
30
+ socketdev/repos/__init__.py,sha256=2_BVRYYpA-wF1W9KvhbaBrfe3g2VHLkWLMizWOiyX3A,5641
28
31
  socketdev/repositories/__init__.py,sha256=0SP-rCSfxWa9DrPkDKXac8SHqmVHFqgqUHDs-5eg8IE,790
29
32
  socketdev/sbom/__init__.py,sha256=LpesXKZhgF5OeNWls10YgxsCNamFW-F8UOy4yI11hrY,2341
30
33
  socketdev/settings/__init__.py,sha256=CCRAnFWOvm7Hi4LY0gbFqsOFHNDlWK3FHei0Edcv_-8,6268
34
+ socketdev/supportedfiles/__init__.py,sha256=XLli-HOPYJrKs0TIHKSD2tk8VSLJsI3owMKeVlGQNms,706
35
+ socketdev/telemetry/__init__.py,sha256=9cRqeT6ToZVnWv65acMX9TXGgDDNe2VY4ZEf-4ooGHI,1444
31
36
  socketdev/threatfeed/__init__.py,sha256=2SsJYKByXBkb2C1fGopwxejkr7mky0kggFKIunyV7Nk,1119
32
37
  socketdev/tools/__init__.py,sha256=ROvpEULLXTKby9DMsVFPlAlysjwfop1NhRqSrFUWprY,1969
33
38
  socketdev/triage/__init__.py,sha256=-h599vThVetfRSOAs1e4IUoMjcXS8xOsUfub41XPiX4,1559
34
39
  socketdev/uploadmanifests/__init__.py,sha256=-sFHbOW-aw7U0wRfEJT_Edrzx8aCbzD9cTGmVTNJKpw,6043
35
- socketdev/utils/__init__.py,sha256=27OgKDg_0lcrSCUy5g1CV_LTv2_OYb9-wkNiamlTntc,13567
36
- socketdev-3.0.21.dist-info/METADATA,sha256=P5bqiKYXA4wocgaR97lBxlP5dkWQZoi2eFc2qArd1N4,36240
37
- socketdev-3.0.21.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
38
- socketdev-3.0.21.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
39
- socketdev-3.0.21.dist-info/RECORD,,
40
+ socketdev/utils/__init__.py,sha256=E11UJTsWsN-ZurOwtKvPGOTc9UMP3ND79nPbmNRRQ6E,17666
41
+ socketdev/webhooks/__init__.py,sha256=fme6K7ma_Gvk_TFOLz9jVcR5QJbDpMHXqRaU3x_RShY,3507
42
+ socketdev-3.0.24.dist-info/METADATA,sha256=vVWPGqcqAeuUnqckpBRLvG-s36TQQHhE5PlvZGDnq0Y,36240
43
+ socketdev-3.0.24.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
44
+ socketdev-3.0.24.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
45
+ socketdev-3.0.24.dist-info/RECORD,,