Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -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__}'
26 changes: 26 additions & 0 deletions socketsecurity/core/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
83 changes: 77 additions & 6 deletions socketsecurity/core/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
f"<code>@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}</code><br/>"
Expand All @@ -1064,7 +1070,7 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
</td>
<td>
<details {details_open}>
<summary>{pkg_label} - {Messages.html_text(alert_title)}</summary>
<summary>{pkg_label} - {Messages.alert_title_html(alert)}</summary>
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
{patched_version_html}
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
Expand All @@ -1082,19 +1088,84 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
<!-- end-socket-alert-{pkg_marker} -->
"""

@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"(?<![\w-])(?:{alternatives})(?![\w-])", re.IGNORECASE)

@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 ""
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'<a href="{Messages.html_attr(base_url + advisory)}">{label}</a>'

@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."""
Expand Down
4 changes: 2 additions & 2 deletions tests/core/test_alert_consolidation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<a href="https://github.com/advisories/GHSA-aaaa-aaaa-aaaa">GHSA-aaaa-aaaa-aaaa</a>)' in comment
assert 'Critical CVE (<a href="https://github.com/advisories/GHSA-bbbb-bbbb-bbbb">GHSA-bbbb-bbbb-bbbb</a>)' in comment


def test_title_already_naming_the_advisory_is_left_alone():
Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_existing_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'<a href="https://github.com/advisories/{ghsa}">{ghsa}</a>' in comment


@pytest.mark.parametrize("triaged_action", ["ignore", "monitor"])
Expand Down
4 changes: 2 additions & 2 deletions tests/core/test_strict_blocking_no_manifest_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'<a href="https://github.com/advisories/{ghsa}">{ghsa}</a>' in security_comment


@pytest.mark.parametrize("policy, infrastructure_code", POLICIES)
Expand Down
127 changes: 127 additions & 0 deletions tests/unit/test_comment_advisory_links.py
Original file line number Diff line number Diff line change
@@ -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'<a href="https://github.com/advisories/{GHSA}">{GHSA}</a>'
CVE_LINK = f'<a href="https://nvd.nist.gov/vuln/detail/{CVE}">{CVE}</a>'


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'<a href="https://github.com/advisories/{GHSA}">{GHSA.upper()}</a>: prototype pollution'
)


def test_title_is_escaped_around_an_id_linked_in_place():
alert = _alert({"cveId": CVE}, title=f"<b>{CVE}</b> & more")

assert Messages.alert_title_html(alert) == f"&lt;b&gt;{CVE_LINK}&lt;/b&gt; &amp; 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 (<a href="https://nvd.nist.gov/vuln/detail/{prefix_cve}">{prefix_cve}</a>)'
)
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-"><img src=x>', "cveId": CVE})

html = Messages.alert_title_html(alert)

assert "<img" not in html
assert "&lt;img src=x&gt;" in html
assert html.endswith(f", {CVE_LINK})")
assert html.count("<a ") == 1


def test_alert_without_advisory_ids_keeps_its_title():
alert = _alert({}, title="Known malware")

assert Messages.alert_title_html(alert) == "Known malware"
assert Messages.alert_title_with_advisory(alert) == "Known malware"


def test_plain_text_title_lists_both_ids():
alert = _alert({"ghsaId": GHSA, "cveId": CVE})

assert Messages.alert_title_with_advisory(alert) == f"Critical CVE ({GHSA}, {CVE})"


def test_deduplication_key_still_uses_one_id():
with_cve = _alert({"ghsaId": GHSA, "cveId": CVE})
without_cve = _alert({"ghsaId": GHSA})

assert with_cve.advisory_id() == GHSA.upper()
assert with_cve.consolidation_key() == without_cve.consolidation_key()
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.