Skip to content

Commit 9949dca

Browse files
committed
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.
1 parent 9e0ded9 commit 9949dca

9 files changed

Lines changed: 89 additions & 42 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616
- SARIF reports use advisory IDs to distinguish findings on the same package
1717
and manifest.
1818
- The "This package" link in GitHub and GitLab security comments opens the
19-
affected package version on socket.dev. Security rows show one package link,
20-
and license findings for distinct scopes or namespaces get separate rows.
19+
affected package version on socket.dev. License findings for different
20+
namespaces appear in separate rows, and generated ignore commands identify
21+
the package by its scope or namespace.
2122
- Large PR/MR security comments fit within GitHub's size limit and show how many
2223
new or existing findings were omitted. Policy checks and reports use all findings.
2324

‎docs/cli-reference.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,8 @@ Security issues detected by Socket Security:
666666
- **PR/MR comments**. The comment lists new alerts first, then existing alerts
667667
with Block findings first in the existing-alerts table. License findings are
668668
grouped by package, including its scope or namespace. **This package** opens
669-
the affected version on socket.dev.
669+
the affected version on socket.dev. Use the generated `@SocketSecurity ignore`
670+
command to target the package's exact scope or namespace.
670671
- **Comment size**. Large comments show how many new and existing alerts were
671672
omitted to fit GitHub's size limit and link to the full report.
672673
Policy checks and reports still use all findings. If you ignore every visible

‎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: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,14 @@ def get_view_report_url(diff: Diff) -> str:
964964
return diff.report_url
965965
return ""
966966

967+
QUALIFIED_ALERT_MARKER_PREFIX = "package:"
968+
969+
@staticmethod
970+
def alert_package_marker(alert: Issue, coordinate: str) -> str:
971+
if coordinate != f"{alert.pkg_name}@{alert.pkg_version}":
972+
coordinate = f"{Messages.QUALIFIED_ALERT_MARKER_PREFIX}{alert.pkg_type}/{coordinate}"
973+
return Messages.comment_marker_text(coordinate)
974+
967975
@staticmethod
968976
def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> str:
969977
"""One row of the security comment table for a package's license policy violations."""
@@ -974,9 +982,9 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st
974982
# Use orange diamond for license policy violations
975983
license_icon = "🔶"
976984

977-
package = f"{first_alert.pkg_name}@{first_alert.pkg_version}"
978-
license_label = Messages.html_text(getattr(first_alert, "purl", "") or package)
979-
license_marker = Messages.comment_marker_text(package)
985+
package = f"{first_alert.package_name_with_namespace()}@{first_alert.pkg_version}"
986+
license_label = Messages.html_text(package)
987+
license_marker = Messages.alert_package_marker(first_alert, package)
980988

981989
# Build license findings list
982990
license_findings = []
@@ -1002,8 +1010,8 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st
10021010
license_manifest_url = Messages.get_manifest_file_url(diff, first_alert.manifests, config)
10031011

10041012
license_ignore_html = (
1005-
f"<p><em>Mark the package as acceptable risk:</em> To ignore findings matching this package name and version in this pull request, reply with "
1006-
f"<code>@SocketSecurity ignore {Messages.html_text(first_alert.pkg_type)}/{Messages.html_text(package)}</code>. "
1013+
f"<p><em>Mark the package as acceptable risk:</em> To ignore findings for this package version in this pull request, reply with "
1014+
f"<code>@SocketSecurity ignore {Messages.html_text(first_alert.pkg_type)}/{license_label}</code>. "
10071015
f"You can also ignore all packages with <code>@SocketSecurity ignore-all</code>. "
10081016
f"To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.</p>"
10091017
) if show_ignore else ""
@@ -1037,8 +1045,9 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10371045
)
10381046
# Generate proper manifest URL
10391047
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
1040-
pkg_label = Messages.html_text(f"{alert.pkg_name}@{alert.pkg_version}")
1041-
pkg_marker = Messages.comment_marker_text(f"{alert.pkg_name}@{alert.pkg_version}")
1048+
package = f"{alert.package_name_with_namespace()}@{alert.pkg_version}"
1049+
pkg_label = Messages.html_text(package)
1050+
pkg_marker = Messages.alert_package_marker(alert, package)
10421051
alert_title = Messages.alert_title_with_advisory(alert)
10431052
ignore_html = (
10441053
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
@@ -1167,7 +1176,7 @@ def security_comment_template(diff: Diff, config=None) -> str:
11671176
+ report_link
11681177
)
11691178

1170-
# Budget UTF-8 bytes to stay below GitHub's 65,536-character limit.
1179+
# Use UTF-8 bytes so multibyte text counts toward the comment size budget.
11711180
SECURITY_COMMENT_SIZE_BUDGET = 60000
11721181
NEW_ALERTS_TRUNCATED_MARKER = "<!-- socket-new-alerts-truncated -->"
11731182
EXISTING_ALERTS_TRUNCATED_MARKER = "<!-- socket-existing-alerts-truncated -->"

‎socketsecurity/core/scm_comments.py‎

Lines changed: 27 additions & 14 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,
@@ -240,7 +247,6 @@ def process_updated_security_comment(
240247
)
241248
for line in comment.body_list
242249
)
243-
pkg_name = pkg_version = "" # Track current package and version
244250

