Skip to content

Commit c769f2b

Browse files
committed
Keep each advisory when collapsing repeat alerts
The diff collapsed alerts on (purl, alert type) so a package pulled in by several manifests reports each finding once. Every CVE of one severity on a package shares an alert type, so a package's second advisory was dropped from every output, and a blocking advisory could be dropped behind a warning on the same package, letting the run pass. Alerts now collapse on Issue.consolidation_key, which adds the ecosystem and the GHSA or CVE ID. The PR comment shows that ID next to the title, so two advisories on one package no longer render as identical rows.
1 parent 51ada53 commit c769f2b

5 files changed

Lines changed: 185 additions & 29 deletions

File tree

‎socketsecurity/core/__init__.py‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,13 +1357,13 @@ def create_full_scan_with_report_url(
13571357
packages=packages
13581358
)
13591359

1360-
consolidated: Set[str] = set()
1360+
consolidated: Set[Tuple[str, str, str, str]] = set()
13611361
for alert_key, alerts in all_alerts_collection.items():
13621362
for alert in alerts:
1363-
alert_str = f"{alert.purl},{alert.type}"
1364-
if (alert.error or alert.warn) and alert_str not in consolidated:
1363+
finding_key = alert.consolidation_key()
1364+
if (alert.error or alert.warn) and finding_key not in consolidated:
13651365
diff.new_alerts.append(alert)
1366-
consolidated.add(alert_str)
1366+
consolidated.add(finding_key)
13671367
diff.alerts_fetched = True
13681368

