Skip to content

Commit 2cd4b11

Browse files
committed
Merge main (3.6.4) and move this change to 3.6.5
# Conflicts: # CHANGELOG.md # socketdev/version.py
2 parents 6faf55b + 2a3fdf7 commit 2cd4b11

4 files changed

Lines changed: 271 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,25 @@ These calls failed with a 404 on every request, whatever the token.
1818
only method, `list()`, requested `GET repos`. Use `repos.get(org_slug)` to list
1919
repositories.
2020

21+
## 3.6.4
22+
23+
### Fixed: every advisory on a package is kept
24+
25+
- `fullscans.stream()` and `purl.post()` no longer merge different
26+
vulnerabilities of the same severity on a package into one alert. Alerts are
27+
now told apart by their advisory ID (`props.ghsaId`, falling back to
28+
`props.cveId`) as well as type, severity, category and file location. Before,
29+
a package with six Critical advisories came back with one `criticalCVE`
30+
alert.
31+
- When the same alert does appear more than once (in one artifact, or across
32+
the release files of a package in a `purl.post()` result), the merged alert
33+
carries the most severe `action` (`error`, then `warn`, `monitor`, `ignore`)
34+
instead of the first one seen. A blocking alert can no longer be hidden
35+
behind a triaged or ignored one. The merged alert keeps the `key` of the
36+
first sighting, so that `key` can come from a release whose own action was
37+
less severe. `fullscans.stream()` does not merge across releases: each
38+
release file is its own artifact there.
39+
2140
## 3.6.3
2241

2342
### Fixed: `settings.integration_events()` requested the wrong path

‎socketdev/core/dedupe.py‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,45 @@
22
from typing import Dict, List, Any
33
from socketdev.log import log
44

5+
# Props that name the advisory behind a vulnerability alert. Every advisory of
6+
# one severity on a package shares an alert type (``criticalCVE``, ``cve`` and
7+
# so on), so these are what tell two of them apart.
8+
#
9+
# Socket's CVE alerts carry ``ghsaId`` and ``cveId``. The other names are in no
10+
# current alert schema; they mirror ``Issue.advisory_id()`` in socket-python-cli
11+
# (socketsecurity/core/classes.py), which reads alerts from this SDK. Keep the
12+
# two lists in step.
13+
ADVISORY_ID_PROPS = ("ghsaId", "ghsa_id", "cveId", "cve_id", "cve")
14+
15+
# Policy actions from least to most severe. An unknown or missing action ranks
16+
# below "ignore", so it never replaces a known action and the merged result
17+
# doesn't depend on which release is listed first.
18+
ACTION_RANK = {"ignore": 0, "monitor": 1, "warn": 2, "error": 3}
19+
520

621
class Dedupe:
722
@staticmethod
823
def normalize_file_path(path: str) -> str:
924
return path.split("/", 1)[-1] if path and "/" in path else path or ""
1025

26+
@staticmethod
27+
def advisory_id(alert: dict) -> str:
28+
"""The alert's GHSA or CVE identifier, upper-cased, or "" if it has none."""
29+
props = alert.get("props")
30+
if not isinstance(props, dict):
31+
return ""
32+
for prop_name in ADVISORY_ID_PROPS:
33+
value = props.get(prop_name)
34+
if isinstance(value, (list, tuple)):
35+
value = next((v for v in value if isinstance(v, str) and v.strip()), "")
36+
if isinstance(value, str) and value.strip():
37+
return value.strip().upper()
38+
return ""
39+
40+
@staticmethod
41+
def action_rank(action: Any) -> int:
42+
return ACTION_RANK.get(action, -1) if isinstance(action, str) else -1
43+
1144
@staticmethod
1245
def alert_key(alert: dict) -> tuple:
1346
return (
@@ -16,29 +49,20 @@ def alert_key(alert: dict) -> tuple:
1649
alert.get("category"),
1750
Dedupe.normalize_file_path(alert.get("file")),
1851
alert.get("start"),
19-
alert.get("end")
52+
alert.get("end"),
53+
Dedupe.advisory_id(alert),
2054
)
2155

2256
@staticmethod
2357
def consolidate_and_merge_alerts(package_group: List[Dict[str, Any]]) -> Dict[str, Any]:
24-
def alert_identity(alert: dict) -> tuple:
25-
return (
26-
alert.get("type"),
27-
alert.get("severity"),
28-
alert.get("category"),
29-
Dedupe.normalize_file_path(alert.get("file")),
30-
alert.get("start"),
31-
alert.get("end")
32-
)
33-
3458
alert_map: Dict[tuple, dict] = {}
3559
releases = set()
3660
for pkg in package_group:
3761
release = pkg.get("release") if pkg.get("release") is not None else pkg.get("type")
3862
releases.add(release)
3963

