socketdev 3.0.6__py3-none-any.whl → 3.0.14__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
@@ -24,6 +24,7 @@ from socketdev.apitokens import ApiTokens
24
24
  from socketdev.auditlog import AuditLog
25
25
  from socketdev.analytics import Analytics
26
26
  from socketdev.alerttypes import AlertTypes
27
+ from socketdev.basics import Basics
27
28
  from socketdev.log import log
28
29
 
29
30
  __author__ = "socket.dev"
@@ -72,6 +73,7 @@ class socketdev:
72
73
  self.auditlog = AuditLog(self.api)
73
74
  self.analytics = Analytics(self.api)
74
75
  self.alerttypes = AlertTypes(self.api)
76
+ self.basics = Basics(self.api)
75
77
 
76
78
  @staticmethod
77
79
  def set_timeout(timeout: int):
@@ -0,0 +1,120 @@
1
+ import logging
2
+ from typing import Optional, Union
3
+ from dataclasses import dataclass, asdict
4
+
5
+ log = logging.getLogger("socketdev")
6
+
7
+
8
+ @dataclass
9
+ class SocketBasicsConfig:
10
+ """Data class representing Socket Basics configuration settings."""
11
+ pythonSastEnabled: bool = False
12
+ golangSastEnabled: bool = False
13
+ javascriptSastEnabled: bool = False
14
+ secretScanningEnabled: bool = False
15
+ trivyImageEnabled: bool = False
16
+ trivyDockerfileEnabled: bool = False
17
+ socketScanningEnabled: bool = False
18
+ socketScaEnabled: bool = False
19
+ additionalParameters: str = ""
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) -> "SocketBasicsConfig":
29
+ return cls(
30
+ pythonSastEnabled=data.get("pythonSastEnabled", False),
31
+ golangSastEnabled=data.get("golangSastEnabled", False),
32
+ javascriptSastEnabled=data.get("javascriptSastEnabled", False),
33
+ secretScanningEnabled=data.get("secretScanningEnabled", False),
34
+ trivyImageEnabled=data.get("trivyImageEnabled", False),
35
+ trivyDockerfileEnabled=data.get("trivyDockerfileEnabled", False),
36
+ socketScanningEnabled=data.get("socketScanningEnabled", False),
37
+ socketScaEnabled=data.get("socketScaEnabled", False),
38
+ additionalParameters=data.get("additionalParameters", ""),
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class SocketBasicsResponse:
44
+ """Data class representing the response from Socket Basics API calls."""
45
+ success: bool
46
+ status: int
47
+ config: Optional[SocketBasicsConfig] = None
48
+ message: Optional[str] = None
49
+
50
+ def __getitem__(self, key):
51
+ return getattr(self, key)
52
+
53
+ def to_dict(self):
54
+ return asdict(self)
55
+
56
+ @classmethod
57
+ def from_dict(cls, data: dict) -> "SocketBasicsResponse":
58
+ return cls(
59
+ config=SocketBasicsConfig.from_dict(data) if data else None,
60
+ success=True,
61
+ status=200,
62
+ )
63
+
64
+
65
+ class Basics:
66
+ """
67
+ Socket Basics API client for managing CI/CD security scanning configurations.
68
+
69
+ Socket Basics is a security scanning suite that includes:
70
+ - SAST (Static Application Security Testing) for Python, Go, and JavaScript
71
+ - Secret scanning for hardcoded credentials
72
+ - Container security for Docker images and Dockerfiles
73
+ - Socket SCA dependency scanning
74
+ """
75
+
76
+ def __init__(self, api):
77
+ self.api = api
78
+
79
+ def get_config(
80
+ self, org_slug: str, use_types: bool = False
81
+ ) -> Union[dict, SocketBasicsResponse]:
82
+ """
83
+ Get Socket Basics configuration for an organization.
84
+
85
+ Args:
86
+ org_slug: Organization slug
87
+ use_types: Whether to return typed response objects (default: False)
88
+
89
+ Returns:
90
+ dict or SocketBasicsResponse: Configuration settings for Socket Basics
91
+
92
+ Example:
93
+ >>> basics = socketdev_client.basics
94
+ >>> config = basics.get_config("my-org")
95
+ >>> print(config["pythonSastEnabled"])
96
+
97
+ >>> # Using typed response
98
+ >>> response = basics.get_config("my-org", use_types=True)
99
+ >>> print(response.config.pythonSastEnabled)
100
+ """
101
+ path = f"orgs/{org_slug}/settings/socket-basics"
102
+ response = self.api.do_request(path=path, method="GET")
103
+
104
+ if response.status_code == 200:
105
+ config_data = response.json()
106
+ if use_types:
107
+ return SocketBasicsResponse.from_dict(config_data)
108
+ return config_data
109
+
110
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
111
+ log.error(f"Failed to get Socket Basics configuration: {response.status_code}, message: {error_message}")
112
+
113
+ if use_types:
114
+ return SocketBasicsResponse(
115
+ success=False,
116
+ status=response.status_code,
117
+ config=None,
118
+ message=error_message
119
+ )
120
+ return {}
socketdev/core/dedupe.py CHANGED
@@ -13,7 +13,7 @@ class Dedupe:
13
13
  return (
14
14
  alert["type"],
15
15
  alert["severity"],
16
- alert["category"],
16
+ alert.get("category"),
17
17
  Dedupe.normalize_file_path(alert.get("file")),
18
18
  alert.get("start"),
19
19
  alert.get("end")
@@ -25,7 +25,7 @@ class Dedupe:
25
25
  return (
26
26
  alert["type"],
27
27
  alert["severity"],
28
- alert["category"],
28
+ alert.get("category"),
29
29
  Dedupe.normalize_file_path(alert.get("file")),
30
30
  alert.get("start"),
31
31
  alert.get("end")
@@ -39,21 +39,29 @@ class Dedupe:
39
39
 
40
40
  for alert in pkg.get("alerts", []):
41
41
  identity = alert_identity(alert)
42
- file = Dedupe.normalize_file_path(alert.get("file"))
43
42
 
44
43
  if identity not in alert_map:
45
- alert_map[identity] = {
44
+ # Build alert dict with only fields that exist in the original alert
45
+ consolidated_alert = {
46
46
  "key": alert["key"], # keep the first key seen
47
47
  "type": alert["type"],
48
48
  "severity": alert["severity"],
49
- "category": alert["category"],
50
- "file": file,
51
- "start": alert.get("start"),
52
- "end": alert.get("end"),
53
49
  "releases": [release],
54
50
  "props": alert.get("props", []),
55
51
  "action": alert["action"]
56
52
  }
53
+
54
+ # Only include optional fields if they exist in the original alert
55
+ if "category" in alert:
56
+ consolidated_alert["category"] = alert["category"]
57
+ if "file" in alert:
58
+ consolidated_alert["file"] = Dedupe.normalize_file_path(alert["file"])
59
+ if "start" in alert:
60
+ consolidated_alert["start"] = alert["start"]
61
+ if "end" in alert:
62
+ consolidated_alert["end"] = alert["end"]
63
+
64
+ alert_map[identity] = consolidated_alert
57
65
  else:
58
66
  if release not in alert_map[identity]["releases"]:
59
67
  alert_map[identity]["releases"].append(release)
@@ -269,63 +269,77 @@ class Utils:
269
269
  if "\\" in file_path:
270
270
  file_path = file_path.replace("\\", "/")
271
271
 
272
- _, name = file_path.rsplit("/", 1)
272
+ for file_path in files:
273
+ # Normalize file path
274
+ if "\\" in file_path:
275
+ file_path = file_path.replace("\\", "/")
273
276
 
274
- # Calculate the key name for the form data
275
- key = file_path
276
- path_stripped = False
277
-
278
- # If base_paths is provided, try to strip one of the paths from the file path
279
- if base_paths:
280
- for bp in base_paths:
281
- # Normalize base_path to ensure consistent handling of trailing slashes
282
- normalized_base_path = bp.rstrip("/") + "/" if not bp.endswith("/") else bp
277
+ # Skip directories
278
+ if os.path.isdir(file_path):
279
+ continue
280
+
281
+ # Handle file path splitting safely
282
+ if "/" in file_path:
283
+ _, name = file_path.rsplit("/", 1)
284
+ else:
285
+ name = file_path
286
+
287
+ # Calculate the key name for the form data
288
+ key = file_path
289
+ path_stripped = False
290
+
291
+ # If base_paths is provided, try to strip one of the paths from the file path
292
+ if base_paths:
293
+ for bp in base_paths:
294
+ normalized_base_path = bp.rstrip("/") + "/" if not bp.endswith("/") else bp
295
+ if key.startswith(normalized_base_path):
296
+ key = key[len(normalized_base_path):]
297
+ path_stripped = True
298
+ break
299
+ elif key.startswith(bp.rstrip("/")):
300
+ stripped_base = bp.rstrip("/")
301
+ if key.startswith(stripped_base + "/") or key == stripped_base:
302
+ key = key[len(stripped_base):]
303
+ key = key.lstrip("/")
304
+ path_stripped = True
305
+ break
306
+ elif base_path:
307
+ normalized_base_path = base_path.rstrip("/") + "/" if not base_path.endswith("/") else base_path
283
308
  if key.startswith(normalized_base_path):
284
309
  key = key[len(normalized_base_path):]
285
310
  path_stripped = True
286
- break
287
- elif key.startswith(bp.rstrip("/")):
288
- # Handle case where base_path matches exactly without trailing slash
289
- stripped_base = bp.rstrip("/")
311
+ elif key.startswith(base_path.rstrip("/")):
312
+ stripped_base = base_path.rstrip("/")
290
313
  if key.startswith(stripped_base + "/") or key == stripped_base:
291
314
  key = key[len(stripped_base):]
292
315
  key = key.lstrip("/")
293
316
  path_stripped = True
294
- break
295
-
296
- # If base_path is provided and no base_paths matched, use single base_path
297
- elif base_path:
298
- # Normalize base_path to ensure consistent handling of trailing slashes
299
- normalized_base_path = base_path.rstrip("/") + "/" if not base_path.endswith("/") else base_path
300
- if key.startswith(normalized_base_path):
301
- key = key[len(normalized_base_path):]
317
+
318
+ # If workspace is provided and no base paths matched, fall back to workspace logic
319
+ if not path_stripped and workspace and file_path.startswith(workspace):
320
+ key = file_path[len(workspace):]
321
+ # Remove all leading slashes (for absolute paths)
322
+ while key.startswith("/"):
323
+ key = key[1:]
302
324
  path_stripped = True
303
- elif key.startswith(base_path.rstrip("/")):
304
- # Handle case where base_path matches exactly without trailing slash
305
- stripped_base = base_path.rstrip("/")
306
- if key.startswith(stripped_base + "/") or key == stripped_base:
307
- key = key[len(stripped_base):]
308
- key = key.lstrip("/")
309
- path_stripped = True
310
-
311
- # If workspace is provided and no base paths matched, fall back to workspace logic
312
- if not path_stripped and workspace and file_path.startswith(workspace):
313
- key = file_path[len(workspace):]
314
- key = key.lstrip("/")
315
- key = key.lstrip("./")
316
- 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("./")
323
325
 
324
- # Create lazy file loader instead of opening file immediately
325
- # Use the relative path (key) as filename instead of truncated basename
326
- lazy_file = LazyFileLoader(file_path, key)
327
- payload = (key, (key, lazy_file))
328
- send_files.append(payload)
326
+ # Clean up relative path prefixes, but preserve filename dots
327
+ while key.startswith("./"):
328
+ key = key[2:]
329
+ while key.startswith("../"):
330
+ key = key[3:]
331
+ # Remove any remaining leading slashes (for absolute paths)
332
+ while key.startswith("/"):
333
+ key = key[1:]
334
+
335
+ # Remove Windows drive letter if present (C:/...)
336
+ if len(key) > 2 and key[1] == ':' and (key[2] == '/' or key[2] == '\\'):
337
+ key = key[2:]
338
+ while key.startswith("/"):
339
+ key = key[1:]
329
340
 
330
- log.debug(f"Prepared {len(send_files)} files for lazy loading")
331
- return send_files
341
+ # Create lazy file loader instead of opening file immediately
342
+ lazy_file = LazyFileLoader(file_path, key)
343
+ payload = (key, (key, lazy_file))
344
+ send_files.append(payload)
345
+ return send_files
socketdev/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "3.0.6"
1
+ __version__ = "3.0.14"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: socketdev
3
- Version: 3.0.6
3
+ Version: 3.0.14
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>
@@ -355,6 +355,46 @@ Get GitHub Flavored Markdown diff between two full scans.
355
355
  - **before (str)** - The base full scan ID
356
356
  - **after (str)** - The comparison full scan ID
357
357
 
358
+ basics.get_config(org_slug, use_types)
359
+ """"""""""""""""""""""""""""""""""""""
360
+ Get Socket Basics configuration for an organization. Socket Basics is a CI/CD security scanning suite that includes SAST scanning, secret detection, container security, and dependency analysis.
361
+
362
+ **Usage:**
363
+
364
+ .. code-block:: python
365
+
366
+ from socketdev import socketdev
367
+ socket = socketdev(token="REPLACE_ME")
368
+
369
+ # Basic usage - returns dictionary
370
+ config = socket.basics.get_config("org_slug")
371
+ print(f"Python SAST enabled: {config['pythonSastEnabled']}")
372
+ print(f"Secret scanning enabled: {config['secretScanningEnabled']}")
373
+
374
+ # Using typed response objects
375
+ from socketdev.basics import SocketBasicsConfig, SocketBasicsResponse
376
+ response = socket.basics.get_config("org_slug", use_types=True)
377
+ if response.success and response.config:
378
+ print(f"JavaScript SAST: {response.config.javascriptSastEnabled}")
379
+ print(f"Trivy scanning: {response.config.trivyImageEnabled}")
380
+
381
+ **PARAMETERS:**
382
+
383
+ - **org_slug (str)** - The organization name
384
+ - **use_types (bool)** - Whether to return typed response objects (default: False)
385
+
386
+ **Socket Basics Features:**
387
+
388
+ - **Python SAST** - Static analysis for Python code
389
+ - **Go SAST** - Static analysis for Go code
390
+ - **JavaScript SAST** - Static analysis for JavaScript/TypeScript code
391
+ - **Secret Scanning** - Detection of hardcoded secrets and credentials
392
+ - **Trivy Image Scanning** - Vulnerability scanning for Docker images
393
+ - **Trivy Dockerfile Scanning** - Vulnerability scanning for Dockerfiles
394
+ - **Socket SCA** - Supply chain analysis for dependencies
395
+ - **Socket Scanning** - General dependency security scanning
396
+ - **Additional Parameters** - Custom configuration options
397
+
358
398
  dependencies.get(limit, offset)
359
399
  """""""""""""""""""""""""""""""
360
400
  Retrieve the dependencies for the organization associated with the API Key
@@ -1,14 +1,15 @@
1
- socketdev/__init__.py,sha256=wcxhpItn-ZkKQYJSsmkHKDaGdtCbWPMvb_delK2xbdU,2811
1
+ socketdev/__init__.py,sha256=oWS-XPjIu0o75jcHLJyhiR47u-uPLZ7BM4nhpdyxZvw,2888
2
2
  socketdev/exceptions.py,sha256=SNU1EgswGwnxI_Zmm325ruP6CFg5C4MsS1qxXWwBJqs,1120
3
3
  socketdev/log.py,sha256=AgEcsPN3y9U-fze8pTFvLigVvNob2vmNC-TkOOQkkeQ,90
4
- socketdev/version.py,sha256=uC8HeJcsNKDMSm12PYMv69I4zC6ciz4KILeBXWW_c8g,22
4
+ socketdev/version.py,sha256=58nfUJ61Il-p2ZdVf2gSLjPEImF5AgR3gUR-VmZM5VA,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
8
8
  socketdev/auditlog/__init__.py,sha256=vjcVtOK6oujqC6-RW5Hrvmth5BqFkLdinbeyqtycOpA,881
9
+ socketdev/basics/__init__.py,sha256=9jTEwC4dMUV-9pKpU4twK-hM1cY0xeXAxjDrb37sxoQ,4067
9
10
  socketdev/core/api.py,sha256=xymEv2szAwZXDsTI4nRC_zcqoSVAenQ-TceNuHfkwbE,5773
10
11
  socketdev/core/classes.py,sha256=fyDlolgnkpHFb1dMHa2SA0czCS1I6Tr3SuYb1a67-dY,3756
11
- socketdev/core/dedupe.py,sha256=pe3w51nEPoCXC6GeGaqjusTNCW3WuYAElEU2Wq4j88w,5003
12
+ socketdev/core/dedupe.py,sha256=bvX92ia4anVQtEv18LaLupisuHg68eNPuLZjmLhhAGE,5493
12
13
  socketdev/core/issues.py,sha256=jIfi6h1Y-d38OgxSFhlgC74TLvY6IfUcWhQfLq8FFPo,68147
13
14
  socketdev/dependencies/__init__.py,sha256=zdAb0lMYF8tTHFWa9kGwz5dv4_Sp1UpzQseg_4_qBfY,2170
14
15
  socketdev/diffscans/__init__.py,sha256=ndsgyFmsvK29pJAEhZyBByZ9ampf1Ks6oV8y1q7mssw,5294
@@ -30,8 +31,8 @@ socketdev/settings/__init__.py,sha256=CCRAnFWOvm7Hi4LY0gbFqsOFHNDlWK3FHei0Edcv_-
30
31
  socketdev/threatfeed/__init__.py,sha256=2SsJYKByXBkb2C1fGopwxejkr7mky0kggFKIunyV7Nk,1119
31
32
  socketdev/tools/__init__.py,sha256=ROvpEULLXTKby9DMsVFPlAlysjwfop1NhRqSrFUWprY,1969
32
33
  socketdev/triage/__init__.py,sha256=-h599vThVetfRSOAs1e4IUoMjcXS8xOsUfub41XPiX4,1559
33
- socketdev/utils/__init__.py,sha256=0MvfpYmrkTWbLY5jE2vCCFHwXM5mGnNbVmazl1tQHPg,13483
34
- socketdev-3.0.6.dist-info/METADATA,sha256=nrqsRqzG5bQ7vbGY-6EZjr8jf2P12B3rZC696T4nN48,34359
35
- socketdev-3.0.6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
36
- socketdev-3.0.6.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
37
- socketdev-3.0.6.dist-info/RECORD,,
34
+ socketdev/utils/__init__.py,sha256=gQBtAdElhpHSjHlB4GIecgJ-1P9aC8azs-eHRlyGCgc,13888
35
+ socketdev-3.0.14.dist-info/METADATA,sha256=y0fZ69AdF7f6VuJYtrhIjLnYvUV8PsCLGsItAmXppCc,36090
36
+ socketdev-3.0.14.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
37
+ socketdev-3.0.14.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
38
+ socketdev-3.0.14.dist-info/RECORD,,