245251
# Loop through the comment lines
246252
for line in comment.body_list:
@@ -251,18 +257,8 @@ def process_updated_security_comment(
251257

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

267263
# If not ignored, include this start marker
268264
if not ignore_section:
@@ -288,6 +284,23 @@ def process_updated_security_comment(
288284

289285
return Messages.normalize_comment_html("\n".join(lines))
290286

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+
291304
@staticmethod
292305
def extract_alert_details_from_row(row: str, ignore_all: bool, ignore_commands: list[tuple[str, str]]) -> tuple:
293306
"""

‎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: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,20 @@ def test_pr_comment_stays_within_the_size_budget(monkeypatch):
588588
assert "Existing alerts (20)" in comment
589589

590590

591+
def test_omitted_existing_blocker_still_fails_strict_blocking(monkeypatch):
592+
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000)
593+
new = [_issue(f"new-{index}", error=False, warn=True) for index in range(20)]
594+
diff = _comment_diff(new=new, existing=[_issue("existing-blocker")])
595+
diff.unchanged_alerts[0].description = "é" * 3000
596+
597+
comment = Messages.security_comment_template(diff, _config())
598+
599+
assert Messages.EXISTING_ALERTS_TRUNCATED_MARKER in comment
600+
assert "existing-blocker@1.0.0" not in comment
601+
assert _handler().return_exit_code(diff) == 1
602+
assert _handler(strict_blocking=False).return_exit_code(diff) == 0
603+
604+
591605
@pytest.mark.parametrize("budget", [6000, 1500])
592606
def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budget):
593607
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", budget)

‎tests/unit/test_comment_package_links.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ class _FakeConfig:
1919
strict_blocking: bool = True
2020

2121

22-
# (artifact fields, expected package page URL)
2322
ECOSYSTEMS = {
2423
"npm": (
2524
dict(type="npm", name="handlebars", version="4.0.11"),
@@ -60,7 +59,6 @@ class _FakeConfig:
6059

6160

6261
def _issues(artifact: dict, alert: dict) -> list:
63-
"""Build Issues the way a scan does: diff artifact -> Package -> Issue."""
6462
package = Package.from_diff_artifact({
6563
"id": f"{artifact['type']}-{artifact['name']}",
6664
"score": {},
@@ -113,7 +111,6 @@ def test_license_row_links_the_package_page(ecosystem):
113111

114112
@pytest.mark.parametrize("alert", [CVE_ALERT, LICENSE_ALERT], ids=["alert", "license"])
115113
def test_existing_alerts_table_links_the_package_page(alert):
116-
"""The --strict-blocking existing-alerts table reuses the same row templates."""
117114
artifact, expected = ECOSYSTEMS["npm-scoped"]
118115
diff = _diff([])
119116
diff.unchanged_alerts = _issues(artifact, alert)
@@ -124,11 +121,12 @@ def test_existing_alerts_table_links_the_package_page(alert):
124121

125122

126123
@pytest.mark.parametrize("section", ["new_alerts", "unchanged_alerts"])
127-
def test_license_rows_keep_package_namespaces_distinct(section):
124+
@pytest.mark.parametrize("alert", [CVE_ALERT, LICENSE_ALERT], ids=["security", "license"])
125+
def test_rows_keep_package_namespaces_distinct(section, alert):
128126
issues = []
129127
for scope in ("@alpha", "@beta"):
130128
artifact = dict(type="npm", namespace=scope, name="widgets", version="1.0.0")
131-
issues += _issues(artifact, LICENSE_ALERT)
129+
issues += _issues(artifact, alert)
132130
diff = _diff([])
133131
setattr(diff, section, issues)
134132

@@ -138,8 +136,19 @@ def test_license_rows_keep_package_namespaces_distinct(section):
138136
"https://socket.dev/npm/package/@alpha/widgets/overview/1.0.0",
139137
"https://socket.dev/npm/package/@beta/widgets/overview/1.0.0",
140138
]
141-
assert "<summary>@alpha/widgets@1.0.0 has a License Policy Violation." in body
142-
assert "<summary>@beta/widgets@1.0.0 has a License Policy Violation." in body
139+
assert "<summary>@alpha/widgets@1.0.0" in body
140+
assert "<summary>@beta/widgets@1.0.0" in body
141+
command = "@SocketSecurity ignore npm/@alpha/widgets@1.0.0"
142+
assert f"<code>{command}</code>" in body
143+
comment = Comment(body_list=body.splitlines())
144+
comments = {"ignore": [Comment(body_list=[command])]}
145+
assert Comments.remove_alerts(comments, issues) == [issues[1]]
146+
updated = Comments.process_security_comment(comment, comments)
147+
assert _this_package_hrefs(updated) == _this_package_hrefs(body)[1:]
148+
149+
legacy = {"ignore": [Comment(body_list=["@SocketSecurity ignore npm/widgets@1.0.0"])]}
150+
assert Comments.remove_alerts(legacy, issues) == []
151+
assert "No dependency alerts to report" in Comments.process_security_comment(comment, legacy)
143152

144153

145154
@pytest.mark.parametrize("with_existing", [False, True])

‎tests/unit/test_ignore_telemetry_filtering.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
"""Tests for the +1 reaction dedup logic used to filter ignore comments for telemetry."""
22

3-
from types import SimpleNamespace
43
from unittest.mock import Mock
54

6-
from socketsecurity.core.classes import Comment
5+
from socketsecurity.core.classes import Comment, Issue
76
from socketsecurity.core.scm_comments import Comments
87
from socketsecurity.socketcli import _match_ignored_alerts_for_telemetry
98

@@ -166,7 +165,7 @@ def test_no_unprocessed_means_no_telemetry(self):
166165
def test_push_telemetry_matches_a_legacy_bare_name_ignore():
167166
comment = _make_comment("SocketSecurity ignore lodash@4.17.21")
168167
_, ignore_commands = Comments.get_ignore_options({"ignore": [comment]})
169-
alert = SimpleNamespace(
168+
alert = Issue(
170169
pkg_type="npm",
171170
pkg_name="lodash",
172171
pkg_version="4.17.21",

0 commit comments

Comments
 (0)