4064
for alert in pkg.get("alerts", []):
41-
identity = alert_identity(alert)
65+
identity = Dedupe.alert_key(alert)
4266

4367
if identity not in alert_map:
4468
# Build alert dict with only fields that exist in the original alert.
@@ -66,8 +90,15 @@ def alert_identity(alert: dict) -> tuple:
6690

6791
alert_map[identity] = consolidated_alert
6892
else:
69-
if release not in alert_map[identity]["releases"]:
70-
alert_map[identity]["releases"].append(release)
93+
merged = alert_map[identity]
94+
if release not in merged["releases"]:
95+
merged["releases"].append(release)
96+
# Keep the most severe action seen, so a release that blocks
97+
# is never hidden behind one that doesn't. Only the action
98+
# moves: key and props stay with the first sighting, so the
99+
# key can belong to a release with a less severe action.
100+
if Dedupe.action_rank(alert.get("action")) > Dedupe.action_rank(merged.get("action")):
101+
merged["action"] = alert.get("action")
71102

72103
base = package_group[0]
73104
base["releases"] = sorted(releases)

‎tests/unit/test_dedupe.py‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,182 @@ def test_dedupe_batched_parameter_backward_compatibility(self):
187187
for pkg in result_batched_true + result_batched_false:
188188
self.assertNotIn("batchIndex", pkg)
189189

