From f302c2f7d1cf58cf2f122583d34ef6bb778aad86 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Tue, 1 Dec 2026 13:51:35 -0500 Subject: [PATCH 1/2] Link the GHSA and CVE ID on each PR/MR comment alert Each security comment row showed one advisory ID, the GHSA when the alert had one and the CVE otherwise, as plain text. Alerts from the API usually carry both, so the CVE was dropped from the row, and developers who only see the PR comment had no link to the advisory. Rows now list every advisory ID on the alert, GHSA first, each linked to its public page (github.com/advisories for GHSA, nvd.nist.gov for CVE), the same two sites the GitLab security report already links. Only IDs in the canonical GHSA or CVE shape are linked; anything else renders as escaped text. IDs keep the API's spelling instead of being upper-cased. Issue.advisory_ids() is new and used only for display. advisory_id() and consolidation_key() are unchanged, so de-duplication, SARIF rule IDs and GitLab finding IDs stay the same. Shares the 2.16.0 version set in #478. --- CHANGELOG.md | 7 ++ pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- socketsecurity/core/classes.py | 26 +++++ socketsecurity/core/messages.py | 55 +++++++++-- tests/core/test_alert_consolidation.py | 4 +- tests/core/test_existing_alerts.py | 2 +- ...test_strict_blocking_no_manifest_change.py | 4 +- tests/unit/test_comment_advisory_links.py | 99 +++++++++++++++++++ uv.lock | 2 +- 10 files changed, 189 insertions(+), 14 deletions(-) create mode 100644 tests/unit/test_comment_advisory_links.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cf2f3aa9..84ab518c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 2.16.0 + +### Changed + +- PR and MR security comments link available GHSA and CVE IDs to their public + advisory pages. + ## 2.15.7 ### Changed: bump pinned Coana CLI to 15.15.9 diff --git a/pyproject.toml b/pyproject.toml index 7452ff6c..c15612d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.7" +version = "2.16.0" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 22abed13..b81e67ea 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.15.7' +__version__ = '2.16.0' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/core/classes.py b/socketsecurity/core/classes.py index bdea4b41..553662f1 100644 --- a/socketsecurity/core/classes.py +++ b/socketsecurity/core/classes.py @@ -382,6 +382,32 @@ def advisory_id(self) -> str: return value.strip().upper() return "" + def advisory_ids(self) -> List[str]: + """Every distinct GHSA and CVE identifier on the alert, GHSA first. + + IDs keep the spelling the API sent. advisory_id() still returns a single + ID because consolidation_key() depends on it; this list is for display, + where an alert that carries both a GHSA and a CVE should show both. + """ + props = getattr(self, "props", None) or {} + ids: List[str] = [] + seen = set() + for prop_name in ADVISORY_ID_PROPS: + values = props.get(prop_name) + if isinstance(values, str): + values = [values] + elif not isinstance(values, (list, tuple)): + continue + for value in values: + if not isinstance(value, str) or not value.strip(): + continue + value = value.strip() + if value.upper() in seen: + continue + seen.add(value.upper()) + ids.append(value) + return ids + def consolidation_key(self) -> Tuple[str, str, str, str]: """Identity used to collapse repeat sightings of one finding into one alert. diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 3b475dee..64920ae7 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -13,6 +13,13 @@ log = logging.getLogger("socketcli") +# Public advisory pages for the IDs shown in PR/MR comments, keyed by the ID's +# canonical shape. The GitLab security report links the same two sites. +ADVISORY_LINK_BASES = ( + (re.compile(r"^GHSA(-[0-9a-z]{4}){3}$", re.IGNORECASE), "https://github.com/advisories/"), + (re.compile(r"^CVE-\d{4}-\d{4,}$", re.IGNORECASE), "https://nvd.nist.gov/vuln/detail/"), +) + class Messages: @staticmethod @@ -1048,7 +1055,6 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s package = f"{alert.package_name_with_namespace()}@{alert.pkg_version}" pkg_label = Messages.html_text(package) pkg_marker = Messages.alert_package_marker(alert, package) - alert_title = Messages.alert_title_with_advisory(alert) ignore_html = ( f"

Mark as acceptable risk: To ignore this alert only in this pull request, reply with:
" f"@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}
" @@ -1064,7 +1070,7 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s

- {pkg_label} - {Messages.html_text(alert_title)} + {pkg_label} - {Messages.alert_title_html(alert)}

Note: {Messages.html_text(alert.description)}

{patched_version_html}

Source: Manifest File

@@ -1082,19 +1088,56 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s """ + @staticmethod + def advisory_ids_for_title(alert: Issue) -> list: + """The alert's GHSA and CVE IDs, GHSA first, minus any its title already names.""" + title = (getattr(alert, "title", "") or "").upper() + ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else [] + return [advisory for advisory in ids if advisory.upper() not in title] + @staticmethod def alert_title_with_advisory(alert: Issue) -> str: - """The alert title, followed by its GHSA or CVE ID when it has one. + """The alert title, followed by its GHSA and CVE IDs when it has them. Every CVE of one severity shares a title ("Critical CVE"), so without the ID two advisories on the same package render as identical rows. """ title = getattr(alert, "title", "") or "" - advisory = alert.advisory_id() if hasattr(alert, "advisory_id") else "" - if advisory and advisory not in title.upper(): - return f"{title} ({advisory})" + ids = Messages.advisory_ids_for_title(alert) + if ids: + return f"{title} ({', '.join(ids)})" return title + @staticmethod + def advisory_link_html(advisory: str) -> str: + """An advisory ID linked to its public advisory page. + + Only IDs in the canonical GHSA or CVE shape are linked, so an unexpected + value renders as escaped text instead of an arbitrary URL path. + """ + for pattern, base_url in ADVISORY_LINK_BASES: + if pattern.match(advisory): + return ( + f'' + f"{Messages.html_text(advisory)}" + ) + return Messages.html_text(advisory) + + @staticmethod + def alert_title_html(alert: Issue) -> str: + """The PR/MR comment row title: escaped title, then each advisory ID linked. + + Developers who only see the PR comment can open the GHSA on GitHub and the + CVE on NVD without a Socket login. Alerts usually carry both IDs, and + either can be published first, so the row shows every ID the alert has. + """ + title = Messages.html_text(getattr(alert, "title", "") or "") + ids = Messages.advisory_ids_for_title(alert) + if not ids: + return title + links = ", ".join(Messages.advisory_link_html(advisory) for advisory in ids) + return f"{title} ({links})" + @staticmethod def security_comment_template(diff: Diff, config=None) -> str: """Render the PR/MR security comment within the provider's size limit.""" diff --git a/tests/core/test_alert_consolidation.py b/tests/core/test_alert_consolidation.py index e0a7d331..bbca9d80 100644 --- a/tests/core/test_alert_consolidation.py +++ b/tests/core/test_alert_consolidation.py @@ -133,8 +133,8 @@ def test_pr_comment_rows_name_the_advisory(): comment = Messages.security_comment_template(diff) - assert "Critical CVE (GHSA-AAAA-AAAA-AAAA)" in comment - assert "Critical CVE (GHSA-BBBB-BBBB-BBBB)" in comment + assert 'Critical CVE (GHSA-aaaa-aaaa-aaaa)' in comment + assert 'Critical CVE (GHSA-bbbb-bbbb-bbbb)' in comment def test_title_already_naming_the_advisory_is_left_alone(): diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index d184c6cc..ae82743e 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -454,7 +454,7 @@ def test_every_same_severity_advisory_on_an_unchanged_package_is_kept(core, capl comment = Messages.security_comment_template(diff, _config()) assert "Existing alerts (6)" in comment for ghsa, _ in HANDLEBARS_CRITICAL_ADVISORIES: - assert ghsa.upper() in comment + assert f'{ghsa}' in comment @pytest.mark.parametrize("triaged_action", ["ignore", "monitor"]) diff --git a/tests/core/test_strict_blocking_no_manifest_change.py b/tests/core/test_strict_blocking_no_manifest_change.py index d2ab41bc..95b9a813 100644 --- a/tests/core/test_strict_blocking_no_manifest_change.py +++ b/tests/core/test_strict_blocking_no_manifest_change.py @@ -265,9 +265,9 @@ def test_code_only_scan_with_pr_context_comments_on_each_existing_blocker( security_comment, _, _, post_security, _ = github_pull_request.call_args.args assert post_security is True assert "Existing alerts (2)" in security_comment - assert resolved[0].upper() not in security_comment + assert resolved[0].upper() not in security_comment.upper() for ghsa, _ in blocking: - assert ghsa.upper() in security_comment + assert f'{ghsa}' in security_comment @pytest.mark.parametrize("policy, infrastructure_code", POLICIES) diff --git a/tests/unit/test_comment_advisory_links.py b/tests/unit/test_comment_advisory_links.py new file mode 100644 index 00000000..8b5e2de4 --- /dev/null +++ b/tests/unit/test_comment_advisory_links.py @@ -0,0 +1,99 @@ +"""PR/MR comment rows show every GHSA and CVE ID on an alert, each linked. + +Developers who only see the PR comment need the advisory itself. Socket CVE +alerts usually carry both a GHSA and a CVE ID, and either can be published +first, so the row names both and links the GHSA to GitHub and the CVE to NVD. +The single advisory_id() used for de-duplication stays unchanged. +""" +from socketsecurity.core.classes import Diff, Issue +from socketsecurity.core.messages import Messages + +GHSA = "GHSA-35jh-r3h4-6jhm" +CVE = "CVE-2021-23337" +GHSA_LINK = f'{GHSA}' +CVE_LINK = f'{CVE}' + + +def _alert(props, title="Critical CVE"): + return Issue( + pkg_type="npm", + pkg_name="lodash", + pkg_version="4.17.20", + purl="lodash@4.17.20", + type="criticalCVE", + severity="critical", + title=title, + description="A vulnerability.", + suggestion="Upgrade.", + url="https://socket.dev/npm/package/lodash/overview/4.17.20", + key="k1", + props=props, + error=True, + ) + + +def _comment(alert): + diff = Diff() + diff.new_alerts = [alert] + diff.diff_url = "https://socket.dev/diff" + diff.report_url = "https://socket.dev/report" + return Messages.security_comment_template(diff) + + +def test_alert_with_both_ids_shows_both_linked_ghsa_first(): + comment = _comment(_alert({"ghsaId": GHSA, "cveId": CVE})) + + assert f"Critical CVE ({GHSA_LINK}, {CVE_LINK})" in comment + + +def test_ghsa_only_alert_links_the_ghsa(): + assert Messages.alert_title_html(_alert({"ghsaId": GHSA})) == f"Critical CVE ({GHSA_LINK})" + + +def test_cve_only_alert_links_the_cve(): + assert Messages.alert_title_html(_alert({"cveId": CVE})) == f"Critical CVE ({CVE_LINK})" + + +def test_older_and_snake_case_spellings_are_read_and_deduplicated(): + alert = _alert({"ghsa_id": GHSA, "cve_id": [CVE, CVE.lower()], "cve": CVE}) + + assert alert.advisory_ids() == [GHSA, CVE] + assert Messages.alert_title_html(alert) == f"Critical CVE ({GHSA_LINK}, {CVE_LINK})" + + +def test_id_already_in_the_title_is_not_repeated(): + alert = _alert({"ghsaId": GHSA, "cveId": CVE}, title=f"{CVE} in lodash") + + assert Messages.alert_title_html(alert) == f"{CVE} in lodash ({GHSA_LINK})" + + +def test_unexpected_id_shape_is_escaped_text_not_a_link(): + alert = _alert({"ghsaId": 'GHSA-">', "cveId": CVE}) + + html = Messages.alert_title_html(alert) + + assert " Date: Wed, 2 Dec 2026 10:44:38 -0500 Subject: [PATCH 2/2] Link advisory IDs that already appear in the alert title An ID the title already named was dropped from the linked list and stayed plain text, and the substring check also hid a different CVE whose ID is a prefix of one in the title (CVE-2021-2333 inside CVE-2021-23337). IDs now match only in full. An ID the title names is linked in place, keeping the title's spelling and linking the API's ID, and the remaining IDs are appended once. The plain-text title uses the same full-ID match. --- socketsecurity/core/messages.py | 68 ++++++++++++++++------- tests/unit/test_comment_advisory_links.py | 34 +++++++++++- 2 files changed, 79 insertions(+), 23 deletions(-) diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 64920ae7..960ca4e4 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -1088,12 +1088,21 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s """ + @staticmethod + def _advisory_id_pattern(ids) -> "re.Pattern[str]": + """Matches any of the IDs in full, so CVE-2021-2333 does not match inside CVE-2021-23337.""" + alternatives = "|".join(re.escape(advisory) for advisory in sorted(ids, key=len, reverse=True)) + return re.compile(rf"(? list: """The alert's GHSA and CVE IDs, GHSA first, minus any its title already names.""" - title = (getattr(alert, "title", "") or "").upper() + title = getattr(alert, "title", "") or "" ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else [] - return [advisory for advisory in ids if advisory.upper() not in title] + return [ + advisory for advisory in ids + if not Messages._advisory_id_pattern([advisory]).search(title) + ] @staticmethod def alert_title_with_advisory(alert: Issue) -> str: @@ -1109,34 +1118,53 @@ def alert_title_with_advisory(alert: Issue) -> str: return title @staticmethod - def advisory_link_html(advisory: str) -> str: + def _advisory_link_base(advisory: str) -> str | None: + for pattern, base_url in ADVISORY_LINK_BASES: + if pattern.match(advisory): + return base_url + return None + + @staticmethod + def advisory_link_html(advisory: str, label_html: str | None = None) -> str: """An advisory ID linked to its public advisory page. Only IDs in the canonical GHSA or CVE shape are linked, so an unexpected value renders as escaped text instead of an arbitrary URL path. """ - for pattern, base_url in ADVISORY_LINK_BASES: - if pattern.match(advisory): - return ( - f'' - f"{Messages.html_text(advisory)}" - ) - return Messages.html_text(advisory) + label = Messages.html_text(advisory) if label_html is None else label_html + base_url = Messages._advisory_link_base(advisory) + if base_url is None: + return label + return f'{label}' @staticmethod def alert_title_html(alert: Issue) -> str: - """The PR/MR comment row title: escaped title, then each advisory ID linked. + """The PR/MR comment row title as HTML. - Developers who only see the PR comment can open the GHSA on GitHub and the - CVE on NVD without a Socket login. Alerts usually carry both IDs, and - either can be published first, so the row shows every ID the alert has. + The title is escaped. The alert's GHSA and CVE IDs are linked in place where + the title names them in full, and the remaining IDs follow once, linked, in + parentheses. Only canonical GHSA and CVE IDs become links. """ - title = Messages.html_text(getattr(alert, "title", "") or "") - ids = Messages.advisory_ids_for_title(alert) - if not ids: - return title - links = ", ".join(Messages.advisory_link_html(advisory) for advisory in ids) - return f"{title} ({links})" + title_html = Messages.html_text(getattr(alert, "title", "") or "") + ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else [] + remaining = Messages.advisory_ids_for_title(alert) + # Canonical IDs are letters, digits and hyphens, which escaping leaves alone. + in_title = { + advisory.upper(): advisory + for advisory in ids + if advisory not in remaining and Messages._advisory_link_base(advisory) + } + if in_title: + title_html = Messages._advisory_id_pattern(in_title.values()).sub( + lambda match: Messages.advisory_link_html( + in_title[match.group(0).upper()], match.group(0) + ), + title_html, + ) + if not remaining: + return title_html + links = ", ".join(Messages.advisory_link_html(advisory) for advisory in remaining) + return f"{title_html} ({links})" @staticmethod def security_comment_template(diff: Diff, config=None) -> str: diff --git a/tests/unit/test_comment_advisory_links.py b/tests/unit/test_comment_advisory_links.py index 8b5e2de4..33d50f4d 100644 --- a/tests/unit/test_comment_advisory_links.py +++ b/tests/unit/test_comment_advisory_links.py @@ -1,4 +1,4 @@ -"""PR/MR comment rows show every GHSA and CVE ID on an alert, each linked. +"""PR/MR comment rows link every GHSA and CVE ID on an alert. Developers who only see the PR comment need the advisory itself. Socket CVE alerts usually carry both a GHSA and a CVE ID, and either can be published @@ -61,10 +61,38 @@ def test_older_and_snake_case_spellings_are_read_and_deduplicated(): assert Messages.alert_title_html(alert) == f"Critical CVE ({GHSA_LINK}, {CVE_LINK})" -def test_id_already_in_the_title_is_not_repeated(): +def test_id_already_in_the_title_is_linked_in_place_and_not_repeated(): alert = _alert({"ghsaId": GHSA, "cveId": CVE}, title=f"{CVE} in lodash") - assert Messages.alert_title_html(alert) == f"{CVE} in lodash ({GHSA_LINK})" + html = Messages.alert_title_html(alert) + + assert html == f"{CVE_LINK} in lodash ({GHSA_LINK})" + assert html.count(CVE) == 2 # the link target and its text, once + assert Messages.alert_title_with_advisory(alert) == f"{CVE} in lodash ({GHSA})" + + +def test_id_in_the_title_keeps_its_spelling_and_links_the_api_id(): + alert = _alert({"ghsaId": GHSA}, title=f"{GHSA.upper()}: prototype pollution") + + assert Messages.alert_title_html(alert) == ( + f'{GHSA.upper()}: prototype pollution' + ) + + +def test_title_is_escaped_around_an_id_linked_in_place(): + alert = _alert({"cveId": CVE}, title=f"{CVE} & more") + + assert Messages.alert_title_html(alert) == f"<b>{CVE_LINK}</b> & more" + + +def test_id_that_is_a_prefix_of_a_different_cve_in_the_title_is_still_linked(): + prefix_cve = "CVE-2021-2333" + alert = _alert({"cveId": prefix_cve}, title=f"{CVE} in lodash") + + assert Messages.alert_title_html(alert) == ( + f'{CVE} in lodash ({prefix_cve})' + ) + assert Messages.alert_title_with_advisory(alert) == f"{CVE} in lodash ({prefix_cve})" def test_unexpected_id_shape_is_escaped_text_not_a_link():