socketdev 3.2.1__py3-none-any.whl → 3.4.2__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/core/api.py +9 -9
- socketdev/core/dedupe.py +12 -9
- socketdev/diffscans/__init__.py +38 -4
- socketdev/exceptions.py +108 -47
- socketdev/fullscans/__init__.py +64 -5
- socketdev/purl/__init__.py +124 -3
- socketdev/version.py +1 -1
- {socketdev-3.2.1.dist-info → socketdev-3.4.2.dist-info}/METADATA +1 -1
- {socketdev-3.2.1.dist-info → socketdev-3.4.2.dist-info}/RECORD +11 -11
- {socketdev-3.2.1.dist-info → socketdev-3.4.2.dist-info}/WHEEL +1 -1
- {socketdev-3.2.1.dist-info → socketdev-3.4.2.dist-info}/licenses/LICENSE +0 -0
socketdev/core/api.py
CHANGED
|
@@ -76,26 +76,26 @@ class API:
|
|
|
76
76
|
path_str = f"\nPath: {url}"
|
|
77
77
|
|
|
78
78
|
if response.status_code == 401:
|
|
79
|
-
raise APIAccessDenied(f"Unauthorized{path_str}{headers_str}")
|
|
79
|
+
raise APIAccessDenied(f"Unauthorized{path_str}{headers_str}", status_code=401)
|
|
80
80
|
if response.status_code == 403:
|
|
81
81
|
try:
|
|
82
82
|
error_message = response.json().get("error", {}).get("message", "")
|
|
83
83
|
if "Insufficient permissions for API method" in error_message:
|
|
84
84
|
log.error(f"{error_message}{path_str}{headers_str}")
|
|
85
|
-
raise APIInsufficientPermissions()
|
|
85
|
+
raise APIInsufficientPermissions(status_code=403)
|
|
86
86
|
elif "Organization not allowed" in error_message:
|
|
87
87
|
log.error(f"{error_message}{path_str}{headers_str}")
|
|
88
|
-
raise APIOrganizationNotAllowed()
|
|
88
|
+
raise APIOrganizationNotAllowed(status_code=403)
|
|
89
89
|
elif "Insufficient max quota" in error_message:
|
|
90
90
|
log.error(f"{error_message}{path_str}{headers_str}")
|
|
91
|
-
raise APIInsufficientQuota()
|
|
91
|
+
raise APIInsufficientQuota(status_code=403)
|
|
92
92
|
else:
|
|
93
|
-
raise APIAccessDenied(f"{error_message or 'Access denied'}{path_str}{headers_str}")
|
|
93
|
+
raise APIAccessDenied(f"{error_message or 'Access denied'}{path_str}{headers_str}", status_code=403)
|
|
94
94
|
except ValueError:
|
|
95
|
-
raise APIAccessDenied(f"Access denied{path_str}{headers_str}")
|
|
95
|
+
raise APIAccessDenied(f"Access denied{path_str}{headers_str}", status_code=403)
|
|
96
96
|
if response.status_code == 404:
|
|
97
97
|
log.error(f"Path not found {path}{path_str}{headers_str}")
|
|
98
|
-
raise APIResourceNotFound()
|
|
98
|
+
raise APIResourceNotFound(status_code=404)
|
|
99
99
|
if response.status_code == 429:
|
|
100
100
|
retry_after = response.headers.get("retry-after")
|
|
101
101
|
if retry_after:
|
|
@@ -109,7 +109,7 @@ class API:
|
|
|
109
109
|
else:
|
|
110
110
|
time_msg = ""
|
|
111
111
|
log.error(f"Insufficient quota for API route.{time_msg}{path_str}{headers_str}")
|
|
112
|
-
raise APIInsufficientQuota()
|
|
112
|
+
raise APIInsufficientQuota(status_code=429)
|
|
113
113
|
if response.status_code == 502:
|
|
114
114
|
log.error(f"Upstream server error{path_str}{headers_str}")
|
|
115
115
|
raise APIBadGateway()
|
|
@@ -124,7 +124,7 @@ class API:
|
|
|
124
124
|
f"Error message: {error_message}"
|
|
125
125
|
)
|
|
126
126
|
log.error(error)
|
|
127
|
-
raise APIFailure(error)
|
|
127
|
+
raise APIFailure(error, status_code=response.status_code)
|
|
128
128
|
|
|
129
129
|
return response
|
|
130
130
|
except Timeout:
|
socketdev/core/dedupe.py
CHANGED
|
@@ -11,8 +11,8 @@ class Dedupe:
|
|
|
11
11
|
@staticmethod
|
|
12
12
|
def alert_key(alert: dict) -> tuple:
|
|
13
13
|
return (
|
|
14
|
-
alert
|
|
15
|
-
alert
|
|
14
|
+
alert.get("type"),
|
|
15
|
+
alert.get("severity"),
|
|
16
16
|
alert.get("category"),
|
|
17
17
|
Dedupe.normalize_file_path(alert.get("file")),
|
|
18
18
|
alert.get("start"),
|
|
@@ -23,8 +23,8 @@ class Dedupe:
|
|
|
23
23
|
def consolidate_and_merge_alerts(package_group: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
24
24
|
def alert_identity(alert: dict) -> tuple:
|
|
25
25
|
return (
|
|
26
|
-
alert
|
|
27
|
-
alert
|
|
26
|
+
alert.get("type"),
|
|
27
|
+
alert.get("severity"),
|
|
28
28
|
alert.get("category"),
|
|
29
29
|
Dedupe.normalize_file_path(alert.get("file")),
|
|
30
30
|
alert.get("start"),
|
|
@@ -41,14 +41,17 @@ class Dedupe:
|
|
|
41
41
|
identity = alert_identity(alert)
|
|
42
42
|
|
|
43
43
|
if identity not in alert_map:
|
|
44
|
-
# Build alert dict with only fields that exist in the original alert
|
|
44
|
+
# Build alert dict with only fields that exist in the original alert.
|
|
45
|
+
# Use .get() for key/type/severity/action so synthetic status rows
|
|
46
|
+
# (e.g. pendingScan/notFound), which are built server-side from a
|
|
47
|
+
# minimal {type, key} base, don't raise KeyError here.
|
|
45
48
|
consolidated_alert = {
|
|
46
|
-
"key": alert
|
|
47
|
-
"type": alert
|
|
48
|
-
"severity": alert
|
|
49
|
+
"key": alert.get("key"), # keep the first key seen
|
|
50
|
+
"type": alert.get("type"),
|
|
51
|
+
"severity": alert.get("severity"),
|
|
49
52
|
"releases": [release],
|
|
50
53
|
"props": alert.get("props", []),
|
|
51
|
-
"action": alert
|
|
54
|
+
"action": alert.get("action")
|
|
52
55
|
}
|
|
53
56
|
|
|
54
57
|
# Only include optional fields if they exist in the original alert
|
socketdev/diffscans/__init__.py
CHANGED
|
@@ -21,12 +21,45 @@ class DiffScans:
|
|
|
21
21
|
log.error(f"Error listing diff scans: {response.status_code}, message: {response.text}")
|
|
22
22
|
return {}
|
|
23
23
|
|
|
24
|
-
def get(self, org_slug: str, diff_scan_id: str) -> dict:
|
|
25
|
-
"""Fetch a diff scan by ID.
|
|
24
|
+
def get(self, org_slug: str, diff_scan_id: str, params: Optional[Dict[str, Any]] = None) -> dict:
|
|
25
|
+
"""Fetch a diff scan by ID.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
org_slug: Organization slug
|
|
29
|
+
diff_scan_id: The ID of the diff scan to fetch
|
|
30
|
+
params: Optional query parameters. Supports:
|
|
31
|
+
cached: When "true", return pre-computed results immediately
|
|
32
|
+
(200) or a processing status (202) instead of holding
|
|
33
|
+
the connection open while the diff is computed.
|
|
34
|
+
omit_unchanged: When "true", omit unchanged artifacts.
|
|
35
|
+
omit_license_details: When "true", omit license details.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
dict: On 200, the API response containing the diff_scan object.
|
|
39
|
+
On 202 (results still processing when cached=true), a dict of
|
|
40
|
+
{"status": "processing", "id": diff_scan_id} so callers can
|
|
41
|
+
poll until the diff scan is ready. Empty dict on error.
|
|
42
|
+
"""
|
|
43
|
+
import urllib.parse
|
|
26
44
|
path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}"
|
|
45
|
+
if params:
|
|
46
|
+
path += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
27
47
|
response = self.api.do_request(path=path, method="GET")
|
|
28
48
|
if response.status_code == 200:
|
|
29
49
|
return response.json()
|
|
50
|
+
if response.status_code == 202:
|
|
51
|
+
result = {}
|
|
52
|
+
try:
|
|
53
|
+
body = response.json()
|
|
54
|
+
if isinstance(body, dict):
|
|
55
|
+
result.update(body)
|
|
56
|
+
except ValueError:
|
|
57
|
+
pass
|
|
58
|
+
# HTTP 202 always means the requested diff is still processing.
|
|
59
|
+
# Keep any additional response fields, but make the polling
|
|
60
|
+
# sentinel and requested resource ID authoritative for callers.
|
|
61
|
+
result.update({"status": "processing", "id": diff_scan_id})
|
|
62
|
+
return result
|
|
30
63
|
log.error(f"Error fetching diff scan: {response.status_code}, message: {response.text}")
|
|
31
64
|
return {}
|
|
32
65
|
|
|
@@ -61,7 +94,8 @@ class DiffScans:
|
|
|
61
94
|
import urllib.parse
|
|
62
95
|
path = f"orgs/{org_slug}/diff-scans/from-repo/{repo_slug}"
|
|
63
96
|
if params:
|
|
64
|
-
|
|
97
|
+
# doseq=True so list values (e.g. committers) become repeated params
|
|
98
|
+
path += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
65
99
|
|
|
66
100
|
# Use lazy loading if requested
|
|
67
101
|
if use_lazy_loading:
|
|
@@ -80,7 +114,7 @@ class DiffScans:
|
|
|
80
114
|
import urllib.parse
|
|
81
115
|
path = f"orgs/{org_slug}/diff-scans/from-ids"
|
|
82
116
|
if params:
|
|
83
|
-
path += "?" + urllib.parse.urlencode(params)
|
|
117
|
+
path += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
84
118
|
response = self.api.do_request(path=path, method="POST")
|
|
85
119
|
if response.status_code in (200, 201):
|
|
86
120
|
return response.json()
|
socketdev/exceptions.py
CHANGED
|
@@ -1,47 +1,108 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
class
|
|
36
|
-
"""Raised when
|
|
37
|
-
pass
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
class
|
|
41
|
-
"""Raised when
|
|
42
|
-
pass
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class
|
|
46
|
-
"""Raised when
|
|
47
|
-
pass
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
# HTTP statuses classified as transient by APIFailure.is_transient_error(): gateway /
|
|
4
|
+
# availability failures where the request was dropped before the application produced a
|
|
5
|
+
# definitive response, so retrying the same request may succeed (408 Request Timeout,
|
|
6
|
+
# 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout).
|
|
7
|
+
TRANSIENT_HTTP_STATUS_CODES = frozenset({408, 502, 503, 504})
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class APIFailure(Exception):
|
|
11
|
+
"""Base exception for all Socket API errors"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, *args, status_code: Optional[int] = None):
|
|
14
|
+
super().__init__(*args)
|
|
15
|
+
self.status_code = status_code
|
|
16
|
+
|
|
17
|
+
def is_transient_error(self) -> bool:
|
|
18
|
+
"""Whether this failure is transient, i.e. retrying the same request may succeed.
|
|
19
|
+
|
|
20
|
+
Transient failures happen at the gateway/connection level - HTTP 408/502/503/504,
|
|
21
|
+
dropped or reset connections, and client-side timeouts - before the server produced
|
|
22
|
+
a definitive response. Deterministic errors (e.g. 400/401/403/404/429) are not
|
|
23
|
+
transient: retrying the same request fails the same way. Classification is based on
|
|
24
|
+
the HTTP status code recorded when the exception was raised (or overridden by
|
|
25
|
+
subclasses without an HTTP status, like timeouts), so it stays correct even if a
|
|
26
|
+
status code gains a dedicated exception subclass later.
|
|
27
|
+
"""
|
|
28
|
+
return self.status_code in TRANSIENT_HTTP_STATUS_CODES
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class APIKeyMissing(APIFailure):
|
|
32
|
+
"""Raised when the api key is not passed and the headers are empty"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class APIAccessDenied(APIFailure):
|
|
36
|
+
"""Raised when access is denied to the API"""
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class APIInsufficientPermissions(APIFailure):
|
|
41
|
+
"""Raised when the API token doesn't have required permissions"""
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class APIOrganizationNotAllowed(APIFailure):
|
|
46
|
+
"""Raised when organization doesn't have access to the feature"""
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class APIInsufficientQuota(APIFailure):
|
|
51
|
+
"""Raised when access is denied to the API due to quota limits"""
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class APIResourceNotFound(APIFailure):
|
|
56
|
+
"""Raised when the requested resource is not found"""
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class APITimeout(APIFailure):
|
|
61
|
+
"""Raised when a request times out"""
|
|
62
|
+
|
|
63
|
+
def is_transient_error(self) -> bool:
|
|
64
|
+
# No HTTP status: the request timed out client-side, so a retry may succeed.
|
|
65
|
+
return True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class APIConnectionError(APIFailure):
|
|
69
|
+
"""Raised when there's a connection error"""
|
|
70
|
+
|
|
71
|
+
def is_transient_error(self) -> bool:
|
|
72
|
+
# No HTTP status: the connection was dropped/reset mid-request, so a retry may succeed.
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class APIBadGateway(APIFailure):
|
|
77
|
+
"""Raised when the upstream server returns a 502 Bad Gateway error"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, *args):
|
|
80
|
+
super().__init__(*args, status_code=502)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class APIPartialResponse(APIFailure):
|
|
84
|
+
"""Raised by ``purl.post(strict=True)`` when the batch response omits requested inputs.
|
|
85
|
+
|
|
86
|
+
The batch purl API is fail-open: input purls whose resolution/analysis has not
|
|
87
|
+
completed are silently dropped from the response unless the caller opts in via
|
|
88
|
+
``alerts=True`` (synthetic ``pendingScan``/``notFound`` rows) or ``poll=True`` (a
|
|
89
|
+
bounded fail-closed wait). ``strict=True`` turns that silent omission into this
|
|
90
|
+
explicit error so callers get a first-class "partial batch" signal without having
|
|
91
|
+
to diff the response themselves.
|
|
92
|
+
|
|
93
|
+
The ``missing`` attribute holds the requested purls that were absent from the
|
|
94
|
+
response (the HTTP call itself succeeded, so there is no status code). A missing
|
|
95
|
+
row may reflect pending analysis, a malformed or unknown purl, or a response contract
|
|
96
|
+
failure, so blindly retrying is not guaranteed to succeed. Callers that need a bounded
|
|
97
|
+
wait should use ``poll=True``; callers that need omission reasons should request
|
|
98
|
+
``alerts=True`` and/or ``purl_errors=True``.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, *args, missing=None):
|
|
102
|
+
super().__init__(*args)
|
|
103
|
+
self.missing = list(missing or [])
|
|
104
|
+
|
|
105
|
+
def is_transient_error(self) -> bool:
|
|
106
|
+
# The HTTP request completed successfully, and the omission reason may be
|
|
107
|
+
# permanent. Server-side polling is the explicit bounded retry mechanism.
|
|
108
|
+
return False
|
socketdev/fullscans/__init__.py
CHANGED
|
@@ -12,9 +12,46 @@ log = logging.getLogger("socketdev")
|
|
|
12
12
|
|
|
13
13
|
class SocketPURL_Type(str, Enum):
|
|
14
14
|
UNKNOWN = "unknown"
|
|
15
|
+
APK = "apk"
|
|
16
|
+
BITBUCKET = "bitbucket"
|
|
17
|
+
CARGO = "cargo"
|
|
18
|
+
COCOAPODS = "cocoapods"
|
|
19
|
+
COMPOSER = "composer"
|
|
20
|
+
CONAN = "conan"
|
|
21
|
+
CONDA = "conda"
|
|
22
|
+
CRAN = "cran"
|
|
23
|
+
DEB = "deb"
|
|
24
|
+
DOCKER = "docker"
|
|
25
|
+
GEM = "gem"
|
|
26
|
+
GENERIC = "generic"
|
|
27
|
+
GITHUB = "github"
|
|
28
|
+
GOLANG = "golang"
|
|
29
|
+
HACKAGE = "hackage"
|
|
30
|
+
HEX = "hex"
|
|
31
|
+
HUGGINGFACE = "huggingface"
|
|
32
|
+
LUAROCKS = "luarocks"
|
|
33
|
+
MAVEN = "maven"
|
|
34
|
+
MLFLOW = "mlflow"
|
|
15
35
|
NPM = "npm"
|
|
36
|
+
NUGET = "nuget"
|
|
37
|
+
OCI = "oci"
|
|
38
|
+
PUB = "pub"
|
|
16
39
|
PYPI = "pypi"
|
|
17
|
-
|
|
40
|
+
RPM = "rpm"
|
|
41
|
+
SWIFT = "swift"
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def _missing_(cls, value):
|
|
45
|
+
# The API can emit purl types this SDK does not know about yet. Fall
|
|
46
|
+
# back to UNKNOWN instead of raising so one artifact cannot fail an
|
|
47
|
+
# entire response parse (same forward-compat approach as
|
|
48
|
+
# SocketCategory, https://github.com/SocketDev/socket-sdk-python/issues/78).
|
|
49
|
+
log.warning(
|
|
50
|
+
"Unknown SocketPURL_Type %r; falling back to UNKNOWN. "
|
|
51
|
+
"Upgrade socketdev to pick up newer purl types.",
|
|
52
|
+
value,
|
|
53
|
+
)
|
|
54
|
+
return cls.UNKNOWN
|
|
18
55
|
|
|
19
56
|
|
|
20
57
|
class SocketIssueSeverity(str, Enum):
|
|
@@ -726,13 +763,24 @@ class FullScanStreamResponse:
|
|
|
726
763
|
|
|
727
764
|
@classmethod
|
|
728
765
|
def from_dict(cls, data: dict) -> "FullScanStreamResponse":
|
|
766
|
+
artifacts = None
|
|
767
|
+
if data.get("artifacts"):
|
|
768
|
+
artifacts = {}
|
|
769
|
+
for artifact_id, raw in data["artifacts"].items():
|
|
770
|
+
try:
|
|
771
|
+
artifacts[artifact_id] = SocketArtifact.from_dict(raw)
|
|
772
|
+
except Exception:
|
|
773
|
+
# One malformed artifact should not fail the whole stream.
|
|
774
|
+
log.warning(
|
|
775
|
+
"Skipping artifact %s that could not be parsed",
|
|
776
|
+
artifact_id,
|
|
777
|
+
exc_info=True,
|
|
778
|
+
)
|
|
729
779
|
return cls(
|
|
730
780
|
success=data["success"],
|
|
731
781
|
status=data["status"],
|
|
732
782
|
message=data.get("message"),
|
|
733
|
-
artifacts=
|
|
734
|
-
if data.get("artifacts")
|
|
735
|
-
else None,
|
|
783
|
+
artifacts=artifacts,
|
|
736
784
|
)
|
|
737
785
|
|
|
738
786
|
|
|
@@ -907,7 +955,18 @@ class FullScans:
|
|
|
907
955
|
stream_str.append(item)
|
|
908
956
|
stream_deduped = Dedupe.dedupe(stream_str, batched=False)
|
|
909
957
|
for batch in stream_deduped:
|
|
910
|
-
|
|
958
|
+
try:
|
|
959
|
+
artifact_id = batch["id"]
|
|
960
|
+
if not isinstance(artifact_id, str) or not artifact_id:
|
|
961
|
+
raise TypeError("artifact id must be a non-empty string")
|
|
962
|
+
artifacts[artifact_id] = batch
|
|
963
|
+
except (KeyError, TypeError):
|
|
964
|
+
# A malformed artifact should not discard valid stream results
|
|
965
|
+
# before FullScanStreamResponse can parse them individually.
|
|
966
|
+
log.warning(
|
|
967
|
+
"Skipping artifact without a usable id",
|
|
968
|
+
exc_info=True,
|
|
969
|
+
)
|
|
911
970
|
if use_types:
|
|
912
971
|
return FullScanStreamResponse.from_dict({"success": True, "status": 200, "artifacts": artifacts})
|
|
913
972
|
return artifacts
|
socketdev/purl/__init__.py
CHANGED
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import urllib.parse
|
|
3
3
|
import warnings
|
|
4
|
+
from typing import Optional
|
|
4
5
|
from socketdev.log import log
|
|
6
|
+
from socketdev.exceptions import APIPartialResponse
|
|
5
7
|
from ..core.dedupe import Dedupe
|
|
6
8
|
|
|
7
9
|
|
|
10
|
+
def _encode_bool_query_value(value) -> str:
|
|
11
|
+
"""Encode typed bools while preserving legacy string query values."""
|
|
12
|
+
if isinstance(value, bool):
|
|
13
|
+
return "true" if value else "false"
|
|
14
|
+
return str(value)
|
|
15
|
+
|
|
16
|
+
|
|
8
17
|
class Purl:
|
|
9
18
|
def __init__(self, api):
|
|
10
19
|
self.api = api
|
|
@@ -14,8 +23,60 @@ class Purl:
|
|
|
14
23
|
license: str = "false",
|
|
15
24
|
components: list = None,
|
|
16
25
|
org_slug: str = None,
|
|
26
|
+
poll: Optional[bool] = None,
|
|
27
|
+
timeout_sec: Optional[int] = None,
|
|
28
|
+
alerts: Optional[bool] = None,
|
|
29
|
+
purl_errors: Optional[bool] = None,
|
|
30
|
+
strict: bool = False,
|
|
17
31
|
**kwargs,
|
|
18
32
|
) -> list:
|
|
33
|
+
"""POST a batch of purls to the Socket batch purl endpoint and return deduped rows.
|
|
34
|
+
|
|
35
|
+
The batch purl API (``POST /v0/purl`` and ``POST /v0/orgs/{slug}/purl``) defaults
|
|
36
|
+
to **fail-open**: any input purl whose resolution/analysis has not finished is
|
|
37
|
+
**silently omitted** from the response. A naive caller therefore cannot tell
|
|
38
|
+
"this version is clean" apart from "this version was dropped from the response".
|
|
39
|
+
The parameters below opt into the server behaviors that make omissions visible.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
license: ``"true"``/``"false"`` — request license information (stringly-typed
|
|
43
|
+
to match the query param the API expects).
|
|
44
|
+
components: list of component dicts to score, e.g. ``[{"purl": "pkg:npm/lodash@4.18.1"}]``.
|
|
45
|
+
org_slug: organization slug. When provided, routes to the org-scoped endpoint
|
|
46
|
+
``POST /v0/orgs/{org_slug}/purl``; otherwise the deprecated ``POST /v0/purl``.
|
|
47
|
+
poll: opt into a fail-closed bounded wait for pending analysis (``poll=True`` →
|
|
48
|
+
``poll=true`` query param). ``None`` omits the param (server default).
|
|
49
|
+
timeout_sec: bound in seconds for the ``poll`` wait (``→ timeoutSec``). The
|
|
50
|
+
server may cap this via a feature flag. ``None`` omits the param.
|
|
51
|
+
alerts: when ``True`` (``→ alerts=true``), the server emits synthetic
|
|
52
|
+
``pendingScan``/``notFound`` status rows instead of silently omitting
|
|
53
|
+
unresolved inputs, so callers can distinguish "no data yet" from "clean".
|
|
54
|
+
purl_errors: when ``True`` (``→ purlErrors``), the server includes per-purl
|
|
55
|
+
error rows for malformed/unresolvable inputs. ``None`` omits the param.
|
|
56
|
+
For backward compatibility, legacy string values passed to the promoted
|
|
57
|
+
Boolean parameters are forwarded unchanged.
|
|
58
|
+
strict: client-side guard. When ``True``, compares the exact ``purl`` string
|
|
59
|
+
of each requested component against the returned ``inputPurl`` (or the
|
|
60
|
+
``purl`` fallback). The API defines ``inputPurl`` as the original,
|
|
61
|
+
unmodified input before server normalization, so canonicalized ``purl``
|
|
62
|
+
values do not cause false omissions. Raises
|
|
63
|
+
:class:`~socketdev.exceptions.APIPartialResponse` (with a ``missing``
|
|
64
|
+
list) if any requested purl is absent from the response. This surfaces
|
|
65
|
+
partial batches even without ``alerts=True``. Only components that carry
|
|
66
|
+
a ``purl`` string are checked.
|
|
67
|
+
**kwargs: forwarded verbatim into the query string (back-compat passthrough for
|
|
68
|
+
any params not yet promoted to first-class arguments).
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
A deduped list of result rows. When ``alerts=True``, unresolved inputs appear
|
|
72
|
+
as synthetic rows carrying ``pendingScan``/``notFound`` alerts rather than being
|
|
73
|
+
omitted. On a non-200 response, logs the error and returns ``[]`` (callers that
|
|
74
|
+
need to fail closed should treat ``[]`` as an error).
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
APIPartialResponse: if ``strict=True`` and one or more requested component purls
|
|
78
|
+
are missing from the response.
|
|
79
|
+
"""
|
|
19
80
|
if org_slug is None:
|
|
20
81
|
warnings.warn(
|
|
21
82
|
"Calling purl.post() without org_slug uses the deprecated POST /v0/purl endpoint. "
|
|
@@ -31,25 +92,85 @@ class Purl:
|
|
|
31
92
|
query_args = {
|
|
32
93
|
"license": license,
|
|
33
94
|
}
|
|
95
|
+
# Promote the typed params into query args only when explicitly set, so existing
|
|
96
|
+
# callers keep the server's fail-open default (None => omit the param entirely).
|
|
97
|
+
if poll is not None:
|
|
98
|
+
query_args["poll"] = _encode_bool_query_value(poll)
|
|
99
|
+
if timeout_sec is not None:
|
|
100
|
+
query_args["timeoutSec"] = str(timeout_sec)
|
|
101
|
+
if alerts is not None:
|
|
102
|
+
query_args["alerts"] = _encode_bool_query_value(alerts)
|
|
103
|
+
if purl_errors is not None:
|
|
104
|
+
query_args["purlErrors"] = _encode_bool_query_value(purl_errors)
|
|
34
105
|
if kwargs:
|
|
35
106
|
query_args.update(kwargs)
|
|
36
107
|
params = urllib.parse.urlencode(query_args)
|
|
37
108
|
path += params
|
|
38
109
|
response = self.api.do_request(path=path, payload=purls, method="POST")
|
|
39
110
|
if response.status_code == 200:
|
|
40
|
-
|
|
111
|
+
artifact_rows = []
|
|
112
|
+
stream_records = []
|
|
41
113
|
result = response.text
|
|
42
114
|
result = result.strip('"').strip()
|
|
43
115
|
for line in result.split("\n"):
|
|
44
116
|
if line and line != '"':
|
|
45
117
|
try:
|
|
46
118
|
item = json.loads(line)
|
|
47
|
-
|
|
119
|
+
if isinstance(item, dict) and item.get("_type") in {
|
|
120
|
+
"purlError",
|
|
121
|
+
"summary",
|
|
122
|
+
}:
|
|
123
|
+
stream_records.append(item)
|
|
124
|
+
else:
|
|
125
|
+
artifact_rows.append(item)
|
|
48
126
|
except json.JSONDecodeError:
|
|
49
127
|
continue
|
|
50
|
-
purl_deduped = Dedupe.dedupe(
|
|
128
|
+
purl_deduped = Dedupe.dedupe(artifact_rows, batched=True)
|
|
129
|
+
purl_deduped.extend(stream_records)
|
|
130
|
+
if strict:
|
|
131
|
+
self._raise_on_missing(components, purl_deduped)
|
|
51
132
|
return purl_deduped
|
|
52
133
|
|
|
53
134
|
log.error(f"Error posting {components} to the Purl API: {response.status_code}")
|
|
54
135
|
log.error(response.text)
|
|
55
136
|
return []
|
|
137
|
+
|
|
138
|
+
@staticmethod
|
|
139
|
+
def _raise_on_missing(components: list, results: list) -> None:
|
|
140
|
+
"""Raise APIPartialResponse if any requested component purl is absent from results.
|
|
141
|
+
|
|
142
|
+
Only components exposing a ``purl`` string are checked. The batch API contract
|
|
143
|
+
defines ``inputPurl`` as the original, unmodified input string before server-side
|
|
144
|
+
normalization, so matching it exactly preserves the caller's identity even when
|
|
145
|
+
the response's canonical ``purl`` differs. ``purl`` is retained as a fallback,
|
|
146
|
+
and typed ``purlError`` stream records carry ``inputPurl`` under ``value``.
|
|
147
|
+
"""
|
|
148
|
+
requested = [
|
|
149
|
+
c["purl"]
|
|
150
|
+
for c in components
|
|
151
|
+
if isinstance(c, dict) and isinstance(c.get("purl"), str)
|
|
152
|
+
]
|
|
153
|
+
if not requested:
|
|
154
|
+
return
|
|
155
|
+
returned = set()
|
|
156
|
+
for row in results:
|
|
157
|
+
if not isinstance(row, dict):
|
|
158
|
+
continue
|
|
159
|
+
for field in ("inputPurl", "purl"):
|
|
160
|
+
value = row.get(field)
|
|
161
|
+
if isinstance(value, str):
|
|
162
|
+
returned.add(value)
|
|
163
|
+
record_value = row.get("value")
|
|
164
|
+
if isinstance(record_value, dict):
|
|
165
|
+
input_purl = record_value.get("inputPurl")
|
|
166
|
+
if isinstance(input_purl, str):
|
|
167
|
+
returned.add(input_purl)
|
|
168
|
+
missing = [purl for purl in requested if purl not in returned]
|
|
169
|
+
if missing:
|
|
170
|
+
raise APIPartialResponse(
|
|
171
|
+
"purl.post(strict=True): the batch response omitted "
|
|
172
|
+
f"{len(missing)} of {len(requested)} requested purls "
|
|
173
|
+
"(fail-open: unresolved inputs are dropped unless alerts=True/poll=True): "
|
|
174
|
+
f"{missing}",
|
|
175
|
+
missing=missing,
|
|
176
|
+
)
|
socketdev/version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "3.2
|
|
1
|
+
__version__ = "3.4.2"
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
socketdev/__init__.py,sha256=mYuLIlXdU0uec1418LIw_oILBRh5DyWQDpWafaMa_AU,4484
|
|
2
|
-
socketdev/exceptions.py,sha256=
|
|
2
|
+
socketdev/exceptions.py,sha256=yr1O1wkJUi-pvXQuqdAj4phNggHmT2N57I6DOdGdsgI,4225
|
|
3
3
|
socketdev/log.py,sha256=AgEcsPN3y9U-fze8pTFvLigVvNob2vmNC-TkOOQkkeQ,90
|
|
4
|
-
socketdev/version.py,sha256=
|
|
4
|
+
socketdev/version.py,sha256=meC-FUH9gTBuueIN71wPqtTSeXVbhd3ODNhsvvwhHmM,22
|
|
5
5
|
socketdev/alertfullscansearch/__init__.py,sha256=YwXrgnrI9z9rAexXFFmoXQcaQdGW47HRhQ58CQBCG3U,884
|
|
6
6
|
socketdev/alerts/__init__.py,sha256=kGLCNXtXTRz3vl2s_bPQ7xuds_QGwNQnah1TfHzp2MU,846
|
|
7
7
|
socketdev/alerttypes/__init__.py,sha256=W-m2D9VxbepSAUELJPmWmX40zksGZbQcSzwQ1kjlB1k,1169
|
|
@@ -9,22 +9,22 @@ socketdev/analytics/__init__.py,sha256=kQGeO67TraqvfmYjfpYCvcNRtxW2a6x5EefEl6Jnc
|
|
|
9
9
|
socketdev/apitokens/__init__.py,sha256=Z6W9Jkh4gdDeJBivfcONZuz7jRKZtxWLTi1n9gkbYVE,4222
|
|
10
10
|
socketdev/auditlog/__init__.py,sha256=vjcVtOK6oujqC6-RW5Hrvmth5BqFkLdinbeyqtycOpA,881
|
|
11
11
|
socketdev/basics/__init__.py,sha256=9jTEwC4dMUV-9pKpU4twK-hM1cY0xeXAxjDrb37sxoQ,4067
|
|
12
|
-
socketdev/core/api.py,sha256=
|
|
12
|
+
socketdev/core/api.py,sha256=cpHgS6d7rKfUSccoXsr_uKkbB60uSiPLs2pMYDN-9FU,6350
|
|
13
13
|
socketdev/core/classes.py,sha256=fyDlolgnkpHFb1dMHa2SA0czCS1I6Tr3SuYb1a67-dY,3756
|
|
14
|
-
socketdev/core/dedupe.py,sha256=
|
|
14
|
+
socketdev/core/dedupe.py,sha256=Fy_HGU77jxt7Dz8TF7AYkEklwtu_xFA40ripaYyBkqs,5774
|
|
15
15
|
socketdev/core/issues.py,sha256=SKhJz7SrglozeuEk72CbbuCM7X0hgzNMk55uM4wX-TI,68081
|
|
16
16
|
socketdev/dependencies/__init__.py,sha256=zdAb0lMYF8tTHFWa9kGwz5dv4_Sp1UpzQseg_4_qBfY,2170
|
|
17
|
-
socketdev/diffscans/__init__.py,sha256=
|
|
17
|
+
socketdev/diffscans/__init__.py,sha256=NCvjirhFGWD93miL87UObQ7SeInBEkNt5R28uLIKYi0,7004
|
|
18
18
|
socketdev/export/__init__.py,sha256=5DqVqHnaK5Aq-ueSTIAplOZJpF21W_pXysIzmMNLGPg,3667
|
|
19
19
|
socketdev/fixes/__init__.py,sha256=ouRSQ5FcqQcjAmrU8aAgd0ZJeo431wBOEVKLR36etik,856
|
|
20
|
-
socketdev/fullscans/__init__.py,sha256=
|
|
20
|
+
socketdev/fullscans/__init__.py,sha256=MhBBVnmT5noDaos9jr0GOo9aEOCpiDaPf8aWn7v-s6I,39921
|
|
21
21
|
socketdev/historical/__init__.py,sha256=DXFmRrHLWHKbZrB8eermM4YG6j4C1S4Lz6-V63_p2gs,3472
|
|
22
22
|
socketdev/labels/__init__.py,sha256=Ep19ZraKqi_a-3-eAOWGhPNQsgwGRY9N28Oyxlxrz-g,5128
|
|
23
23
|
socketdev/licensemetadata/__init__.py,sha256=pDcvpkc08QtMqhsnKP1Cfjvs3m-MRPYUK-uLh8aRkrU,815
|
|
24
24
|
socketdev/npm/__init__.py,sha256=FvU8z6dY3EsBNLBsKwQKT5soNb6ous1o63aphmbBHh4,906
|
|
25
25
|
socketdev/openapi/__init__.py,sha256=7Avxgz8RYqC5TCSQCKvmnvzsa2lgV_1y--8eMsy9xYc,500
|
|
26
26
|
socketdev/org/__init__.py,sha256=2e9fe9jF8V_zb2V-qtmkQZUzJv6qbfpbb1p4Hdgsx9A,903
|
|
27
|
-
socketdev/purl/__init__.py,sha256=
|
|
27
|
+
socketdev/purl/__init__.py,sha256=eJ3s4fpwykiMiNWaKDebo5BZAELVHZkSy6FbJcq9hrE,8455
|
|
28
28
|
socketdev/quota/__init__.py,sha256=IblVMP3M7HwXtHs2wnr72GlcNIQtykOKsZKLSehEC8c,487
|
|
29
29
|
socketdev/report/__init__.py,sha256=L1EuvUnatxWAwQdLiTQwdRNIVglWYoyWqSISuZB0RTE,3454
|
|
30
30
|
socketdev/repos/__init__.py,sha256=2_BVRYYpA-wF1W9KvhbaBrfe3g2VHLkWLMizWOiyX3A,5641
|
|
@@ -39,7 +39,7 @@ socketdev/triage/__init__.py,sha256=-h599vThVetfRSOAs1e4IUoMjcXS8xOsUfub41XPiX4,
|
|
|
39
39
|
socketdev/uploadmanifests/__init__.py,sha256=-sFHbOW-aw7U0wRfEJT_Edrzx8aCbzD9cTGmVTNJKpw,6043
|
|
40
40
|
socketdev/utils/__init__.py,sha256=E11UJTsWsN-ZurOwtKvPGOTc9UMP3ND79nPbmNRRQ6E,17666
|
|
41
41
|
socketdev/webhooks/__init__.py,sha256=fme6K7ma_Gvk_TFOLz9jVcR5QJbDpMHXqRaU3x_RShY,3507
|
|
42
|
-
socketdev-3.2.
|
|
43
|
-
socketdev-3.2.
|
|
44
|
-
socketdev-3.2.
|
|
45
|
-
socketdev-3.2.
|
|
42
|
+
socketdev-3.4.2.dist-info/METADATA,sha256=RnLUxMbKxsOz18o-e_bJaFvLz3zcRJ-CLxbIC0nMduk,45557
|
|
43
|
+
socketdev-3.4.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
44
|
+
socketdev-3.4.2.dist-info/licenses/LICENSE,sha256=mC0II_UuE-_gCG9XqOLNyrV3crnROzMpdAetGnMrhpw,1068
|
|
45
|
+
socketdev-3.4.2.dist-info/RECORD,,
|
|
File without changes
|