190+
@staticmethod
191+
def _cve(ghsa, action, cve="", severity="critical", alert_type="criticalCVE", key=None):
192+
return {
193+
"key": key or f"key-{ghsa}",
194+
"type": alert_type,
195+
"severity": severity,
196+
"category": "vulnerability",
197+
"action": action,
198+
"props": {"ghsaId": ghsa, "cveId": cve},
199+
}
200+
201+
def test_same_severity_advisories_on_one_package_stay_separate(self):
202+
"""Each advisory keeps its own alert even when type and severity match"""
203+
ghsa_ids = [
204+
"GHSA-8r5x-fm3f-whwj", "GHSA-p8wg-vrv2-v86f", "GHSA-2w6w-674q-4c4q",
205+
"GHSA-w457-6q6x-cgp9", "GHSA-765h-qjxv-5f44", "GHSA-f2jv-r9rf-7988",
206+
]
207+
packages = [{
208+
"id": "artifact-1", "type": "npm", "name": "handlebars", "version": "4.0.11",
209+
"alerts": [self._cve(ghsa, "error") for ghsa in ghsa_ids],
210+
}]
211+
212+
result = Dedupe.dedupe(packages, batched=False)
213+
214+
alerts = result[0]["alerts"]
215+
self.assertEqual(len(alerts), 6)
216+
self.assertEqual(sorted(a["props"]["ghsaId"] for a in alerts), sorted(ghsa_ids))
217+
self.assertTrue(all(a["action"] == "error" for a in alerts))
218+
219+
def test_blocking_advisory_is_kept_when_an_earlier_one_is_triaged(self):
220+
"""A monitored or ignored advisory listed first must not hide a later Block one"""
221+
for triaged_action in ("ignore", "monitor", "warn"):
222+
with self.subTest(triaged_action=triaged_action):
223+
packages = [{
224+
"id": "artifact-1", "type": "npm", "name": "example", "version": "1.0.0",
225+
"alerts": [
226+
self._cve("GHSA-aaaa-aaaa-aaaa", triaged_action),
227+
self._cve("GHSA-bbbb-bbbb-bbbb", "error"),
228+
],
229+
}]
230+
231+
alerts = Dedupe.dedupe(packages, batched=False)[0]["alerts"]
232+
233+
actions = {a["props"]["ghsaId"]: a["action"] for a in alerts}
234+
self.assertEqual(actions, {
235+
"GHSA-aaaa-aaaa-aaaa": triaged_action,
236+
"GHSA-bbbb-bbbb-bbbb": "error",
237+
})
238+
239+
def test_same_advisory_across_releases_merges_with_most_severe_action(self):
240+
"""One advisory seen in several releases is one alert carrying the strictest action"""
241+
orders = [
242+
["ignore", "monitor", "error", "warn"],
243+
["error", "ignore", "monitor", "warn"],
244+
["monitor", "warn", "ignore", "error"],
245+
]
246+
for actions in orders:
247+
with self.subTest(actions=actions):
248+
packages = [
249+
{
250+
"id": f"artifact-{i}", "type": "pypi", "name": "example", "version": "1.0",
251+
"release": release, "inputPurl": "pkg:pypi/example@1.0",
252+
"alerts": [self._cve("GHSA-cccc-cccc-cccc", action, cve="CVE-2020-0001",
253+
key=f"key-{release}")],
254+
}
255+
for i, (release, action) in enumerate(zip(["a", "b", "c", "d"], actions))
256+
]
257+
258+
alerts = Dedupe.dedupe(packages)[0]["alerts"]
259+
260+
self.assertEqual(len(alerts), 1)
261+
self.assertEqual(alerts[0]["action"], "error")
262+
self.assertEqual(alerts[0]["releases"], ["a", "b", "c", "d"])
263+
264+
def test_merged_action_ranks_error_warn_monitor_ignore(self):
265+
cases = [
266+
(["ignore", "monitor"], "monitor"),
267+
(["monitor", "warn"], "warn"),
268+
(["warn", "ignore"], "warn"),
269+
([None, "ignore"], "ignore"),
270+
(["ignore", None], "ignore"),
271+
(["unknown-action", "monitor"], "monitor"),
272+
# An unknown action yields to any known one, "ignore" included,
273+
# and never replaces a known "error", in either order.
274+
(["unknown-action", "ignore"], "ignore"),
275+
(["error", "unknown-action"], "error"),
276+
(["unknown-action", "error"], "error"),
277+
]
278+
for actions, expected in cases:
279+
with self.subTest(actions=actions):
280+
packages = [
281+
{
282+
"id": f"artifact-{i}", "type": "pypi", "name": "example", "version": "1.0",
283+
"release": f"r{i}", "inputPurl": "pkg:pypi/example@1.0",
284+
"alerts": [self._cve("GHSA-dddd-dddd-dddd", action)],
285+
}
286+
for i, action in enumerate(actions)
287+
]
288+
alerts = Dedupe.dedupe(packages)[0]["alerts"]
289+
self.assertEqual(len(alerts), 1)
290+
self.assertEqual(alerts[0]["action"], expected)
291+
292+
def test_merged_alert_keeps_first_key_when_action_comes_from_a_later_release(self):
293+
"""Only the action moves to the most severe sighting; key and props stay with the first"""
294+
packages = [
295+
{
296+
"id": f"artifact-{release}", "type": "pypi", "name": "example", "version": "1.0",
297+
"release": release, "inputPurl": "pkg:pypi/example@1.0",
298+
"alerts": [self._cve("GHSA-eeee-eeee-eeee", action, key=f"key-{release}")],
299+
}
300+
for release, action in [("sdist", "monitor"), ("wheel", "error")]
301+
]
302+
303+
alerts = Dedupe.dedupe(packages)[0]["alerts"]
304+
305+
self.assertEqual(len(alerts), 1)
306+
self.assertEqual(alerts[0]["key"], "key-sdist")
307+
self.assertEqual(alerts[0]["action"], "error")
308+
309+
def test_non_advisory_alert_on_a_package_with_cves_keeps_its_own_entry(self):
310+
packages = [{
311+
"id": "artifact-1", "type": "npm", "name": "example", "version": "1.0.0",
312+
"alerts": [
313+
self._cve("GHSA-ffff-ffff-ffff", "monitor"),
314+
{"key": "key-malware", "type": "malware", "severity": "critical",
315+
"category": "supplyChainRisk", "action": "error", "props": {}},
316+
],
317+
}]
318+
319+
alerts = Dedupe.dedupe(packages, batched=False)[0]["alerts"]
320+
321+
self.assertEqual({a["type"]: a["action"] for a in alerts}, {"criticalCVE": "monitor", "malware": "error"})
322+
323+
def test_dedupe_of_no_packages_is_empty(self):
324+
self.assertEqual(Dedupe.dedupe([]), [])
325+
326+
def test_advisory_id_falls_back_to_cve_and_ignores_case(self):
327+
self.assertEqual(Dedupe.advisory_id({"props": {"ghsaId": "", "cveId": "cve-2021-1"}}), "CVE-2021-1")
328+
self.assertEqual(Dedupe.advisory_id({"props": {"ghsaId": " ghsa-x "}}), "GHSA-X")
329+
self.assertEqual(Dedupe.advisory_id({"props": {"cve": ["", "CVE-2022-2"]}}), "CVE-2022-2")
330+
self.assertEqual(Dedupe.advisory_id({"props": []}), "")
331+
self.assertEqual(Dedupe.advisory_id({}), "")
332+
333+
packages = [{
334+
"id": "artifact-1", "type": "npm", "name": "example", "version": "1.0.0",
335+
"alerts": [
336+
self._cve("", "error", cve="CVE-2021-0001"),
337+
self._cve("", "error", cve="CVE-2021-0002"),
338+
self._cve("", "monitor", cve="cve-2021-0001"),
339+
],
340+
}]
341+
alerts = Dedupe.dedupe(packages, batched=False)[0]["alerts"]
342+
self.assertEqual(sorted(a["props"]["cveId"] for a in alerts), ["CVE-2021-0001", "CVE-2021-0002"])
343+
344+
def test_alerts_without_advisory_still_merge_across_releases(self):
345+
"""Alerts without an advisory ID merge on type, severity and location, with file paths normalized"""
346+
def file_alert(path, action):
347+
return {
348+
"key": f"key-{path}", "type": "networkAccess", "severity": "middle",
349+
"category": "supplyChainRisk", "file": path, "start": 10, "end": 20,
350+
"action": action, "props": {"module": "http"},
351+
}
352+
packages = [
353+
{"id": "1", "type": "pypi", "name": "example", "version": "1.0", "release": "wheel",
354+
"inputPurl": "pkg:pypi/example@1.0", "alerts": [file_alert("wheel/example/net.py", "monitor")]},
355+
{"id": "2", "type": "pypi", "name": "example", "version": "1.0", "release": "sdist",
356+
"inputPurl": "pkg:pypi/example@1.0", "alerts": [file_alert("sdist/example/net.py", "warn")]},
357+
]
358+
359+
alerts = Dedupe.dedupe(packages)[0]["alerts"]
360+
361+
self.assertEqual(len(alerts), 1)
362+
self.assertEqual(alerts[0]["file"], "example/net.py")
363+
self.assertEqual(alerts[0]["action"], "warn")
364+
self.assertEqual(alerts[0]["releases"], ["wheel", "sdist"])
365+
190366

