socketdev 3.0.13__py3-none-any.whl → 3.0.16__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
@@ -25,6 +25,7 @@ from socketdev.auditlog import AuditLog
25
25
  from socketdev.analytics import Analytics
26
26
  from socketdev.alerttypes import AlertTypes
27
27
  from socketdev.basics import Basics
28
+ from socketdev.uploadmanifests import UploadManifests
28
29
  from socketdev.log import log
29
30
 
30
31
  __author__ = "socket.dev"
@@ -74,6 +75,7 @@ class socketdev:
74
75
  self.analytics = Analytics(self.api)
75
76
  self.alerttypes = AlertTypes(self.api)
76
77
  self.basics = Basics(self.api)
78
+ self.uploadmanifests = UploadManifests(self.api)
77
79
 
78
80
  @staticmethod
79
81
  def set_timeout(timeout: int):
@@ -0,0 +1,67 @@
1
+ import os
2
+ import logging
3
+ from typing import List, Optional, Union
4
+ from ..utils import Utils
5
+
6
+ log = logging.getLogger("socketdev")
7
+
8
+
9
+ class UploadManifests:
10
+ def __init__(self, api):
11
+ self.api = api
12
+
13
+ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace: Optional[str] = None, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None, use_lazy_loading: bool = True) -> str:
14
+ """
15
+ Upload manifest files to Socket API and return tarHash.
16
+
17
+ Args:
18
+ org_slug: Organization slug
19
+ file_paths: List of manifest file paths to upload
20
+ workspace: Base directory path to make paths relative to
21
+ base_path: Optional base path to strip from key names for cleaner file organization
22
+ base_paths: Optional list of base paths to strip from key names (takes precedence over base_path)
23
+ use_lazy_loading: Whether to use lazy file loading (default: True)
24
+
25
+ Returns:
26
+ str: The tarHash from the upload response
27
+
28
+ Raises:
29
+ Exception: If upload fails
30
+ """
31
+ # Filter to only existing files
32
+ valid_files = [f for f in file_paths if os.path.exists(f) and os.path.isfile(f)]
33
+
34
+ if not valid_files:
35
+ raise Exception("No valid manifest files found to upload")
36
+
37
+ # Prepare files for upload using the utility function
38
+ if use_lazy_loading:
39
+ loaded_files = Utils.load_files_for_sending_lazy(
40
+ valid_files,
41
+ workspace=workspace,
42
+ base_path=base_path,
43
+ base_paths=base_paths
44
+ )
45
+ else:
46
+ # Fallback to basic file loading if needed
47
+ loaded_files = []
48
+ for file_path in valid_files:
49
+ key = os.path.basename(file_path)
50
+ with open(file_path, 'rb') as f:
51
+ loaded_files.append((key, (key, f.read())))
52
+
53
+ # Make the upload request
54
+ path = f"orgs/{org_slug}/upload-manifest-files"
55
+ response = self.api.do_request(path=path, files=loaded_files, method="POST")
56
+
57
+ if response.status_code != 200:
58
+ raise Exception(f"Upload failed with status {response.status_code}: {response.text}")
59
+
60
+ result = response.json()
61
+ tar_hash = result.get('tarHash')
62
+
63
+ if not tar_hash:
64
+ raise Exception("Server did not return a tarHash")
65
+
66
+ log.info(f"Successfully uploaded {len(valid_files)} manifest files, tarHash: {tar_hash}")
67
+ return tar_hash
@@ -1,4 +1,4 @@
1
- from typing import Literal, List, Tuple
1
+ from typing import Literal, List, Tuple, Optional
2
2
  import logging
3
3
  import os
4
4
  import weakref
@@ -233,7 +233,7 @@ class Utils:
233
233
  return integration_type # type: ignore
234
234
 
235
235
  @staticmethod
