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,48 @@
1
+ import json
2
+ from urllib.parse import urlencode
3
+ import logging
4
+ from socketdev.tools import load_files
5
+ from ..utils import Utils
6
+
7
+ log = logging.getLogger("socketdev")
8
+
9
+ # TODO: Add types for responses. Not currently used in the CLI.
10
+
11
+
12
+ class Dependencies:
13
+ def __init__(self, api):
14
+ self.api = api
15
+
16
+ def post(self, files: list, params: dict, use_lazy_loading: bool = False, workspace: str = None) -> dict:
17
+ if use_lazy_loading:
18
+ loaded_files = Utils.load_files_for_sending_lazy(files, workspace)
19
+ else:
20
+ loaded_files = []
21
+ loaded_files = load_files(files, loaded_files)
22
+
23
+ path = "dependencies/upload?" + urlencode(params)
24
+ response = self.api.do_request(path=path, files=loaded_files, method="POST")
25
+ if response.status_code == 200:
26
+ result = response.json()
27
+ else:
28
+ result = {}
29
+ log.error(f"Error posting {files} to the Dependency API")
30
+ log.error(response.text)
31
+ return result
32
+
33
+ def get(
34
+ self,
35
+ limit: int = 50,
36
+ offset: int = 0,
37
+ ) -> dict:
38
+ path = "dependencies/search"
39
+ payload = {"limit": limit, "offset": offset}
40
+ payload_str = json.dumps(payload)
41
+ response = self.api.do_request(path=path, method="POST", payload=payload_str)
42
+ if response.status_code == 200:
43
+ result = response.json()
44
+ else:
45
+ result = {}
46
+ log.error("Unable to retrieve Dependencies")
47
+ log.error(response.text)
48
+ return result
@@ -0,0 +1,105 @@
1
+ import json
2
+ import logging
3
+ from typing import Any, Dict, Optional, Union
4
+ from ..utils import Utils
5
+
6
+ log = logging.getLogger("socketdev")
7
+
8
+ class DiffScans:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def list(self, org_slug: str, params: Optional[Dict[str, Any]] = None) -> dict:
13
+ """List all diff scans for an organization."""
14
+ path = f"orgs/{org_slug}/diff-scans"
15
+ if params:
16
+ import urllib.parse
17
+ path += "?" + urllib.parse.urlencode(params)
18
+ response = self.api.do_request(path=path, method="GET")
19
+ if response.status_code == 200:
20
+ return response.json()
21
+ log.error(f"Error listing diff scans: {response.status_code}, message: {response.text}")
22
+ return {}
23
+
24
+ def get(self, org_slug: str, diff_scan_id: str) -> dict:
25
+ """Fetch a diff scan by ID."""
26
+ path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}"
27
+ response = self.api.do_request(path=path, method="GET")
28
+ if response.status_code == 200:
29
+ return response.json()
30
+ log.error(f"Error fetching diff scan: {response.status_code}, message: {response.text}")
31
+ return {}
32
+
33
+ def create_from_repo(self, org_slug: str, repo_slug: str, files: list, params: Optional[Dict[str, Any]] = None, use_lazy_loading: bool = False, workspace: str = None, max_open_files: int = 100) -> dict:
34
+ """
35
+ Create a diff scan from repo HEAD, uploading files as multipart form data.
36
+
37
+ Args:
38
+ org_slug: Organization slug
39
+ repo_slug: Repository slug
40
+ files: List of file paths to upload for scanning
41
+ params: Optional query parameters for the request
42
+ use_lazy_loading: Whether to use lazy file loading to prevent "too many open files"
43
+ errors when uploading large numbers of files (default: False)
44
+ NOTE: In version 3.0, this will default to True for better performance
45
+ workspace: Base directory path to make file paths relative to
46
+ max_open_files: Maximum number of files to keep open simultaneously when using
47
+ lazy loading. Useful for systems with low ulimit values (default: 100)
48
+
49
+ Returns:
50
+ dict: API response containing diff scan results
51
+
52
+ Note:
53
+ When use_lazy_loading=True, files are opened only when needed during upload,
54
+ preventing file descriptor exhaustion. The max_open_files parameter controls how many
55
+ files can be open simultaneously - set this lower on systems with restrictive ulimits.
56
+
57
+ For large file uploads (>100 files), it's recommended to set use_lazy_loading=True.
58
+ """
59
+ import urllib.parse
60
+ path = f"orgs/{org_slug}/diff-scans/from-repo/{repo_slug}"
61
+ if params:
62
+ path += "?" + urllib.parse.urlencode(params)
63
+
64
+ # Use lazy loading if requested
65
+ if use_lazy_loading:
66
+ prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files)
67
+ else:
68
+ prepared_files = files
69
+
70
+ response = self.api.do_request(path=path, method="POST", files=prepared_files)
71
+ if response.status_code in (200, 201):
72
+ return response.json()
73
+ log.error(f"Error creating diff scan from repo: {response.status_code}, message: {response.text}")
74
+ return {}
75
+
76
+ def create_from_ids(self, org_slug: str, params: Dict[str, Any]) -> dict:
77
+ """Create a diff scan from two full scan IDs using query params."""
78
+ import urllib.parse
79
+ path = f"orgs/{org_slug}/diff-scans/from-ids"
80
+ if params:
81
+ path += "?" + urllib.parse.urlencode(params)
82
+ response = self.api.do_request(path=path, method="POST")
83
+ if response.status_code in (200, 201):
84
+ return response.json()
85
+ log.error(f"Error creating diff scan from IDs: {response.status_code}, message: {response.text}")
86
+ return {}
87
+
88
+ def gfm(self, org_slug: str, diff_scan_id: str) -> dict:
89
+ """Fetch GFM (GitHub Flavored Markdown) comments for a diff scan."""
90
+ path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}/gfm"
91
+ response = self.api.do_request(path=path, method="GET")
92
+ if response.status_code == 200:
93
+ return response.json()
94
+ log.error(f"Error fetching diff scan GFM: {response.status_code}, message: {response.text}")
95
+ return {}
96
+
97
+ def delete(self, org_slug: str, diff_scan_id: str) -> bool:
98
+ """Delete a diff scan by ID."""
99
+ path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}"
100
+ response = self.api.do_request(path=path, method="DELETE")
101
+ if response.status_code == 200:
102
+ if "status" in response.json() and response.json()["status"] == "ok":
103
+ return True
104
+ log.error(f"Error deleting diff scan: {response.status_code}, message: {response.text}")
105
+ return False
@@ -0,0 +1,47 @@
1
+ class APIFailure(Exception):
2
+ """Base exception for all Socket API errors"""
3
+ pass
4
+
5
+
6
+ class APIKeyMissing(APIFailure):
7
+ """Raised when the api key is not passed and the headers are empty"""
8
+
9
+
10
+ class APIAccessDenied(APIFailure):
11
+ """Raised when access is denied to the API"""
12
+ pass
13
+
14
+
15
+ class APIInsufficientPermissions(APIFailure):
16
+ """Raised when the API token doesn't have required permissions"""
17
+ pass
18
+
19
+
20
+ class APIOrganizationNotAllowed(APIFailure):
21
+ """Raised when organization doesn't have access to the feature"""
22
+ pass
23
+
24
+
25
+ class APIInsufficientQuota(APIFailure):
26
+ """Raised when access is denied to the API due to quota limits"""
27
+ pass
28
+
29
+
30
+ class APIResourceNotFound(APIFailure):
31
+ """Raised when the requested resource is not found"""
32
+ pass
33
+
34
+
35
+ class APITimeout(APIFailure):
36
+ """Raised when a request times out"""
37
+ pass
38
+
39
+
40
+ class APIConnectionError(APIFailure):
41
+ """Raised when there's a connection error"""
42
+ pass
43
+
44
+
45
+ class APIBadGateway(APIFailure):
46
+ """Raised when the upstream server returns a 502 Bad Gateway error"""
47
+ pass
@@ -0,0 +1,75 @@
1
+ from urllib.parse import urlencode
2
+ from dataclasses import dataclass, asdict
3
+ from typing import Optional
4
+ import logging
5
+
6
+ log = logging.getLogger("socketdev")
7
+
8
+
9
+ @dataclass
10
+ class ExportQueryParams:
11
+ author: Optional[str] = None
12
+ project_group: Optional[str] = None
13
+ project_name: Optional[str] = None
14
+ project_version: Optional[str] = None
15
+ project_id: Optional[str] = None
16
+
17
+ def to_query_params(self) -> str:
18
+ # Filter out None values and convert to query string
19
+ params = {k: v for k, v in asdict(self).items() if v is not None}
20
+ if not params:
21
+ return ""
22
+ return "?" + urlencode(params)
23
+
24
+
25
+ class Export:
26
+ def __init__(self, api):
27
+ self.api = api
28
+
29
+ def cdx_bom(
30
+ self, org_slug: str, id: str, query_params: Optional[ExportQueryParams] = None, use_types: bool = False
31
+ ) -> dict:
32
+ """
33
+ Export a Socket SBOM as a CycloneDX SBOM
34
+ :param org_slug: String - The slug of the organization
35
+ :param id: String - The id of either a full scan or an sbom report
36
+ :param query_params: Optional[ExportQueryParams] - Query parameters for filtering
37
+ :param use_types: Optional[bool] - Whether to return typed responses
38
+ :return: dict
39
+ """
40
+ path = f"orgs/{org_slug}/export/cdx/{id}"
41
+ if query_params:
42
+ path += query_params.to_query_params()
43
+ response = self.api.do_request(path=path)
44
+
45
+ if response.status_code == 200:
46
+ return response.json()
47
+ # TODO: Add typed response when types are defined
48
+
49
+ log.error(f"Error exporting CDX BOM: {response.status_code}")
50
+ log.error(response.text)
51
+ return {}
52
+
53
+ def spdx_bom(
54
+ self, org_slug: str, id: str, query_params: Optional[ExportQueryParams] = None, use_types: bool = False
55
+ ) -> dict:
56
+ """
57
+ Export a Socket SBOM as an SPDX SBOM
58
+ :param org_slug: String - The slug of the organization
59
+ :param id: String - The id of either a full scan or an sbom report
60
+ :param query_params: Optional[ExportQueryParams] - Query parameters for filtering
61
+ :param use_types: Optional[bool] - Whether to return typed responses
62
+ :return: dict
63
+ """
64
+ path = f"orgs/{org_slug}/export/spdx/{id}"
65
+ if query_params:
66
+ path += query_params.to_query_params()
67
+ response = self.api.do_request(path=path)
68
+
69
+ if response.status_code == 200:
70
+ return response.json()
71
+ # TODO: Add typed response when types are defined
72
+
73
+ log.error(f"Error exporting SPDX BOM: {response.status_code}")
74
+ log.error(response.text)
75
+ return {}