13691369
sbom_end = time.time()
@@ -2880,29 +2880,27 @@ def get_new_alerts(
28802880
if alert_key not in removed_package_alerts:
28812881
new_alerts = added_package_alerts[alert_key]
28822882
for alert in new_alerts:
2883-
# Consolidate by package and alert type, not by manifest details
2884-
alert_str = f"{alert.purl},{alert.type}"
2883+
finding_key = alert.consolidation_key()
28852884

28862885
if alert.error or alert.warn:
2887-
if alert_str not in consolidated_alerts:
2886+
if finding_key not in consolidated_alerts:
28882887
alerts.append(alert)
2889-
consolidated_alerts.add(alert_str)
2888+
consolidated_alerts.add(finding_key)
28902889
else:
28912890
new_alerts = added_package_alerts[alert_key]
28922891
removed_alerts = removed_package_alerts[alert_key]
28932892

28942893
for alert in new_alerts:
2895-
# Consolidate by package and alert type, not by manifest details
2896-
alert_str = f"{alert.purl},{alert.type}"
2894+
finding_key = alert.consolidation_key()
28972895

28982896
# Only add if:
28992897
# 1. Alert isn't in removed packages (or we're not ignoring readded alerts)
29002898
# 2. We haven't already recorded this alert
29012899
# 3. It's an error or warning
2902-
if (not ignore_readded or alert not in removed_alerts) and alert_str not in consolidated_alerts:
2900+
if (not ignore_readded or alert not in removed_alerts) and finding_key not in consolidated_alerts:
29032901
if alert.error or alert.warn:
29042902
alerts.append(alert)
2905-
consolidated_alerts.add(alert_str)
2903+
consolidated_alerts.add(finding_key)
29062904

29072905
return alerts
29082906

@@ -2927,13 +2925,12 @@ def get_unchanged_alerts(
29272925

29282926
for alert_key in unchanged_package_alerts:
29292927
for alert in unchanged_package_alerts[alert_key]:
2930-
# Consolidate by package and alert type
2931-
alert_str = f"{alert.purl},{alert.type}"
2928+
finding_key = alert.consolidation_key()
29322929

29332930
# Only include error or warning alerts
2934-
if (alert.error or alert.warn) and alert_str not in consolidated_alerts:
2931+
if (alert.error or alert.warn) and finding_key not in consolidated_alerts:
29352932
alerts.append(alert)
2936-
consolidated_alerts.add(alert_str)
2933+
consolidated_alerts.add(finding_key)
29372934

29382935
return alerts
29392936

@@ -2957,10 +2954,10 @@ def get_removed_alerts(
29572954

29582955
for alert_key in removed_package_alerts:
29592956
for alert in removed_package_alerts[alert_key]:
2960-
alert_str = f"{alert.purl},{alert.type}"
2957+
finding_key = alert.consolidation_key()
29612958

2962-
if alert_str not in consolidated_alerts:
2959+
if finding_key not in consolidated_alerts:
29632960
alerts.append(alert)
2964-
consolidated_alerts.add(alert_str)
2961+
consolidated_alerts.add(finding_key)
29652962

29662963
return alerts

‎socketsecurity/core/alert_selection.py‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,8 @@ def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> List[Issue]
1515
"""Select diff alerts for output rendering.
1616
1717
In strict blocking mode, include unchanged alerts so rendered output aligns
18-
with pass/fail policy evaluation. An unchanged alert that is already listed
19-
as new (same ecosystem, purl and alert type) is skipped so each finding is
20-
rendered once. The ecosystem is part of the key because ``Issue.purl`` holds
21-
only name and version, so an npm and a PyPI package can share it.
18+
with pass/fail policy evaluation. An unchanged alert already listed as new
19+
(same Issue.consolidation_key) is skipped so each finding is rendered once.
2220
"""
2321
selected = list(getattr(diff, "new_alerts", []) or [])
2422
if strict_blocking:
@@ -31,11 +29,10 @@ def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> List[Issue]
3129
return selected
3230

3331

34-
def _alert_identity(alert: Issue) -> Optional[Tuple[str, str, str]]:
35-
purl = getattr(alert, "purl", "") or ""
36-
if not purl:
32+
def _alert_identity(alert: Issue) -> Optional[Tuple[str, str, str, str]]:
33+
if not (getattr(alert, "purl", "") or ""):
3734
return None
38-
return (getattr(alert, "pkg_type", "") or "", purl, getattr(alert, "type", "") or "")
35+
return alert.consolidation_key()
3936

4037

4138
def clone_diff_with_selected_alerts(diff: Diff, selected_alerts: List[Issue]) -> Diff:

‎socketsecurity/core/classes.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import logging
33
from dataclasses import dataclass, field
4-
from typing import Dict, List, Optional, TypedDict
4+
from typing import Dict, List, Optional, Tuple, TypedDict
55

66
from socketdev.fullscans import (
77
FullScanMetadata,
@@ -19,6 +19,11 @@
1919
# one path segment that cannot be split back into two, and the page does not resolve.
2020
NAMESPACE_REQUIRED_TYPES = frozenset({"maven"})
2121

22+
# Alert props that name a vulnerability advisory, in the order Issue.advisory_id
23+
# reads them. Alerts reach Issue.props from several sources, so both spellings
24+
# appear; "cve" is the older field name.
25+
ADVISORY_ID_PROPS = ("ghsaId", "ghsa_id", "cveId", "cve_id", "cve")
26+
2227
__all__ = [
2328
"Report",
2429
"Score",
@@ -354,6 +359,34 @@ def __init__(self, **kwargs):
354359
if not hasattr(self, "ignore"):
355360
self.ignore = False
356361

362+
def advisory_id(self) -> str:
363+
"""The GHSA or CVE identifier in the alert's props, upper-cased, or ""."""
364+
props = getattr(self, "props", None) or {}
365+
for prop_name in ADVISORY_ID_PROPS:
366+
value = props.get(prop_name)
367+
if isinstance(value, (list, tuple)):
368+
value = next((v for v in value if isinstance(v, str) and v.strip()), "")
369+
if isinstance(value, str) and value.strip():
370+
return value.strip().upper()
371+
return ""
372+
373+
def consolidation_key(self) -> Tuple[str, str, str, str]:
374+
"""Identity used to collapse repeat sightings of one finding into one alert.
375+
376+
The same alert arrives once per manifest that pulls the package in, so the
377+
key leaves manifest details out. It keeps the advisory ID because every CVE
378+
of a given severity on a package shares one alert type (``criticalCVE``,
379+
``cve`` and so on): without it, a package's second advisory would be dropped,
380+
and with it any blocking action that advisory carried. It keeps the
381+
ecosystem because ``purl`` holds only name and version.
382+
"""
383+
return (
384+
getattr(self, "pkg_type", "") or "",
385+
getattr(self, "purl", "") or "",
386+
getattr(self, "type", "") or "",
387+
self.advisory_id(),
388+
)
389+
357390
def __str__(self):
358391
return json.dumps(self.__dict__)
359392

‎socketsecurity/core/messages.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,19 @@ def get_view_report_url(diff: Diff) -> str:
925925
return diff.report_url
926926
return ""
927927

928+
@staticmethod
929+
def alert_title_with_advisory(alert: Issue) -> str:
930+
"""The alert title, followed by its GHSA or CVE ID when it has one.
931+
932+
Every CVE of one severity shares a title ("Critical CVE"), so without the
933+
ID two advisories on the same package render as identical rows.
934+
"""
935+
title = getattr(alert, "title", "") or ""
936+
advisory = alert.advisory_id() if hasattr(alert, "advisory_id") else ""
937+
if advisory and advisory not in title.upper():
938+
return f"{title} ({advisory})"
939+
return title
940+
928941
@staticmethod
929942
def security_comment_template(diff: Diff, config=None) -> str:
930943
"""
@@ -993,6 +1006,7 @@ def security_comment_template(diff: Diff, config=None) -> str:
9931006
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
9941007
pkg_label = Messages.html_text(f"{alert.pkg_name}@{alert.pkg_version}")
9951008
pkg_marker = Messages.comment_marker_text(f"{alert.pkg_name}@{alert.pkg_version}")
1009+
alert_title = Messages.alert_title_with_advisory(alert)
9961010
# Generate a table row for each alert
9971011
ignore_html = (
9981012
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
@@ -1009,7 +1023,7 @@ def security_comment_template(diff: Diff, config=None) -> str:
10091023
</td>
10101024
<td>
10111025
<details {details_open}>
1012-
<summary>{pkg_label} - {Messages.html_text(alert.title)}</summary>
1026+
<summary>{pkg_label} - {Messages.html_text(alert_title)}</summary>
10131027
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
10141028
{patched_version_html}
10151029
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
"""Repeat sightings of one finding collapse into one alert; distinct advisories don't.
2+
3+
The same alert arrives once per manifest that pulls a package in, so the diff
4+
collapses alerts on Issue.consolidation_key. Every CVE of one severity on a
5+
package shares an alert type, so the key has to include the advisory ID, or a
6+
package's second advisory is dropped along with any blocking action it carries.
7+
"""
8+
from unittest.mock import Mock
9+
10+
from socketsecurity.config import CliConfig
11+
from socketsecurity.core import Core
12+
from socketsecurity.core.classes import Diff, Issue
13+
from socketsecurity.core.messages import Messages
14+
from socketsecurity.output import OutputHandler
15+
16+
17+
def _cve(advisory, error=False, warn=False, pkg_type="npm", key=None, props_field="ghsaId"):
18+
return Issue(
19+
pkg_type=pkg_type,
20+
pkg_name="lodash",
21+
pkg_version="4.17.20",
22+
purl="lodash@4.17.20",
23+
type="criticalCVE",
24+
severity="critical",
25+
title="Critical CVE",
26+
description="A vulnerability.",
27+
suggestion="Upgrade.",
28+
url="https://socket.dev/npm/package/lodash",
29+
key=key or f"key-{advisory}",
30+
props={props_field: advisory},
31+
error=error,
32+
warn=warn,
33+
)
34+
35+
36+
def test_two_advisories_on_one_package_are_both_new_alerts():
37+
alerts = {
38+
"k1": [_cve("GHSA-aaaa-aaaa-aaaa", error=True)],
39+
"k2": [_cve("GHSA-bbbb-bbbb-bbbb", error=True)],
40+
}
41+
42+
new_alerts = Core.get_new_alerts(alerts, {})
43+
44+
assert sorted(a.advisory_id() for a in new_alerts) == [
45+
"GHSA-AAAA-AAAA-AAAA",
46+
"GHSA-BBBB-BBBB-BBBB",
47+
]
48+
49+
50+
def test_blocking_advisory_is_not_hidden_behind_a_warning():
51+
"""The kept advisory is a warning; dropping the second would pass the run."""
52+
alerts = {
53+
"k1": [_cve("GHSA-aaaa-aaaa-aaaa", warn=True)],
54+
"k2": [_cve("GHSA-bbbb-bbbb-bbbb", error=True)],
55+
}
56+
diff = Diff()
57+
diff.new_alerts = Core.get_new_alerts(alerts, {})
58+
59+
config = Mock(spec=CliConfig)
60+
config.disable_blocking = False
61+
config.strict_blocking = False
62+
assert not OutputHandler(config, Mock()).report_pass(diff)
63+
64+
65+
def test_same_advisory_from_two_manifests_is_one_alert():
66+
alerts = {
67+
"k1": [_cve("GHSA-aaaa-aaaa-aaaa", error=True), _cve("GHSA-aaaa-aaaa-aaaa", error=True)],
68+
}
69+
70+
assert len(Core.get_new_alerts(alerts, {})) == 1
71+
72+
73+
def test_unchanged_and_removed_alerts_keep_each_advisory():
74+
alerts = {
75+
"k1": [_cve("CVE-2026-0001", error=True, props_field="cveId")],
76+
"k2": [_cve("CVE-2026-0002", error=True, props_field="cveId")],
77+
}
78+
79+
assert len(Core.get_unchanged_alerts(alerts)) == 2
80+
assert len(Core.get_removed_alerts(alerts)) == 2
81+
82+
83+
def test_consolidation_key_includes_ecosystem_and_ignores_advisory_case():
84+
npm = _cve("ghsa-aaaa-aaaa-aaaa")
85+
pypi = _cve("GHSA-AAAA-AAAA-AAAA", pkg_type="pypi")
86+
87+
assert npm.consolidation_key() != pypi.consolidation_key()
88+
assert npm.consolidation_key()[3] == pypi.consolidation_key()[3]
89+
90+
91+
def test_non_advisory_alerts_still_collapse_per_package_and_type():
92+
"""Alerts with no advisory ID keep the per-package, per-type collapse."""
93+
first = Issue(pkg_type="npm", purl="a@1.0.0", type="envVars", props={}, warn=True, key="k1")
94+
second = Issue(pkg_type="npm", purl="a@1.0.0", type="envVars", props={}, warn=True, key="k2")
95+
96+
assert len(Core.get_new_alerts({"k1": [first], "k2": [second]}, {})) == 1
97+
98+
99+
def test_pr_comment_rows_name_the_advisory():
100+
diff = Diff()
101+
diff.new_alerts = [_cve("GHSA-aaaa-aaaa-aaaa", error=True), _cve("GHSA-bbbb-bbbb-bbbb", error=True)]
102+
diff.diff_url = "https://socket.dev/diff"
103+
diff.report_url = "https://socket.dev/report"
104+
105+
comment = Messages.security_comment_template(diff)
106+
107+
assert "Critical CVE (GHSA-AAAA-AAAA-AAAA)" in comment
108+
assert "Critical CVE (GHSA-BBBB-BBBB-BBBB)" in comment
109+
110+
111+
def test_title_already_naming_the_advisory_is_left_alone():
112+
alert = _cve("GHSA-aaaa-aaaa-aaaa")
113+
alert.title = "GHSA-aaaa-aaaa-aaaa in lodash"
114+
115+
assert Messages.alert_title_with_advisory(alert) == "GHSA-aaaa-aaaa-aaaa in lodash"

0 commit comments

Comments
 (0)