diff --git a/CHANGELOG.md b/CHANGELOG.md index cf2f3aa..84ab518 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 7452ff6..c15612d 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 22abed1..b81e67e 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 bdea4b4..553662f 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 3b475de..960ca4e 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
Note: {Messages.html_text(alert.description)}
{patched_version_html}Source: Manifest File
@@ -1082,19 +1088,84 @@ 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 "" + ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else [] + return [ + advisory for advisory in ids + if not Messages._advisory_id_pattern([advisory]).search(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_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. + """ + 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 as HTML. + + 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_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: """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 e0a7d33..bbca9d8 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 d184c6c..ae82743 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 d2ab41b..95b9a81 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 0000000..33d50f4 --- /dev/null +++ b/tests/unit/test_comment_advisory_links.py @@ -0,0 +1,127 @@ +"""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 +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_linked_in_place_and_not_repeated(): + alert = _alert({"ghsaId": GHSA, "cveId": CVE}, title=f"{CVE} in lodash") + + 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(): + alert = _alert({"ghsaId": 'GHSA-">