191367
if __name__ == '__main__':
192368
unittest.main()

‎tests/unit/test_full_scan_cached_polling_http.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,37 @@ def test_duplicate_artifacts_merge_alerts_and_preserve_score_event(api_fixture):
118118
assert artifact["alerts"][0]["releases"] == ["wheel", "source"]
119119

120120

121+
def test_stream_keeps_each_advisory_and_its_action(api_fixture):
122+
"""Same-severity CVEs on one artifact reach the caller as separate alerts."""
123+
path = "orgs/org/full-scans/scan"
124+
125+
def cve(ghsa, cve_id, action):
126+
return {
127+
"key": "key-" + ghsa, "type": "criticalCVE", "severity": "critical",
128+
"category": "vulnerability", "action": action,
129+
"props": {"ghsaId": ghsa, "cveId": cve_id},
130+
}
131+
132+
artifact = {
133+
"id": "artifact-1", "type": "npm", "name": "handlebars", "version": "4.0.11",
134+
"alerts": [
135+
cve("GHSA-w457-6q6x-cgp9", "CVE-2019-19919", "monitor"),
136+
cve("GHSA-765h-qjxv-5f44", "CVE-2021-23383", "error"),
137+
cve("GHSA-f2jv-r9rf-7988", "CVE-2021-23369", "ignore"),
138+
],
139+
}
140+
api_fixture.route("GET", path, ndjson(artifact))
141+
142+
typed = sdk_for(api_fixture).fullscans.stream("org", "scan", use_types=True)
143+
144+
alerts = typed.artifacts["artifact-1"].alerts
145+
assert [(alert.props["ghsaId"], alert.action) for alert in alerts] == [
146+
("GHSA-w457-6q6x-cgp9", "monitor"),
147+
("GHSA-765h-qjxv-5f44", "error"),
148+
("GHSA-f2jv-r9rf-7988", "ignore"),
149+
]
150+
151+
121152
@pytest.mark.parametrize("status", [403, 404])
122153
def test_deterministic_errors_stop_immediately(api_fixture, status):
123154
api_fixture.route("GET", "orgs/org/full-scans/scan", SocketResponse(status, {"error": {"message": "denied"}}))

0 commit comments

Comments
 (0)