Skip to content

Commit 3274b99

Browse files
committed
Report existing alerts from the full scan, and list them in the PR comment
The cached diff-scans endpoint returns unchanged artifacts with no alerts, so --strict-blocking had nothing to block on and passed runs with blocking alerts on packages the change didn't touch. The GitLab security report and FOSSA-format output, which list every current finding, missed the same alerts. When one of those outputs is enabled, the CLI now reads the alerts on unchanged packages from the new full scan. It skips that request when the comparison already carries them, as the streaming fallback does, and fails the run if the request fails rather than reporting no existing alerts. Under --strict-blocking the PR comment lists existing alerts in their own table after the new ones, blocking first, and stops adding rows before the comment reaches GitHub's size limit. Ignore comments apply to existing alerts too, since they now fail the run and each row offers the command.
1 parent c769f2b commit 3274b99

4 files changed

Lines changed: 511 additions & 50 deletions

File tree

‎socketsecurity/core/__init__.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2494,6 +2494,8 @@ def create_new_diff(
24942494
)
24952495

24962496
unchanged_packages = Core.get_unchanged_packages(packages, added_packages, removed_packages)
2497+
if unchanged_packages and self._requires_unchanged_alerts():
2498+
self.add_existing_alerts_from_full_scan(unchanged_packages, new_full_scan.id)
24972499