236
- def load_files_for_sending_lazy(files: List[str], workspace: str = None, max_open_files: int = 100, base_path: str = None, base_paths: List[str] = None) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
236
+ def load_files_for_sending_lazy(files: List[str], workspace: Optional[str] = None, max_open_files: int = 100, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
237
237
  """
238
238
  Prepares files for sending to the Socket API using lazy loading.
239
239
 
@@ -268,61 +268,72 @@ class Utils:
268
268
  # Normalize file path
269
269
  if "\\" in file_path:
270
270
  file_path = file_path.replace("\\", "/")
271
-
272
- _, name = file_path.rsplit("/", 1)
271
+
272
+ # Skip directories
273
+ if os.path.isdir(file_path):
274
+ continue
275
+
276
+ # Handle file path splitting safely
277
+ if "/" in file_path:
278
+ _, name = file_path.rsplit("/", 1)
279
+ else:
280
+ name = file_path
273
281
 
274
282
  # Calculate the key name for the form data
275
283
  key = file_path
276
284
  path_stripped = False
277
-
285
+
278
286
  # If base_paths is provided, try to strip one of the paths from the file path
279
287
  if base_paths:
280
288
  for bp in base_paths:
281
- # Normalize base_path to ensure consistent handling of trailing slashes
282
289
  normalized_base_path = bp.rstrip("/") + "/" if not bp.endswith("/") else bp
283
290
  if key.startswith(normalized_base_path):
284
291
  key = key[len(normalized_base_path):]
285
292
  path_stripped = True
286
293
  break
287
294
  elif key.startswith(bp.rstrip("/")):
288
- # Handle case where base_path matches exactly without trailing slash
289
295
  stripped_base = bp.rstrip("/")
290
296
  if key.startswith(stripped_base + "/") or key == stripped_base:
291
297
  key = key[len(stripped_base):]
292
298
  key = key.lstrip("/")
293
299
  path_stripped = True
294
300
  break
295
-
296
- # If base_path is provided and no base_paths matched, use single base_path
297
301
  elif base_path:
298
- # Normalize base_path to ensure consistent handling of trailing slashes
299
302
  normalized_base_path = base_path.rstrip("/") + "/" if not base_path.endswith("/") else base_path
300
303
  if key.startswith(normalized_base_path):
301
304
  key = key[len(normalized_base_path):]
302
305
  path_stripped = True
303
306
  elif key.startswith(base_path.rstrip("/")):
304
- # Handle case where base_path matches exactly without trailing slash
305
307
  stripped_base = base_path.rstrip("/")
306
308
  if key.startswith(stripped_base + "/") or key == stripped_base:
307
309
  key = key[len(stripped_base):]
308
310
  key = key.lstrip("/")
309
311
  path_stripped = True
310
-
312
+
311
313
  # If workspace is provided and no base paths matched, fall back to workspace logic
312
314
  if not path_stripped and workspace and file_path.startswith(workspace):
313
315
  key = file_path[len(workspace):]
314
- key = key.lstrip("/")
315
- key = key.lstrip("./")
316
+ # Remove all leading slashes (for absolute paths)
317
+ while key.startswith("/"):
318
+ key = key[1:]
316
319
  path_stripped = True
317
-
318
- # If no path stripping occurred, clean up the key
319
- if not path_stripped:
320
- # No base_path, base_paths, or workspace stripping occurred, clean up leading parts
321
- key = key.lstrip("/")
322
- key = key.lstrip("./")
320
+
321
+ # Clean up relative path prefixes, but preserve filename dots
322
+ while key.startswith("./"):
323
+ key = key[2:]
324
+ while key.startswith("../"):
325
+ key = key[3:]
326
+ # Remove any remaining leading slashes (for absolute paths)
327
+ while key.startswith("/"):
328
+ key = key[1:]
329
+
330
+ # Remove Windows drive letter if present (C:/...)
331
+ if len(key) > 2 and key[1] == ':' and (key[2] == '/' or key[2] == '\\'):
332
+ key = key[2:]
333
+ while key.startswith("/"):
334
+ key = key[1:]
323
335
 
324
336
  # Create lazy file loader instead of opening file immediately
325
- # Use the relative path (key) as filename instead of truncated basename
326
337
  lazy_file = LazyFileLoader(file_path, key)
327
338
  payload = (key, (key, lazy_file))
328
339
  send_files.append(payload)
socketdev/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "3.0.13"
1
+ __version__ = "3.0.16"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: socketdev
3
- Version: 3.0.13
3
+ Version: 3.0.16
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,7 @@
1
- socketdev/__init__.py,sha256=oWS-XPjIu0o75jcHLJyhiR47u-uPLZ7BM4nhpdyxZvw,2888
1
+ socketdev/__init__.py,sha256=aZhHDONQpWnX-Doxf_NNClJREgu-aXvGaEv6xPrYRgI,3001
2
2
  socketdev/exceptions.py,sha256=SNU1EgswGwnxI_Zmm325ruP6CFg5C4MsS1qxXWwBJqs,1120
3
3
  socketdev/log.py,sha256=AgEcsPN3y9U-fze8pTFvLigVvNob2vmNC-TkOOQkkeQ,90
4
- socketdev/version.py,sha256=ke1rwjyXlCOHnJ2lhlgdf61bsdFmmfXKtfFoY6LDF88,23
4
+ socketdev/version.py,sha256=PqtbPq3twQFhrmoNUmgkuDLFZ2kj-AYNbWriNF-hNQM,23
5
5
  socketdev/alerttypes/__init__.py,sha256=W-m2D9VxbepSAUELJPmWmX40zksGZbQcSzwQ1kjlB1k,1169
6
6
  socketdev/analytics/__init__.py,sha256=kQGeO67TraqvfmYjfpYCvcNRtxW2a6x5EefEl6Jnca8,2223
7
7
  socketdev/apitokens/__init__.py,sha256=Z6W9Jkh4gdDeJBivfcONZuz7jRKZtxWLTi1n9gkbYVE,4222
@@ -31,8 +31,9 @@ socketdev/settings/__init__.py,sha256=CCRAnFWOvm7Hi4LY0gbFqsOFHNDlWK3FHei0Edcv_-
31
31
  socketdev/threatfeed/__init__.py,sha256=2SsJYKByXBkb2C1fGopwxejkr7mky0kggFKIunyV7Nk,1119
32
32
  socketdev/tools/__init__.py,sha256=ROvpEULLXTKby9DMsVFPlAlysjwfop1NhRqSrFUWprY,1969
33
33
  socketdev/triage/__init__.py,sha256=-h599vThVetfRSOAs1e4IUoMjcXS8xOsUfub41XPiX4,1559
34
- socketdev/utils/__init__.py,sha256=0MvfpYmrkTWbLY5jE2vCCFHwXM5mGnNbVmazl1tQHPg,13483
35
- socketdev-3.0.13.dist-info/METADATA,sha256=JzAUlRqjOllvDsChtVwVniarefstBFuS3wMGRHGIZgw,36090
36
- socketdev-3.0.13.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
37
- socketdev-3.0.13.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
38
- socketdev-3.0.13.dist-info/RECORD,,
34
+ socketdev/uploadmanifests/__init__.py,sha256=7ekyDEa0GCyoLVZUwobgc5jP6hzO-QI45Gz0Cw0nesg,2652
35
+ socketdev/utils/__init__.py,sha256=27OgKDg_0lcrSCUy5g1CV_LTv2_OYb9-wkNiamlTntc,13567
36
+ socketdev-3.0.16.dist-info/METADATA,sha256=C6jbmqkQC2C-upL-CJufkwpRWPTMtyhEZx3OtINithI,36090
37
+ socketdev-3.0.16.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
38
+ socketdev-3.0.16.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
39
+ socketdev-3.0.16.dist-info/RECORD,,