Skip to content

Commit 3b3ec62

Browse files
dc-larsenlelia
andauthored
Link advisory IDs in PR and MR security comments (#477)
* Check --branch and --commit-sha before marking a scan as the default branch Default-branch detection read only the CI variables. On GitHub Actions it compared GITHUB_REF to the repository's default branch and checked that the GITHUB_SHA commit is on it; --branch and --commit-sha were never consulted. A workflow_run job triggered by develop (the default branch) that checks out a release tag on main and passes --branch main --commit-sha <tag> was detected as a default-branch scan. The full scan was created with make_default_branch=true and set_as_pending_head=true, which moved the repository's default branch to main, and with develop's commit message. Without --scm, DEFAULT_BRANCH=false did not help, and nothing could turn --default-branch detection off. When --branch or --commit-sha names a different ref than the CI variables, the scan is no longer treated as the default branch unless that branch is the default branch and that commit is on it. A commit missing from the checkout cannot be checked, so it is not treated as the default branch either. The check can only turn detection off; --default-branch still marks a scan explicitly. The commit message and the committer fallback now come from the --commit-sha commit when the checkout has it. Changed-file detection still reads the CI variables. Add --no-default-branch, which forces make_default_branch and set_as_pending_head off whatever git or the CI environment says. It is mutually exclusive with --default-branch, on the command line and in a --config file. Set the version to 2.16.0. * Clear CI committer usernames in git interface tests GitHub Actions sets GITHUB_ACTOR, which get_formatted_committer prefers over the commit's committer, so the --commit-sha committer test failed in CI. * Apply the explicit-ref check to the combined default-branch detection With --scm github, the SCM adapter's is_default_branch was copied into config.default_branch, so DEFAULT_BRANCH=true restored default-branch status after git had rejected a mismatched --branch or --commit-sha. resolve_default_branch() now makes the decision in one place: --no-default-branch and --default-branch are authoritative, and otherwise the SCM and git detection results are combined before the explicit-ref check runs. Git.apply_explicit_ref() only records the named ref and switches the commit details; explicit_ref_allows_default_branch() does the check. Adds CLI-path tests with SCM detection enabled covering both outgoing flags, the explicit overrides, and the commit message and committer fallback. Sets the release to 2.16.0 and updates the CLI reference, README and CHANGELOG. * 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. * 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. * Compare --commit-sha with the commit CI names When the clone lacks the CI commit, Git falls back to HEAD. A --commit-sha naming that checkout then matched self.commit and was not treated as an explicit ref, so the reachability check never ran and DEFAULT_BRANCH=true with --scm github could still mark a scan of another ref as the default branch. Compare with the CI SHA when there is one. * Update tracked branch heads from full scans Full scans sent set_as_pending_head=is_default_branch, so only a default-branch scan could become a head. The API also makes a scan the head of a branch that matches the organization's tracked branch patterns (Settings > Alerts > Scans), but only when the request sets set_as_pending_head, and it ignores the flag on branches it doesn't track. Python CLI scans of a tracked branch were never that branch's head, so their findings never reached the organization Alerts page. Branch runs now send set_as_pending_head=true and let the API decide. make_default_branch is unchanged. A run counts as a pull or merge request when it has a PR number, when the SCM adapter selected the comparison flow, or when the CI environment describes a PR or MR event, so a PR run with --pr-number 0 stays out of the new path. A scan marked as the default branch, including one with an explicit --default-branch on a PR, still requests it as before, and --no-default-branch keeps it off. --pending-head stays a deprecated no-op. Its warning, the CLI reference, the README and the CHANGELOG describe the new behavior. Shares the 2.16.0 version set in #478. * Keep incomplete branch refs from falling back to the default branch --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent d71b14d commit 3b3ec62

7 files changed

Lines changed: 232 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
- Full scans of tracked branches can update branch heads, so findings from
1414
those branches can appear on the organization Alerts page after upgrade.
1515
Use `--no-default-branch` to opt a scan out.
16+
- PR and MR security comments link available GHSA and CVE IDs to their public
17+
advisory pages.
1618

1719
### Fixed
1820

‎socketsecurity/core/classes.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,27 @@ def advisory_id(self) -> str:
382382
return value.strip().upper()
383383
return ""
384384

385+
def advisory_ids(self) -> List[str]:
386+
"""Return distinct advisory IDs for display, using the API spelling and GHSA first."""
387+
props = getattr(self, "props", None) or {}
388+
ids: List[str] = []
389+
seen = set()
390+
for prop_name in ADVISORY_ID_PROPS:
391+
values = props.get(prop_name)
392+
if isinstance(values, str):
393+
values = [values]
394+
elif not isinstance(values, (list, tuple)):
395+
continue
396+
for value in values:
397+
if not isinstance(value, str) or not value.strip():
398+
continue
399+
value = value.strip()
400+
if value.upper() in seen:
401+
continue
402+
seen.add(value.upper())
403+
ids.append(value)
404+
return ids
405+
385406
def consolidation_key(self) -> Tuple[str, str, str, str]:
386407
"""Identity used to collapse repeat sightings of one finding into one alert.
387408

‎socketsecurity/core/messages.py‎

Lines changed: 77 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@
1313

1414
log = logging.getLogger("socketcli")
1515

16+
# Public advisory pages for the IDs shown in PR/MR comments, keyed by the ID's
17+
# canonical shape. The GitLab security report links the same two sites.
18+
ADVISORY_LINK_BASES = (
19+
(re.compile(r"^GHSA(-[0-9a-z]{4}){3}$", re.IGNORECASE), "https://github.com/advisories/"),
20+
(re.compile(r"^CVE-\d{4}-\d{4,}$", re.IGNORECASE), "https://nvd.nist.gov/vuln/detail/"),
21+
)
22+
1623
class Messages:
1724

1825
@staticmethod
@@ -1048,7 +1055,6 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10481055
package = f"{alert.package_name_with_namespace()}@{alert.pkg_version}"
10491056
pkg_label = Messages.html_text(package)
10501057
pkg_marker = Messages.alert_package_marker(alert, package)
1051-
alert_title = Messages.alert_title_with_advisory(alert)
10521058
ignore_html = (
10531059
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
10541060
f"<code>@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}</code><br/>"
@@ -1064,7 +1070,7 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10641070
</td>
10651071
<td>
10661072
<details {details_open}>
1067-
<summary>{pkg_label} - {Messages.html_text(alert_title)}</summary>
1073+
<summary>{pkg_label} - {Messages.alert_title_html(alert)}</summary>
10681074
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
10691075
{patched_version_html}
10701076
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
@@ -1082,19 +1088,84 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10821088
<!-- end-socket-alert-{pkg_marker} -->
10831089
"""
10841090

1091+
@staticmethod
1092+
def _advisory_id_pattern(ids) -> "re.Pattern[str]":
1093+
"""Matches any of the IDs in full, so CVE-2021-2333 does not match inside CVE-2021-23337."""
1094+
alternatives = "|".join(re.escape(advisory) for advisory in sorted(ids, key=len, reverse=True))
1095+
return re.compile(rf"(?<![\w-])(?:{alternatives})(?![\w-])", re.IGNORECASE)
1096+
1097+
@staticmethod
1098+
def advisory_ids_for_title(alert: Issue) -> list:
1099+
"""The alert's GHSA and CVE IDs, GHSA first, minus any its title already names."""
1100+
title = getattr(alert, "title", "") or ""
1101+
ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else []
1102+
return [
1103+
advisory for advisory in ids
1104+
if not Messages._advisory_id_pattern([advisory]).search(title)
1105+
]
1106+
10851107
@staticmethod
10861108
def alert_title_with_advisory(alert: Issue) -> str:
1087-
"""The alert title, followed by its GHSA or CVE ID when it has one.
1109+
"""The alert title, followed by its GHSA and CVE IDs when it has them.
10881110
10891111
Every CVE of one severity shares a title ("Critical CVE"), so without the
10901112
ID two advisories on the same package render as identical rows.
10911113
"""
10921114
title = getattr(alert, "title", "") or ""
1093-
advisory = alert.advisory_id() if hasattr(alert, "advisory_id") else ""
1094-
if advisory and advisory not in title.upper():
1095-
return f"{title} ({advisory})"
1115+
ids = Messages.advisory_ids_for_title(alert)
1116+
if ids:
1117+
return f"{title} ({', '.join(ids)})"
10961118
return title
10971119

1120+
@staticmethod
1121+
def _advisory_link_base(advisory: str) -> str | None:
1122+
for pattern, base_url in ADVISORY_LINK_BASES:
1123+
if pattern.match(advisory):
1124+
return base_url
1125+
return None
1126+
1127+
@staticmethod
1128+
def advisory_link_html(advisory: str, label_html: str | None = None) -> str:
1129+
"""An advisory ID linked to its public advisory page.
1130+
1131+
Only IDs in the canonical GHSA or CVE shape are linked, so an unexpected
1132+
value renders as escaped text instead of an arbitrary URL path.
1133+
"""
1134+
label = Messages.html_text(advisory) if label_html is None else label_html
1135+
base_url = Messages._advisory_link_base(advisory)
1136+
if base_url is None:
1137+
return label
1138+
return f'<a href="{Messages.html_attr(base_url + advisory)}">{label}</a>'
1139+
1140+
@staticmethod
1141+
def alert_title_html(alert: Issue) -> str:
1142+
"""The PR/MR comment row title as HTML.
1143+
1144+
The title is escaped. The alert's GHSA and CVE IDs are linked in place where
1145+
the title names them in full, and the remaining IDs follow once, linked, in
1146+
parentheses. Only canonical GHSA and CVE IDs become links.
1147+
"""
1148+
title_html = Messages.html_text(getattr(alert, "title", "") or "")
1149+
ids = alert.advisory_ids() if hasattr(alert, "advisory_ids") else []
1150+
remaining = Messages.advisory_ids_for_title(alert)
1151+
# Canonical IDs are letters, digits and hyphens, which escaping leaves alone.
1152+
in_title = {
1153+
advisory.upper(): advisory
1154+
for advisory in ids
1155+
if advisory not in remaining and Messages._advisory_link_base(advisory)
1156+
}
1157+
if in_title:
1158+
title_html = Messages._advisory_id_pattern(in_title.values()).sub(
1159+
lambda match: Messages.advisory_link_html(
1160+
in_title[match.group(0).upper()], match.group(0)
1161+
),
1162+
title_html,
1163+
)
1164+
if not remaining:
1165+
return title_html
1166+
links = ", ".join(Messages.advisory_link_html(advisory) for advisory in remaining)
1167+
return f"{title_html} ({links})"
1168+
10981169
@staticmethod
10991170
def security_comment_template(diff: Diff, config=None) -> str:
11001171
"""Render the PR/MR security comment within the provider's size limit."""

‎tests/core/test_alert_consolidation.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,8 @@ def test_pr_comment_rows_name_the_advisory():
133133

134134
comment = Messages.security_comment_template(diff)
135135

136-
assert "Critical CVE (GHSA-AAAA-AAAA-AAAA)" in comment
137-
assert "Critical CVE (GHSA-BBBB-BBBB-BBBB)" in comment
136+
assert 'Critical CVE (<a href="https://github.com/advisories/GHSA-aaaa-aaaa-aaaa">GHSA-aaaa-aaaa-aaaa</a>)' in comment
137+
assert 'Critical CVE (<a href="https://github.com/advisories/GHSA-bbbb-bbbb-bbbb">GHSA-bbbb-bbbb-bbbb</a>)' in comment
138138

139139

140140
def test_title_already_naming_the_advisory_is_left_alone():

‎tests/core/test_existing_alerts.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ def test_every_same_severity_advisory_on_an_unchanged_package_is_kept(core, capl
454454
comment = Messages.security_comment_template(diff, _config())
455455
assert "Existing alerts (6)" in comment
456456
for ghsa, _ in HANDLEBARS_CRITICAL_ADVISORIES:
457-
assert ghsa.upper() in comment
457+
assert f'<a href="https://github.com/advisories/{ghsa}">{ghsa}</a>' in comment
458458

459459

460460
@pytest.mark.parametrize("triaged_action", ["ignore", "monitor"])

‎tests/core/test_strict_blocking_no_manifest_change.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,9 +269,9 @@ def test_code_only_scan_with_pr_context_comments_on_each_existing_blocker(
269269
security_comment, _, _, post_security, _ = github_pull_request.call_args.args
270270
assert post_security is True
271271
assert "Existing alerts (2)" in security_comment
272-
assert resolved[0].upper() not in security_comment
272+
assert resolved[0].upper() not in security_comment.upper()
273273
for ghsa, _ in blocking:
274-
assert ghsa.upper() in security_comment
274+
assert f'<a href="https://github.com/advisories/{ghsa}">{ghsa}</a>' in security_comment
275275

276276

277277
@pytest.mark.parametrize("policy, infrastructure_code", POLICIES)
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""PR/MR comment rows link every GHSA and CVE ID on an alert.
2+
3+
Developers who only see the PR comment need the advisory itself. Socket CVE
4+
alerts usually carry both a GHSA and a CVE ID, and either can be published
5+
first, so the row names both and links the GHSA to GitHub and the CVE to NVD.
6+
The single advisory_id() used for de-duplication stays unchanged.
7+
"""
8+
from socketsecurity.core.classes import Diff, Issue
9+
from socketsecurity.core.messages import Messages
10+
11+
GHSA = "GHSA-35jh-r3h4-6jhm"
12+
CVE = "CVE-2021-23337"
13+
GHSA_LINK = f'<a href="https://github.com/advisories/{GHSA}">{GHSA}</a>'
14+
CVE_LINK = f'<a href="https://nvd.nist.gov/vuln/detail/{CVE}">{CVE}</a>'
15+
16+
17+
def _alert(props, title="Critical CVE"):
18+
return Issue(
19+
pkg_type="npm",
20+
pkg_name="lodash",
21+
pkg_version="4.17.20",
22+
purl="lodash@4.17.20",
23+
type="criticalCVE",
24+
severity="critical",
25+
title=title,
26+
description="A vulnerability.",
27+
suggestion="Upgrade.",
28+
url="https://socket.dev/npm/package/lodash/overview/4.17.20",
29+
key="k1",
30+
props=props,
31+
error=True,
32+
)
33+
34+
35+
def _comment(alert):
36+
diff = Diff()
37+
diff.new_alerts = [alert]
38+
diff.diff_url = "https://socket.dev/diff"
39+
diff.report_url = "https://socket.dev/report"
40+
return Messages.security_comment_template(diff)
41+
42+
43+
def test_alert_with_both_ids_shows_both_linked_ghsa_first():
44+
comment = _comment(_alert({"ghsaId": GHSA, "cveId": CVE}))
45+
46+
assert f"Critical CVE ({GHSA_LINK}, {CVE_LINK})" in comment
47+
48+
49+
def test_ghsa_only_alert_links_the_ghsa():
50+
assert Messages.alert_title_html(_alert({"ghsaId": GHSA})) == f"Critical CVE ({GHSA_LINK})"
51+
52+
53+
def test_cve_only_alert_links_the_cve():
54+
assert Messages.alert_title_html(_alert({"cveId": CVE})) == f"Critical CVE ({CVE_LINK})"
55+
56+
57+
def test_older_and_snake_case_spellings_are_read_and_deduplicated():
58+
alert = _alert({"ghsa_id": GHSA, "cve_id": [CVE, CVE.lower()], "cve": CVE})
59+
60+
assert alert.advisory_ids() == [GHSA, CVE]
61+
assert Messages.alert_title_html(alert) == f"Critical CVE ({GHSA_LINK}, {CVE_LINK})"
62+
63+
64+
def test_id_already_in_the_title_is_linked_in_place_and_not_repeated():
65+
alert = _alert({"ghsaId": GHSA, "cveId": CVE}, title=f"{CVE} in lodash")
66+
67+
html = Messages.alert_title_html(alert)
68+
69+
assert html == f"{CVE_LINK} in lodash ({GHSA_LINK})"
70+
assert html.count(CVE) == 2 # the link target and its text, once
71+
assert Messages.alert_title_with_advisory(alert) == f"{CVE} in lodash ({GHSA})"
72+
73+
74+
def test_id_in_the_title_keeps_its_spelling_and_links_the_api_id():
75+
alert = _alert({"ghsaId": GHSA}, title=f"{GHSA.upper()}: prototype pollution")
76+
77+
assert Messages.alert_title_html(alert) == (
78+
f'<a href="https://github.com/advisories/{GHSA}">{GHSA.upper()}</a>: prototype pollution'
79+
)
80+
81+
82+
def test_title_is_escaped_around_an_id_linked_in_place():
83+
alert = _alert({"cveId": CVE}, title=f"<b>{CVE}</b> & more")
84+
85+
assert Messages.alert_title_html(alert) == f"&lt;b&gt;{CVE_LINK}&lt;/b&gt; &amp; more"
86+
87+
88+
def test_id_that_is_a_prefix_of_a_different_cve_in_the_title_is_still_linked():
89+
prefix_cve = "CVE-2021-2333"
90+
alert = _alert({"cveId": prefix_cve}, title=f"{CVE} in lodash")
91+
92+
assert Messages.alert_title_html(alert) == (
93+
f'{CVE} in lodash (<a href="https://nvd.nist.gov/vuln/detail/{prefix_cve}">{prefix_cve}</a>)'
94+
)
95+
assert Messages.alert_title_with_advisory(alert) == f"{CVE} in lodash ({prefix_cve})"
96+
97+
98+
def test_unexpected_id_shape_is_escaped_text_not_a_link():
99+
alert = _alert({"ghsaId": 'GHSA-"><img src=x>', "cveId": CVE})
100+
101+
html = Messages.alert_title_html(alert)
102+
103+
assert "<img" not in html
104+
assert "&lt;img src=x&gt;" in html
105+
assert html.endswith(f", {CVE_LINK})")
106+
assert html.count("<a ") == 1
107+
108+
109+
def test_alert_without_advisory_ids_keeps_its_title():
110+
alert = _alert({}, title="Known malware")
111+
112+
assert Messages.alert_title_html(alert) == "Known malware"
113+
assert Messages.alert_title_with_advisory(alert) == "Known malware"
114+
115+
116+
def test_plain_text_title_lists_both_ids():
117+
alert = _alert({"ghsaId": GHSA, "cveId": CVE})
118+
119+
assert Messages.alert_title_with_advisory(alert) == f"Critical CVE ({GHSA}, {CVE})"
120+
121+
122+
def test_deduplication_key_still_uses_one_id():
123+
with_cve = _alert({"ghsaId": GHSA, "cveId": CVE})
124+
without_cve = _alert({"ghsaId": GHSA})
125+
126+
assert with_cve.advisory_id() == GHSA.upper()
127+
assert with_cve.consolidation_key() == without_cve.consolidation_key()

0 commit comments

Comments
 (0)