24982500
diff = self.create_diff_report(added_packages, removed_packages, unchanged_packages)
24992501
diff.packages = packages
@@ -2518,6 +2520,86 @@ def create_new_diff(
25182520

25192521
return diff
25202522

2523+
def _requires_unchanged_alerts(self) -> bool:
2524+
"""Whether an enabled output reads alerts on unchanged packages.
2525+
2526+
``--strict-blocking`` fails the run on them, and the GitLab security report
2527+
and FOSSA-format output list every current finding, not only new ones.
2528+
A subset of _requires_unchanged_artifacts.
2529+
"""
2530+
config = self.cli_config
2531+
if config is None:
2532+
return False
2533+
return bool(
2534+
getattr(config, "strict_blocking", False)
2535+
or getattr(config, "enable_gitlab_security", False)
2536+
or getattr(config, "legal_format", "socket") == "fossa"
2537+
)
2538+
2539+
def add_existing_alerts_from_full_scan(
2540+
self, unchanged_packages: Dict[str, Package], full_scan_id: str
2541+
) -> None:
2542+
"""Fill in the alerts on unchanged packages from the new full scan.
2543+
2544+
The cached diff-scans endpoint returns unchanged artifacts with an empty
2545+
``alerts`` list, because it keeps only the alerts it counts as new. The full
2546+
scan of the same commit carries every package's alerts with their policy
2547+
actions, so they are read from there. Packages are matched by artifact ID,
2548+
then by ecosystem, namespace, name and version.
2549+
2550+
Skipped when any unchanged package already has alerts: the comparison then
2551+
came from an endpoint that includes them, such as the streaming fallback.
2552+
A failed fetch raises, because reporting existing alerts as absent would
2553+
let ``--strict-blocking`` pass a run it should fail.
2554+
"""
2555+
if any(package.alerts for package in unchanged_packages.values()):
2556+
log.debug("The comparison already includes alerts on unchanged packages")
2557+
return
2558+
2559+
start = time.time()
2560+
by_id: Dict[str, List[dict]] = {}
2561+
by_identity: Dict[Tuple[str, str, str, str], List[dict]] = {}
2562+
for artifact in self.get_sbom_data(full_scan_id).values():
2563+
data = asdict(artifact)
2564+
alerts = data.get("alerts") or []
2565+
by_id[data["id"]] = alerts
2566+
by_identity[Core._package_identity(
2567+
data["type"], data.get("namespace"), data["name"], data["version"]
2568+
)] = alerts
2569+
2570+
matched = 0
2571+
alert_count = 0
2572+
for package in unchanged_packages.values():
2573+
alerts = by_id.get(package.id)
2574+
if alerts is None:
2575+
alerts = by_identity.get(Core._package_identity(
2576+
package.type, package.namespace, package.name, package.version
2577+
))
2578+
if alerts is None:
2579+
continue
2580+
package.alerts = alerts
2581+
matched += 1
2582+
alert_count += len(alerts)
2583+
2584+
log.info(
2585+
f"Loaded {alert_count} alerts for {matched} of {len(unchanged_packages)} "
2586+
f"unchanged packages from full scan {full_scan_id} in {time.time() - start:.2f}s"
2587+
)
2588+
if matched < len(unchanged_packages):
2589+
log.warning(
2590+
f"{len(unchanged_packages) - matched} unchanged packages were not found in "
2591+
f"full scan {full_scan_id}, so their existing alerts are not reported"
2592+
)
2593+
2594+
@staticmethod
2595+
def _package_identity(package_type, namespace, name, version) -> Tuple[str, str, str, str]:
2596+
return (
2597+
str(Package.normalize_type(package_type) or ""),
2598+
(namespace or "").strip("/"),
2599+
name or "",
2600+
version or "",
2601+
)
2602+
25212603
@staticmethod
25222604
def get_unchanged_packages(
25232605
packages: Dict[str, Package],

‎socketsecurity/core/messages.py‎

Lines changed: 128 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,57 @@ def get_view_report_url(diff: Diff) -> str:
925925
return diff.report_url
926926
return ""
927927

928+
@staticmethod
929+
def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> str:
930+
"""One row of the security comment table for a non-license alert."""
931+
severity_icon = Messages.get_severity_icon(alert.severity)
932+
action = "Block" if alert.error else "Warn"
933+
details_open = ""
934+
patched_version = Messages.get_patched_version(alert)
935+
patched_version_html = (
936+
"<p><strong>Patched version:</strong> "
937+
f"<code>{Messages.html_text(patched_version)}</code></p>"
938+
if patched_version else ""
939+
)
940+
# Generate proper manifest URL
941+
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
942+
pkg_label = Messages.html_text(f"{alert.pkg_name}@{alert.pkg_version}")
943+
pkg_marker = Messages.comment_marker_text(f"{alert.pkg_name}@{alert.pkg_version}")
944+
alert_title = Messages.alert_title_with_advisory(alert)
945+
# Generate a table row for each alert
946+
ignore_html = (
947+
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
948+
f"<code>@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}</code><br/>"
949+
f"Or ignore all future alerts with:<br/>"
950+
f"<code>@SocketSecurity ignore-all</code></p>"
951+
) if show_ignore else ""
952+
return f"""
953+
<!-- start-socket-alert-{pkg_marker} -->
954+
<tr>
955+
<td><strong>{action}</strong></td>
956+
<td align="center">
957+
<img src="{severity_icon}" alt="{Messages.html_attr(alert.severity)}" width="20" height="20">
958+
</td>
959+
<td>
960+
<details {details_open}>
961+
<summary>{pkg_label} - {Messages.html_text(alert_title)}</summary>
962+
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
963+
{patched_version_html}
964+
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
965+
<p>ℹ️ Read more on:
966+
<a href="{Messages.html_attr(alert.purl)}">This package</a> |
967+
<a href="{Messages.html_attr(alert.url)}">This alert</a> |
968+
<a href="https://socket.dev/alerts/malware">What is known malware?</a></p>
969+
<blockquote>
970+
<p><em>Suggestion:</em> {Messages.html_text(alert.suggestion)}</p>
971+
{ignore_html}
972+
</blockquote>
973+
</details>
974+
</td>
975+
</tr>
976+
<!-- end-socket-alert-{pkg_marker} -->
977+
"""
978+
928979
@staticmethod
929980
def alert_title_with_advisory(alert: Issue) -> str:
930981
"""The alert title, followed by its GHSA or CVE ID when it has one.
@@ -962,10 +1013,11 @@ def security_comment_template(diff: Diff, config=None) -> str:
9621013
security_alerts.append(alert)
9631014

9641015
view_report_url = Messages.get_view_report_url(diff)
1016+
existing_alerts = Messages.existing_comment_alerts(diff, config)
9651017

9661018
# Without this the caution banner would sit above a table with no rows,
9671019
# which is how a comment looks once every alert it raised is resolved.
968-
if not security_alerts and not license_groups:
1020+
if not security_alerts and not license_groups and not existing_alerts:
9691021
return Messages.security_comment_no_alerts_template(view_report_url)
9701022

9711023
# Start of the comment
@@ -993,53 +1045,7 @@ def security_comment_template(diff: Diff, config=None) -> str:
9931045

9941046
# Loop through security alerts (non-license), dynamically generating rows
9951047
for alert in security_alerts:
996-
severity_icon = Messages.get_severity_icon(alert.severity)
997-
action = "Block" if alert.error else "Warn"
998-
details_open = ""
999-
patched_version = Messages.get_patched_version(alert)
1000-
patched_version_html = (
1001-
"<p><strong>Patched version:</strong> "
1002-
f"<code>{Messages.html_text(patched_version)}</code></p>"
1003-
if patched_version else ""
1004-
)
1005-
# Generate proper manifest URL
1006-
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
1007-
pkg_label = Messages.html_text(f"{alert.pkg_name}@{alert.pkg_version}")
1008-
pkg_marker = Messages.comment_marker_text(f"{alert.pkg_name}@{alert.pkg_version}")
1009-
alert_title = Messages.alert_title_with_advisory(alert)
1010-
# Generate a table row for each alert
1011-
ignore_html = (
1012-
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
1013-
f"<code>@SocketSecurity ignore {Messages.html_text(alert.pkg_type)}/{pkg_label}</code><br/>"
1014-
f"Or ignore all future alerts with:<br/>"
1015-
f"<code>@SocketSecurity ignore-all</code></p>"
1016-
) if show_ignore else ""
1017-
comment += f"""
1018-
<!-- start-socket-alert-{pkg_marker} -->
1019-
<tr>
1020-
<td><strong>{action}</strong></td>
1021-
<td align="center">
1022-
<img src="{severity_icon}" alt="{Messages.html_attr(alert.severity)}" width="20" height="20">
1023-
</td>
1024-
<td>
1025-
<details {details_open}>
1026-
<summary>{pkg_label} - {Messages.html_text(alert_title)}</summary>
1027-
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
1028-
{patched_version_html}
1029-
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
1030-
<p>ℹ️ Read more on:
1031-
<a href="{Messages.html_attr(alert.purl)}">This package</a> |
1032-
<a href="{Messages.html_attr(alert.url)}">This alert</a> |
1033-
<a href="https://socket.dev/alerts/malware">What is known malware?</a></p>
1034-
<blockquote>
1035-
<p><em>Suggestion:</em> {Messages.html_text(alert.suggestion)}</p>
1036-
{ignore_html}
1037-
</blockquote>
1038-
</details>
1039-
</td>
1040-
</tr>
1041-
<!-- end-socket-alert-{pkg_marker} -->
1042-
"""
1048+
comment += Messages.security_alert_row(alert, diff, config, show_ignore)
10431049

10441050
# Add license policy violation entries grouped by PURL
10451051
for purl_key, alerts in license_groups.items():
@@ -1099,17 +1105,90 @@ def security_comment_template(diff: Diff, config=None) -> str:
10991105
<!-- end-socket-alert-{license_marker} -->
11001106
"""
11011107

1108+
if not security_alerts and not license_groups:
1109+
comment += """
1110+
<tr>
1111+
<td colspan="3">No new alerts in this change.</td>
1112+
</tr>
1113+
"""
1114+
11021115
# Close table
1103-
comment += f"""
1116+
comment += """
11041117
</tbody>
11051118
</table>
11061119
<!-- end-socket-alerts-table -->
1120+
"""
1121+
if existing_alerts:
1122+
comment += Messages.existing_alerts_section(
1123+
existing_alerts, diff, config, show_ignore, view_report_url, len(comment)
1124+
)
11071125

1126+
comment += f"""
11081127
[View full report]({view_report_url}?action=error%2Cwarn)
11091128
"""
11101129

11111130
return Messages.normalize_comment_html(comment)
11121131

1132+
# GitHub rejects comment bodies over 65,536 characters. The existing-alerts
1133+
# section is the open-ended part of the security comment, so it stops adding
1134+
# rows at this size and links to the full report for the rest.
1135+
SECURITY_COMMENT_SIZE_BUDGET = 60000
1136+
1137+
@staticmethod
1138+
def existing_comment_alerts(diff: Diff, config) -> list:
1139+
"""Alerts on unchanged packages to show in the PR comment.
1140+
1141+
Only under --strict-blocking, where they fail the run: without it they
1142+
don't affect the result, and listing them would bury the new ones.
1143+
"""
1144+
if not (config and getattr(config, "strict_blocking", False)):
1145+
return []
1146+
new_keys = {alert.consolidation_key() for alert in getattr(diff, "new_alerts", []) or []}
1147+
return [
1148+
alert for alert in getattr(diff, "unchanged_alerts", []) or []
1149+
if (alert.error or alert.warn) and alert.consolidation_key() not in new_keys
1150+
]
1151+
1152+
@staticmethod
1153+
def existing_alerts_section(
1154+
alerts: list, diff: Diff, config, show_ignore: bool, view_report_url: str, size_so_far: int
1155+
) -> str:
1156+
"""Table of alerts on packages this change didn't touch, blocking ones first."""
1157+
ordered = sorted(alerts, key=lambda alert: not alert.error)
1158+
blocking = sum(1 for alert in ordered if alert.error)
1159+
section = f"""
1160+
<!-- start-socket-existing-alerts -->
1161+
**Existing alerts ({len(ordered)}).** These are on dependencies this change didn't add or update. `--strict-blocking` fails the run on the {blocking} with a **Block** action.
1162+
1163+
<table>
1164+
<thead>
1165+
<tr>
1166+
<th>Action</th>
1167+
<th>Severity</th>
1168+
<th align="left">Alert (click for details)</th>
1169+
</tr>
1170+
</thead>
1171+
<tbody>
1172+
"""
1173+
closing = """
1174+
</tbody>
1175+
</table>
1176+
"""
1177+
shown = 0
1178+
for alert in ordered:
1179+
row = Messages.security_alert_row(alert, diff, config, show_ignore)
1180+
if size_so_far + len(section) + len(row) + len(closing) > Messages.SECURITY_COMMENT_SIZE_BUDGET:
1181+
break
1182+
section += row
1183+
shown += 1
1184+
section += closing
1185+
if shown < len(ordered):
1186+
section += (
1187+
f"\n{len(ordered) - shown} more existing alert(s) are not shown here to keep "
1188+
f"this comment within GitHub's size limit. See the [full report]({view_report_url}?action=error%2Cwarn).\n"
1189+
)
1190+
return section + "<!-- end-socket-existing-alerts -->\n"
1191+
11131192
@staticmethod
11141193
def get_severity_icon(severity: str) -> str:
11151194
"""

‎socketsecurity/socketcli.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,13 @@ def _is_unprocessed(c):
875875
diff.new_alerts = Comments.remove_alerts(comments, diff.new_alerts)
876876

877877
ignored_alerts = [a for a in alerts_before if a not in diff.new_alerts]
878+
# Under --strict-blocking, existing alerts fail the run and appear in
879+
# the comment with the same ignore instructions, so an ignore has to
880+
# apply to them as well.
881+
if config.strict_blocking and diff.unchanged_alerts:
882+
existing_before = list(diff.unchanged_alerts)
883+
diff.unchanged_alerts = Comments.remove_alerts(comments, diff.unchanged_alerts)
884+
ignored_alerts += [a for a in existing_before if a not in diff.unchanged_alerts]
878885
# Emit telemetry per-comment so each event carries the comment author.
879886
unprocessed_ignore = [
880887
c for c in comments.get("ignore", [])
@@ -957,7 +964,7 @@ def _is_unprocessed(c):
957964

958965
new_security_comment = should_write_comment(
959966
config.disable_security_issue,
960-
len(diff.new_alerts) > 0,
967+
len(diff.new_alerts) > 0 or bool(Messages.existing_comment_alerts(diff, config)),
961968
update_old_security_comment,
962969
)
963970
if not new_security_comment:

0 commit comments

Comments
 (0)