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,62 @@
1
+ import json
2
+ from socketdev.core.classes import Package
3
+ import logging
4
+
5
+ log = logging.getLogger("socketdev")
6
+
7
+ # TODO: Add response type classes for SBOM endpoints
8
+
9
+
10
+ class Sbom:
11
+ def __init__(self, api):
12
+ self.api = api
13
+
14
+ # NOTE: This method's NDJSON handling is inconsistent with other methods in the SDK.
15
+ # While other methods return arrays for NDJSON responses, this returns a dictionary.
16
+ # This inconsistency is preserved to maintain backward compatibility with clients
17
+ # who have been using this method since its introduction 9 months ago.
18
+ def view(self, report_id: str) -> dict[str, dict]:
19
+ path = f"sbom/view/{report_id}"
20
+ response = self.api.do_request(path=path)
21
+ if response.status_code == 200:
22
+ sbom = []
23
+ sbom_dict = {}
24
+ data = response.text
25
+ data.strip('"')
26
+ data.strip()
27
+ for line in data.split("\n"):
28
+ if line != '"' and line != "" and line is not None:
29
+ item = json.loads(line)
30
+ sbom.append(item)
31
+ for val in sbom:
32
+ sbom_dict[val["id"]] = val
33
+ else:
34
+ log.error(f"Error viewing SBOM: {response.status_code}")
35
+ log.error(response.text)
36
+ sbom_dict = {}
37
+ return sbom_dict
38
+
39
+ def create_packages_dict(self, sbom: dict[str, dict]) -> dict[str, Package]:
40
+ """
41
+ Converts the SBOM Artifacts from the FulLScan into a Dictionary for parsing
42
+ :param sbom: list - Raw artifacts for the SBOM
43
+ :return:
44
+ """
45
+ packages = {}
46
+ top_level_count = {}
47
+ for package_id in sbom:
48
+ item = sbom[package_id]
49
+ package = Package(**item)
50
+ if package.id in packages:
51
+ log.error(f"Duplicate package_id: {package_id}")
52
+ else:
53
+ packages[package.id] = package
54
+ for top_id in package.topLevelAncestors:
55
+ if top_id not in top_level_count:
56
+ top_level_count[top_id] = 1
57
+ else:
58
+ top_level_count[top_id] += 1
59
+ if len(top_level_count) > 0:
60
+ for package_id in top_level_count:
61
+ packages[package_id].transitives = top_level_count[package_id]
62
+ return packages
@@ -0,0 +1,172 @@
1
+ import logging
2
+ from enum import Enum
3
+ from typing import Dict, Optional, Union
4
+ from dataclasses import dataclass, asdict
5
+
6
+ log = logging.getLogger("socketdev")
7
+
8
+
9
+ class SecurityAction(str, Enum):
10
+ DEFER = "defer"
11
+ ERROR = "error"
12
+ WARN = "warn"
13
+ MONITOR = "monitor"
14
+ IGNORE = "ignore"
15
+
16
+
17
+ @dataclass
18
+ class SecurityPolicyRule:
19
+ action: SecurityAction
20
+
21
+ def __getitem__(self, key):
22
+ return getattr(self, key)
23
+
24
+ def to_dict(self):
25
+ return asdict(self)
26
+
27
+ @classmethod
28
+ def from_dict(cls, data: dict) -> "SecurityPolicyRule":
29
+ return cls(action=SecurityAction(data["action"]))
30
+
31
+
32
+ @dataclass
33
+ class OrgSecurityPolicyResponse:
34
+ success: bool
35
+ status: int
36
+ securityPolicyRules: Optional[Dict[str, SecurityPolicyRule]] = None
37
+ message: Optional[str] = None
38
+
39
+ def __getitem__(self, key):
40
+ return getattr(self, key)
41
+
42
+ def to_dict(self):
43
+ return asdict(self)
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: dict) -> "OrgSecurityPolicyResponse":
47
+ return cls(
48
+ securityPolicyRules={k: SecurityPolicyRule.from_dict(v) for k, v in data["securityPolicyRules"].items()}
49
+ if data.get("securityPolicyRules")
50
+ else None,
51
+ success=data["success"],
52
+ status=data["status"],
53
+ message=data.get("message"),
54
+ )
55
+
56
+
57
+ class Settings:
58
+ def __init__(self, api):
59
+ self.api = api
60
+
61
+ def create_params_string(self, params: dict) -> str:
62
+ param_str = ""
63
+
64
+ for name, value in params.items():
65
+ if value:
66
+ if name == "committers" and isinstance(value, list):
67
+ # Handle committers specially - add multiple params
68
+ for committer in value:
69
+ param_str += f"&{name}={committer}"
70
+ else:
71
+ param_str += f"&{name}={value}"
72
+
73
+ param_str = "?" + param_str.lstrip("&")
74
+ return param_str
75
+
76
+ def get(
77
+ self, org_slug: str, custom_rules_only: bool = False, use_types: bool = False
78
+ ) -> Union[dict, OrgSecurityPolicyResponse]:
79
+ path = f"orgs/{org_slug}/settings/security-policy"
80
+ params = {"custom_rules_only": custom_rules_only}
81
+ params_args = self.create_params_string(params) if custom_rules_only else ""
82
+ path += params_args
83
+ response = self.api.do_request(path=path, method="GET")
84
+
85
+ if response.status_code == 200:
86
+ rules = response.json()
87
+ if use_types:
88
+ return OrgSecurityPolicyResponse.from_dict(
89
+ {"securityPolicyRules": rules.get("securityPolicyRules", {}), "success": True, "status": 200}
90
+ )
91
+ return rules
92
+
93
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
94
+ log.error(f"Failed to get security policy: {response.status_code}, message: {error_message}")
95
+ if use_types:
96
+ return OrgSecurityPolicyResponse.from_dict(
97
+ {"securityPolicyRules": {}, "success": False, "status": response.status_code, "message": error_message}
98
+ )
99
+ return {}
100
+
101
+ def integration_events(self, org_slug: str, integration_id: str) -> dict:
102
+ """Get integration events for a specific integration.
103
+
104
+ Args:
105
+ org_slug: Organization slug
106
+ integration_id: Integration ID
107
+ """
108
+ path = f"orgs/{org_slug}/settings/integrations/{integration_id}"
109
+ response = self.api.do_request(path=path)
110
+
111
+ if response.status_code == 200:
112
+ return response.json()
113
+
114
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
115
+ log.error(f"Error getting integration events: {response.status_code}, message: {error_message}")
116
+ return {}
117
+
118
+ def get_license_policy(self, org_slug: str) -> dict:
119
+ """Get license policy settings for an organization.
120
+
121
+ Args:
122
+ org_slug: Organization slug
123
+ """
124
+ path = f"orgs/{org_slug}/settings/license-policy"
125
+ response = self.api.do_request(path=path)
126
+
127
+ if response.status_code == 200:
128
+ return response.json()
129
+
130
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
131
+ log.error(f"Error getting license policy: {response.status_code}, message: {error_message}")
132
+ return {}
133
+
134
+ def update_security_policy(self, org_slug: str, body: dict, custom_rules_only: bool = False) -> dict:
135
+ """Update security policy settings for an organization.
136
+
137
+ Args:
138
+ org_slug: Organization slug
139
+ body: Security policy configuration to update
140
+ custom_rules_only: Optional flag to update only custom rules
141
+ """
142
+ path = f"orgs/{org_slug}/settings/security-policy"
143
+ if custom_rules_only:
144
+ path += "?custom_rules_only=true"
145
+
146
+ response = self.api.do_request(path=path, method="POST", payload=body)
147
+
148
+ if response.status_code == 200:
149
+ return response.json()
150
+
151
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
152
+ log.error(f"Error updating security policy: {response.status_code}, message: {error_message}")
153
+ return {}
154
+
155
+ def update_license_policy(self, org_slug: str, body: dict, merge_update: bool = False) -> dict:
156
+ """Update license policy settings for an organization.
157
+
158
+ Args:
159
+ org_slug: Organization slug
160
+ body: License policy configuration to update
161
+ merge_update: Optional flag to merge updates instead of replacing (defaults to False)
162
+ """
163
+ path = f"orgs/{org_slug}/settings/license-policy?merge_update={str(merge_update).lower()}"
164
+
165
+ response = self.api.do_request(path=path, method="POST", payload=body)
166
+
167
+ if response.status_code == 200:
168
+ return response.json()
169
+
170
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
171
+ log.error(f"Error updating license policy: {response.status_code}, message: {error_message}")
172
+ return {}
File without changes
@@ -0,0 +1,65 @@
1
+ import glob
2
+ import sys
3
+ import platform
4
+
5
+
6
+ def find_package_files(folder: str, file_types: list) -> list:
7
+ files = []
8
+ for file_type in file_types:
9
+ search_pattern = f"{folder}/**/{file_type}"
10
+ result = glob.glob(search_pattern, recursive=True)
11
+ if sys.platform.lower() == "win32":
12
+ result = fix_file_path(result)
13
+ files.extend(result)
14
+ return files
15
+
16
+
17
+ def fix_file_path(files) -> list:
18
+ fixed_files = []
19
+ for file in files:
20
+ file = file.replace("\\", "/")
21
+ fixed_files.append(file)
22
+ return fixed_files
23
+
24
+
25
+
26
+
27
+ def load_files(files: list, loaded_files: list, workspace: str = None) -> list:
28
+ for file in files:
29
+ if platform.system() == "Windows":
30
+ file = file.replace("\\", "/")
31
+ if "/" in file:
32
+ path, name = file.rsplit("/", 1)
33
+ else:
34
+ path = "."
35
+ name = file
36
+ full_path = f"{path}/{name}"
37
+
38
+ # Calculate key based on workspace if provided
39
+ if workspace and full_path.startswith(workspace):
40
+ key = full_path[len(workspace):]
41
+ key = key.lstrip("/")
42
+ key = key.lstrip("./")
43
+ else:
44
+ key = full_path
45
+
46
+ payload = (key, (name, open(full_path, "rb")))
47
+ loaded_files.append(payload)
48
+ return loaded_files
49
+
50
+
51
+ def prepare_for_csv(dependencies: list, packages: dict) -> list:
52
+ output = []
53
+ for dependency in dependencies:
54
+ if dependency.name in packages:
55
+ for package in packages[dependency.name]:
56
+ output_object = [
57
+ dependency.repository,
58
+ dependency.branch,
59
+ package.name,
60
+ package.version,
61
+ package.license,
62
+ package.repository,
63
+ ]
64
+ output.append(output_object)
65
+ return output
@@ -0,0 +1,47 @@
1
+ import logging
2
+ from urllib.parse import urlencode
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Triage:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def list_alert_triage(self, org_slug: str, query_params: dict = None) -> dict:
12
+ """Get list of triaged alerts for an organization.
13
+
14
+ Args:
15
+ org_slug: Organization slug
16
+ query_params: Optional dictionary of query parameters
17
+ """
18
+ path = f"orgs/{org_slug}/triage/alerts"
19
+ if query_params:
20
+ path += "?" + urlencode(query_params)
21
+
22
+ response = self.api.do_request(path=path)
23
+
24
+ if response.status_code == 200:
25
+ return response.json()
26
+
27
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
28
+ log.error(f"Error getting alert triage list: {response.status_code}, message: {error_message}")
29
+ return {}
30
+
31
+ def update_alert_triage(self, org_slug: str, body: dict) -> dict:
32
+ """Update triaged alerts for an organization.
33
+
34
+ Args:
35
+ org_slug: Organization slug
36
+ body: Alert triage configuration to update
37
+ """
38
+ path = f"orgs/{org_slug}/triage/alerts"
39
+
40
+ response = self.api.do_request(path=path, method="POST", payload=body)
41
+
42
+ if 200 <= response.status_code < 300:
43
+ return response.json()
44
+
45
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
46
+ log.error(f"Error updating alert triage: {response.status_code}, message: {error_message}")
47
+ return {}
@@ -0,0 +1,284 @@
1
+ from typing import Literal, List, Tuple
2
+ import logging
3
+ import os
4
+ import weakref
5
+ from threading import Lock
6
+
7
+ log = logging.getLogger("socketdev")
8
+
9
+ IntegrationType = Literal["api", "github", "gitlab", "bitbucket", "azure"]
10
+ INTEGRATION_TYPES = ("api", "github", "gitlab", "bitbucket", "azure")
11
+
12
+
13
+ class FileDescriptorManager:
14
+ """
15
+ Global manager to track and limit the number of open file descriptors.
16
+ Automatically closes least recently used files when limit is reached.
17
+ """
18
+ _instance = None
19
+ _lock = Lock()
20
+
21
+ def __new__(cls):
22
+ if cls._instance is None:
23
+ with cls._lock:
24
+ if cls._instance is None:
25
+ cls._instance = super().__new__(cls)
26
+ cls._instance._initialized = False
27
+ return cls._instance
28
+
29
+ def __init__(self):
30
+ if not self._initialized:
31
+ self.max_open_files = 100 # Default limit, can be overridden
32
+ self.open_files = [] # List of weakrefs to LazyFileLoader instances
33
+ self._initialized = True
34
+ log.debug(f"FileDescriptorManager initialized with default max_open_files={self.max_open_files}")
35
+
36
+ def set_max_open_files(self, max_files: int):
37
+ """Set the maximum number of open files."""
38
+ with self._lock:
39
+ self.max_open_files = max_files
40
+ log.debug(f"FileDescriptorManager max_open_files set to {self.max_open_files}")
41
+
42
+ # If we're now over the limit, close some files
43
+ while len(self.open_files) >= self.max_open_files:
44
+ self.open_files = [ref for ref in self.open_files if ref() is not None]
45
+ if len(self.open_files) >= self.max_open_files and self.open_files:
46
+ oldest_ref = self.open_files.pop(0)
47
+ oldest_file = oldest_ref()
48
+ if oldest_file is not None and oldest_file._file is not None:
49
+ oldest_file.close()
50
+ log.debug(f"Auto-closed file due to new descriptor limit: {oldest_file.file_path}")
51
+ else:
52
+ break
53
+
54
+ def register_file_open(self, lazy_file_loader):
55
+ """Register a file as opened and manage the descriptor limit."""
56
+ with self._lock:
57
+ # Remove any dead weak references
58
+ self.open_files = [ref for ref in self.open_files if ref() is not None]
59
+
60
+ # If we're at the limit, close the oldest file
61
+ if len(self.open_files) >= self.max_open_files:
62
+ oldest_ref = self.open_files.pop(0)
63
+ oldest_file = oldest_ref()
64
+ if oldest_file is not None and oldest_file._file is not None:
65
+ oldest_file.close()
66
+ log.debug(f"Auto-closed file due to descriptor limit: {oldest_file.file_path}")
67
+
68
+ # Add the new file to the end of the list
69
+ self.open_files.append(weakref.ref(lazy_file_loader))
70
+
71
+ def unregister_file(self, lazy_file_loader):
72
+ """Remove a file from the tracking list when it's closed."""
73
+ with self._lock:
74
+ self.open_files = [ref for ref in self.open_files
75
+ if ref() is not None and ref() is not lazy_file_loader]
76
+
77
+
78
+ # Global instance
79
+ _fd_manager = FileDescriptorManager()
80
+
81
+
82
+ class LazyFileLoader:
83
+ """
84
+ A file-like object that only opens the actual file when needed for reading.
85
+ This prevents keeping too many file descriptors open simultaneously.
86
+
87
+ This class implements the standard file-like interface that requests library
88
+ expects for multipart uploads, making it a drop-in replacement for regular
89
+ file objects.
90
+ """
91
+
92
+ def __init__(self, file_path: str, name: str):
93
+ self.file_path = file_path
94
+ self.name = name
95
+ self._file = None
96
+ self._closed = False
97
+ self._position = 0
98
+ self._size = None
99
+
100
+ def _ensure_open(self):
101
+ """Ensure the file is open and seek to the correct position."""
102
+ if self._closed:
103
+ raise ValueError("I/O operation on closed file.")
104
+
105
+ if self._file is None:
106
+ try:
107
+ self._file = open(self.file_path, 'rb')
108
+ _fd_manager.register_file_open(self)
109
+ log.debug(f"Opened file for reading: {self.file_path}")
110
+ # Seek to the current position if we've been reading before
111
+ if self._position > 0:
112
+ self._file.seek(self._position)
113
+ except OSError as e:
114
+ if e.errno == 24: # Too many open files
115
+ # Try to force garbage collection to close unused files
116
+ import gc
117
+ gc.collect()
118
+ # Retry once
119
+ self._file = open(self.file_path, 'rb')
120
+ _fd_manager.register_file_open(self)
121
+ log.debug(f"Opened file for reading (after gc): {self.file_path}")
122
+ if self._position > 0:
123
+ self._file.seek(self._position)
124
+ else:
125
+ raise
126
+
127
+ def _get_size(self):
128
+ """Get file size without keeping file open."""
129
+ if self._size is None:
130
+ self._size = os.path.getsize(self.file_path)
131
+ return self._size
132
+
133
+ def read(self, size: int = -1):
134
+ """Read from the file, opening it if needed."""
135
+ self._ensure_open()
136
+ data = self._file.read(size)
137
+ self._position = self._file.tell()
138
+
139
+ # If we've read the entire file, close it to free the file descriptor
140
+ if size == -1 or len(data) < size:
141
+ self.close()
142
+
143
+ return data
144
+
145
+ def readline(self, size: int = -1):
146
+ """Read a line from the file."""
147
+ self._ensure_open()
148
+ data = self._file.readline(size)
149
+ self._position = self._file.tell()
150
+ return data
151
+
152
+ def seek(self, offset: int, whence: int = 0):
153
+ """Seek to a position in the file."""
154
+ if self._closed:
155
+ raise ValueError("I/O operation on closed file.")
156
+
157
+ # Calculate new position for tracking
158
+ if whence == 0: # SEEK_SET
159
+ self._position = offset
160
+ elif whence == 1: # SEEK_CUR
161
+ self._position += offset
162
+ elif whence == 2: # SEEK_END
163
+ # We need to open the file to get its size
164
+ self._ensure_open()
165
+ result = self._file.seek(offset, whence)
166
+ self._position = self._file.tell()
167
+ return result
168
+
169
+ # If file is already open, seek it too
170
+ if self._file is not None:
171
+ result = self._file.seek(self._position)
172
+ return result
173
+
174
+ return self._position
175
+
176
+ def tell(self):
177
+ """Return current file position."""
178
+ if self._closed:
179
+ raise ValueError("I/O operation on closed file.")
180
+
181
+ if self._file is not None:
182
+ self._position = self._file.tell()
183
+
184
+ return self._position
185
+
186
+ def close(self):
187
+ """Close the file if it was opened."""
188
+ if self._file is not None:
189
+ self._file.close()
190
+ log.debug(f"Closed file: {self.file_path}")
191
+ self._file = None
192
+ _fd_manager.unregister_file(self)
193
+ self._closed = True
194
+
195
+ def __enter__(self):
196
+ return self
197
+
198
+ def __exit__(self, exc_type, exc_val, exc_tb):
199
+ self.close()
200
+
201
+ def __len__(self):
202
+ """Return file size. Requests library uses this for Content-Length."""
203
+ return self._get_size()
204
+
205
+ @property
206
+ def closed(self):
207
+ """Check if the file is closed."""
208
+ return self._closed
209
+
210
+ @property
211
+ def mode(self):
212
+ """Return the file mode."""
213
+ return 'rb'
214
+
215
+ def readable(self):
216
+ """Return whether the file is readable."""
217
+ return not self._closed
218
+
219
+ def writable(self):
220
+ """Return whether the file is writable."""
221
+ return False
222
+
223
+ def seekable(self):
224
+ """Return whether the file supports seeking."""
225
+ return True
226
+
227
+
228
+ class Utils:
229
+ @staticmethod
230
+ def validate_integration_type(integration_type: str) -> IntegrationType:
231
+ if integration_type not in INTEGRATION_TYPES:
232
+ raise ValueError(f"Invalid integration type: {integration_type}")
233
+ return integration_type # type: ignore
234
+
235
+ @staticmethod
236
+ def load_files_for_sending_lazy(files: List[str], workspace: str = None, max_open_files: int = 100) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
237
+ """
238
+ Prepares files for sending to the Socket API using lazy loading.
239
+
240
+ This version doesn't open all files immediately, instead it creates
241
+ LazyFileLoader objects that only open files when they're actually read.
242
+ This prevents "Too many open files" errors when dealing with large numbers
243
+ of manifest files.
244
+
245
+ Args:
246
+ files: List of file paths from find_files()
247
+ workspace: Base directory path to make paths relative to
248
+ max_open_files: Maximum number of files to keep open simultaneously (default: 100)
249
+
250
+ Returns:
251
+ List of tuples formatted for requests multipart upload:
252
+ [(field_name, (filename, lazy_file_object)), ...]
253
+ """
254
+ # Configure the file descriptor manager with the specified limit
255
+ _fd_manager.set_max_open_files(max_open_files)
256
+
257
+ send_files = []
258
+ if workspace and "\\" in workspace:
259
+ workspace = workspace.replace("\\", "/")
260
+
261
+ for file_path in files:
262
+ # Normalize file path
263
+ if "\\" in file_path:
264
+ file_path = file_path.replace("\\", "/")
265
+
266
+ _, name = file_path.rsplit("/", 1)
267
+
268
+ # Calculate the key (relative path from workspace)
269
+ if workspace and file_path.startswith(workspace):
270
+ key = file_path[len(workspace):]
271
+ else:
272
+ key = file_path
273
+
274
+ key = key.lstrip("/")
275
+ key = key.lstrip("./")
276
+
277
+ # Create lazy file loader instead of opening file immediately
278
+ # Use the relative path (key) as filename instead of truncated basename
279
+ lazy_file = LazyFileLoader(file_path, key)
280
+ payload = (key, (key, lazy_file))
281
+ send_files.append(payload)
282
+
283
+ log.debug(f"Prepared {len(send_files)} files for lazy loading")
284
+ return send_files
socketdev/version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "3.0.0"