Skip to content

Commit b3dc63f

Browse files
dc-larsenlelia
andauthored
Fix package links in PR and MR security comments (#465)
* Link "This package" in PR comments to the package page Each security comment row linked "This package" to the bare package coordinate (alert.purl, e.g. handlebars@4.0.11), so GitHub and GitLab resolved it as a relative link to a page that does not exist. The alert rows have done this since the HTML comment template was introduced, and license rows since they were added; the --strict-blocking existing-alerts table reuses both templates. Both rows now use alert.url, the package overview URL that Package.socket_url builds with the namespace (npm scope, Maven groupId, Go module path). The Markdown, Slack and Jira outputs already link the package with that URL. * Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. * Keep scoped package ignores precise Include the package namespace in comment rows and generated ignore commands. Match qualified commands in both scan results and comment updates, while continuing to honor existing bare-name commands. * Preserve alert order when truncating PR comments * Don't claim existing alerts fail the run under --disable-blocking * Note the report-only wording fix in the changelog --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent ef54e69 commit b3dc63f

11 files changed

Lines changed: 530 additions & 144 deletions

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,14 @@
4141
review run the PR scan.
4242
- GitHub pull request comment runs exit `0` and leave the Socket security
4343
comment unchanged when there are no Socket ignore commands to process.
44+
- Under `--strict-blocking --disable-blocking`, the PR/MR comment and console
45+
summary no longer say that existing Block alerts fail the run.
46+
- The "This package" link in GitHub and GitLab security comments opens the
47+
affected package version on socket.dev. License findings for different
48+
namespaces appear in separate rows, and generated ignore commands identify
49+
the package by its scope or namespace.
50+
- Large PR/MR security comments fit within GitHub's size limit and show how many
51+
new or existing findings were omitted. Policy checks and reports use all findings.
4452

4553
### Documentation
4654

‎docs/cli-reference.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -664,7 +664,16 @@ Security issues detected by Socket Security:
664664
- **With `--reach`**. With no explicit baseline, the CLI looks for a default-branch head scan with reachability enabled. If none exists, the CLI compares against an empty baseline and classifies all findings as new. Scan the default branch with `--reach` too.
665665
- **Policy actions**. Warn findings are reported. If the same finding has both Warn and Block actions, Block takes precedence.
666666
- **Existing alerts come from the full scan**. The CLI fetches the current full scan when the comparison leaves out alerts on unchanged packages or when a dependency version changes. A failed fetch or a missing package in that response triggers the infrastructure-error exit code.
667-
- **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first, with license violations grouped per package. `@SocketSecurity ignore` applies to them too. Very large sets are cut off before the comment reaches GitHub's size limit, with a link to the full report. Ignoring every displayed alert preserves the warning about omitted findings; `ignore-all` also clears omitted findings.
667+
- **PR/MR comments**. The comment lists new alerts first, then existing alerts
668+
with Block findings first in the existing-alerts table. License findings are
669+
grouped by package, including its scope or namespace. **This package** opens
670+
the affected version on socket.dev. Use the generated `@SocketSecurity ignore`
671+
command to target the package's exact scope or namespace.
672+
- **Comment size**. Large comments show how many new and existing alerts were
673+
omitted to fit GitHub's size limit and link to the full report.
674+
Policy checks and reports still use all findings. If you ignore every visible
675+
alert, the comment keeps the omission notice. Use `@SocketSecurity ignore-all`
676+
to clear all findings, including omitted ones.
668677
- **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass.
669678
- **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode.
670679

‎socketsecurity/core/classes.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,13 @@ def __init__(self, **kwargs):
359359
if not hasattr(self, "ignore"):
360360
self.ignore = False
361361

362+
def package_name_with_namespace(self) -> str:
363+
"""Read the name from the CLI's `[namespace/]name@version` coordinate."""
364+
name, _, _ = (getattr(self, "purl", "") or "").rpartition("@")
365+
if name and not name.startswith("pkg:"):
366+
return name
367+
return self.pkg_name
368+
362369
def advisory_id(self) -> str:
363370
"""The preferred GHSA or CVE identifier, upper-cased, or "".
364371

‎socketsecurity/core/messages.py‎

Lines changed: 118 additions & 111 deletions
Large diffs are not rendered by default.

‎socketsecurity/core/scm_comments.py‎

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def remove_alerts(comments: dict, new_alerts: list) -> list:
4545
break
4646
else:
4747
if any(
48-
Comments.is_ignore(alert.pkg_name, alert.pkg_version, name, version, alert.pkg_type)
48+
Comments.matches_issue(alert, name, version)
4949
for name, version in ignore_commands
5050
):
5151
log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored")
@@ -83,6 +83,13 @@ def get_ignore_options(comments: dict) -> [bool, list]:
8383
log.error(error)
8484
return ignore_all, ignore_commands
8585

86+
@staticmethod
87+
def matches_issue(alert: Issue, name: str, version: str) -> bool:
88+
return any(
89+
Comments.is_ignore(package_name, alert.pkg_version, name, version, alert.pkg_type)
90+
for package_name in {alert.pkg_name, alert.package_name_with_namespace()}
91+
)
92+
8693
@staticmethod
8794
def is_ignore(
8895
pkg_name: str, pkg_version: str, name: str, version: str,
@@ -234,9 +241,12 @@ def process_updated_security_comment(
234241
# truncated comment still has undisplayed findings unless ignore-all was
235242
# explicitly requested, even after its last visible row is removed.
236243
has_undisplayed_alerts = not ignore_all and any(
237-
Messages.EXISTING_ALERTS_TRUNCATED_MARKER in line for line in comment.body_list
244+
line.strip() in (
245+
Messages.NEW_ALERTS_TRUNCATED_MARKER,
246+
Messages.EXISTING_ALERTS_TRUNCATED_MARKER,
247+
)
248+
for line in comment.body_list
238249
)
239-
pkg_name = pkg_version = "" # Track current package and version
240250

241251
# Loop through the comment lines
242252
for line in comment.body_list:
@@ -247,18 +257,8 @@ def process_updated_security_comment(
247257

248258
# Detect the start of an alert section
249259
if stripped.startswith("<!-- start-socket-alert-"):
250-
# Extract package name and version from the comment
251-
try:
252-
start_marker = stripped[len("<!-- start-socket-alert-"):-4] # Strip the comment markers
253-
pkg_name, pkg_version = start_marker.rsplit("@", 1)
254-
except ValueError:
255-
pkg_name, pkg_version = "", ""
256-
257-
# Determine if we should ignore this alert
258-
ignore_section = ignore_all or any(
259-
Comments.is_ignore(pkg_name, pkg_version, name, version)
260-
for name, version in ignore_commands
261-
)
260+
marker = stripped.removeprefix("<!-- start-socket-alert-").removesuffix(" -->")
261+
ignore_section = ignore_all or Comments.matches_alert_marker(marker, ignore_commands)
262262

263263
# If not ignored, include this start marker
264264
if not ignore_section:
@@ -284,6 +284,23 @@ def process_updated_security_comment(
284284

285285
return Messages.normalize_comment_html("\n".join(lines))
286286

287+
@staticmethod
288+
def matches_alert_marker(marker: str, ignore_commands: list[tuple[str, str]]) -> bool:
289+
coordinate, separator, pkg_version = marker.rpartition("@")
290+
if not separator:
291+
return False
292+
prefix = Messages.QUALIFIED_ALERT_MARKER_PREFIX
293+
if coordinate.startswith(prefix):
294+
pkg_type, _, pkg_name = coordinate.removeprefix(prefix).partition("/")
295+
names = {pkg_name, pkg_name.rsplit("/", 1)[-1]}
296+
else:
297+
pkg_type, names = "", {coordinate}
298+
return any(
299+
Comments.is_ignore(pkg_name, pkg_version, name, version, pkg_type)
300+
for name, version in ignore_commands
301+
for pkg_name in names
302+
)
303+
287304
@staticmethod
288305
def extract_alert_details_from_row(row: str, ignore_all: bool, ignore_commands: list[tuple[str, str]]) -> tuple:
289306
"""

‎socketsecurity/output.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,12 @@ def build_summary_text(self, diff_report: Diff) -> str:
276276
if new_warning > 0:
277277
lines.append(f" - {warning_label}: {new_warning}")
278278
if unchanged_blocking > 0:
279-
lines.append(
280-
f" - EXISTING blocking issues: {unchanged_blocking} (causing failure due to --strict-blocking)"
279+
reason = (
280+
"not failing the run: --disable-blocking is set"
281+
if getattr(self.config, "disable_blocking", False)
282+
else "causing failure due to --strict-blocking"
281283
)
284+
lines.append(f" - EXISTING blocking issues: {unchanged_blocking} ({reason})")
282285
if unchanged_warning > 0:
283286
lines.append(f" - EXISTING warning issues: {unchanged_warning}")
284287
if is_full_scan:

‎socketsecurity/socketcli.py‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,7 @@ def _match_ignored_alerts_for_telemetry(
160160
alert
161161
for alert in ignored_alerts
162162
if any(
163-
Comments.is_ignore(
164-
alert.pkg_name,
165-
alert.pkg_version,
166-
name,
167-
version,
168-
alert.pkg_type,
169-
)
163+
Comments.matches_issue(alert, name, version)
170164
for name, version in ignore_commands
171165
)
172166
]

‎tests/core/test_existing_alerts.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -579,20 +579,52 @@ def test_pr_comment_stays_within_the_size_budget(monkeypatch):
579579

580580
comment = Messages.security_comment_template(diff, _config())
581581

582-
assert len(comment) < 6500
582+
assert len(comment.encode()) <= Messages.SECURITY_COMMENT_SIZE_BUDGET
583583
assert "more existing alert(s) are not shown" in comment
584584
assert "Existing alerts (20)" in comment
585585

586586

587-
@pytest.mark.parametrize("budget", [6000, 1])
587+
def test_existing_comment_truncation_keeps_the_blocking_first_order(monkeypatch):
588+
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000)
589+
large_blocker = _issue("large-blocker")
590+
large_blocker.description = "é" * 3000
591+
diff = _comment_diff(existing=[
592+
_issue("later-warning", error=False, warn=True),
593+
_issue("first-blocker"),
594+
large_blocker,
595+
])
596+
597+
comment = Messages.security_comment_template(diff, _config())
598+
599+
assert "first-blocker@1.0.0" in comment
600+
assert "large-blocker@1.0.0" not in comment
601+
assert "later-warning@1.0.0" not in comment
602+
assert "2 more existing alert(s) are not shown" in comment
603+
assert "[View full report](https://socket.dev/diff?action=error%2Cwarn)" in comment
604+
605+
606+
def test_omitted_existing_blocker_still_fails_strict_blocking(monkeypatch):
607+
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000)
608+
new = [_issue(f"new-{index}", error=False, warn=True) for index in range(20)]
609+
diff = _comment_diff(new=new, existing=[_issue("existing-blocker")])
610+
diff.unchanged_alerts[0].description = "é" * 3000
611+
612+
comment = Messages.security_comment_template(diff, _config())
613+
614+
assert Messages.EXISTING_ALERTS_TRUNCATED_MARKER in comment
615+
assert "existing-blocker@1.0.0" not in comment
616+
assert _handler().return_exit_code(diff) == 1
617+
assert _handler(strict_blocking=False).return_exit_code(diff) == 0
618+
619+
620+
@pytest.mark.parametrize("budget", [6000, 1500])
588621
def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budget):
589622
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", budget)
590623
diff = _comment_diff(existing=[_issue(f"pkg{i}") for i in range(20)])
591624
body = Messages.security_comment_template(diff, _config())
592625
visible = re.findall(r"<!-- start-socket-alert-(.*?) -->", body)
593626
assert len(visible) < len(diff.unchanged_alerts)
594-
if budget > 1:
595-
assert visible
627+
assert bool(visible) == (budget == 6000)
596628
comments = {"ignore": [
597629
Comment(body_list=[f"@SocketSecurity ignore npm/{package}"])
598630
for package in visible
@@ -603,7 +635,7 @@ def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budge
603635

604636
assert "No dependency alerts to report" not in updated
605637
assert "more existing alert(s) are not shown" in updated
606-
assert "[full report](https://socket.dev/diff?action=error%2Cwarn)" in updated
638+
assert "[View full report](https://socket.dev/diff?action=error%2Cwarn)" in updated
607639
# Reprocessing the comment must not lose the undisplayed findings either.
608640
assert Comments.process_security_comment(Comment(body_list=updated.splitlines()), comments) == updated
609641

0 commit comments

Comments
 (0)