Skip to content

Commit f10bd48

Browse files
authored
Make @SocketSecurity ignore follow Policies
On an organization on the new Socket Policies, an ignore comment may pass only Blocks under a "Developers can skip" rule, and never below a Required rule's minimum. The CLI applied every ignore itself, so a No-exceptions or Required Block passed once someone commented. The API now sends actionAfterPullRequestIgnore on each alert. An ignore keeps an alert with error, lowers a Block with warn to Warn, and drops it otherwise. Comment rows the ignore can't remove carry markers without a package, so neither this CLI nor older ones remove them from a comment-triggered run, and on GitLab such a run sets no commit status while a kept Block is listed. An ignore comment that changes nothing gets no +1. Without the field (every other organization) results, comments, reactions and status are as before. Refs WEB-2599 Assisted-by: Claude Code:claude-opus-5-5
1 parent bc836ea commit f10bd48

18 files changed

Lines changed: 2695 additions & 52 deletions

‎CHANGELOG.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,26 @@
11
# Changelog
22

3+
## 2.16.0
4+
5+
### Changed: `@SocketSecurity ignore` follows the organization's Policies
6+
7+
- On an organization that uses the new Socket Policies, an
8+
`@SocketSecurity ignore` or `@SocketSecurity ignore-all` comment removes only
9+
the alerts the organization's policy lets an ignore pass. An alert the policy
10+
keeps at Block still fails the run; one it lowers to Warn is reported as Warn.
11+
This applies to new alerts and, with `--strict-blocking`, existing ones.
12+
- In the pull or merge request comment, a row an ignore would leave unchanged
13+
shows no ignore command. A comment-triggered run leaves the rows of alerts the
14+
policy keeps in place; the next pipeline run updates them. On GitLab with
15+
`--enable-commit-status`, that comment-triggered run sets no commit status
16+
while the comment lists a Block alert the policy keeps or lowers to Warn; the
17+
next pipeline run sets it. With `--disable-ignore`, the comment-triggered run
18+
sets the status as before.
19+
- A Block alert an ignore lowers to Warn counts as ignored: the ignore comment
20+
gets its +1 reaction.
21+
- Other organizations see no change.
22+
- Requires `socketdev` 3.7.0.
23+
324
## 2.15.8
425

526
### Changed: bump pinned Coana CLI to 15.15.10

‎docs/cli-reference.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,12 @@ only from a commenter with write access to the repository. A command from anyone
736736
else is skipped, logged with the author's name, and the alerts it named stay
737737
reported. `--disable-ignore` turns the feature off entirely.
738738

739+
On an organization that uses the new Socket Policies, an honored command still
740+
removes only what the organization's policy lets an ignore pass. An alert the
741+
policy keeps stays in the reports with the action the policy gives it. When an
742+
ignore would leave an alert unchanged, its row in the pull or merge request
743+
comment shows no ignore command.
744+
739745
| Provider | How access is determined | If it cannot be determined |
740746
|:---------|:-------------------------|:---------------------------|
741747
| GitHub | Effective repository permission, read once per commenter per run. Write, maintain, or admin access is honored. | The command is honored and a warning is logged. |
@@ -917,6 +923,16 @@ reports, including the GitLab report. With `--strict-blocking`, it also removes
917923
matching existing alerts from blocking checks and reports. Without strict blocking,
918924
the GitLab report still includes existing findings.
919925

926+
On an organization that uses the new Socket Policies, the command removes only the
927+
alerts the organization's policy lets an ignore pass. An alert the policy keeps at
928+
Block still fails the run, and one the policy lowers to Warn is reported as Warn.
929+
A comment-triggered run (`issue_comment`) leaves the rows of alerts the policy
930+
keeps in the comment; the next pipeline run updates them. On GitLab with
931+
`--enable-commit-status`, that comment-triggered run sets no commit status while
932+
the comment lists a Block alert the policy keeps or lowers to Warn; the next
933+
pipeline run sets it. With `--disable-ignore`, the comment-triggered run sets the
934+
status as before.
935+
920936
`--disable-ignore` disables these commands. See [Who can ignore an alert](#who-can-ignore-an-alert)
921937
for authorization rules. To suppress a finding across future PRs, update its policy
922938
or triage state in Socket's dashboard.

‎pyproject.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.15.8"
9+
version = "2.16.0"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [
@@ -16,7 +16,7 @@ dependencies = [
1616
"gitpython==3.2.1",
1717
"packaging==26.3",
1818
"python-dotenv==1.2.4",
19-
"socketdev==3.6.4",
19+
"socketdev==3.7.0",
2020
"beautifulsoup4==4.15.0",
2121
"markdown==3.11.3",
2222
"brotli==1.2.1; platform_python_implementation == 'CPython'",

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.15.8'
2+
__version__ = '2.16.0'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/core/__init__.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from socketsecurity.config import CliConfig
3030
from git import Repo
3131
from socketdev import socketdev
32+
from socketdev.core.dedupe import Dedupe
3233
from socketdev.exceptions import (
3334
APIFailure,
3435
APIInsufficientQuota,
@@ -2958,6 +2959,9 @@ def add_package_alerts_to_collection(self, package: Package, alerts_collection:
29582959
if 'action' in alert_item and alert_item['action']:
29592960
action = alert_item['action']
29602961
setattr(issue_alert, action, True)
2962+
action_after_ignore = alert_item.get("actionAfterPullRequestIgnore")
2963+
if isinstance(action_after_ignore, str) and action_after_ignore:
2964+
issue_alert.action_after_pull_request_ignore = action_after_ignore
29612965

29622966
if issue_alert.key not in alerts_collection:
29632967
alerts_collection[issue_alert.key] = [issue_alert]
@@ -3060,12 +3064,18 @@ def get_unchanged_alerts(
30603064
def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, str, str, str], Issue]:
30613065
"""Keep the strongest reportable action for each finding across manifests and scan results."""
30623066
findings: Dict[Tuple[str, str, str, str], Issue] = {}
3067+
after_ignore: Dict[Tuple[str, str, str, str], str] = {}
30633068
for alert in alerts:
30643069
if alert.error or alert.warn:
30653070
key = alert.consolidation_key()
30663071
previous = findings.get(key)
30673072
if previous is None or (alert.error and not previous.error):
30683073
findings[key] = alert
3074+
action = getattr(alert, "action_after_pull_request_ignore", None)
3075+
if Dedupe.action_rank(action) > Dedupe.action_rank(after_ignore.get(key)):
3076+
after_ignore[key] = action
3077+
for key, action in after_ignore.items():
3078+
findings[key].action_after_pull_request_ignore = action
30693079
return findings
30703080

30713081
@staticmethod

‎socketsecurity/core/classes.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,9 @@ class Issue:
327327
# introduced_by chain, but its manifest is still known.
328328
manifest_files: list
329329
direct: bool
330+
# Set only when the API sent one, so an Issue without it compares and
331+
# serializes as before.
332+
action_after_pull_request_ignore: str
330333

331334
def __init__(self, **kwargs):
332335
if kwargs:
@@ -399,6 +402,11 @@ def consolidation_key(self) -> Tuple[str, str, str, str]:
399402
self.advisory_id(),
400403
)
401404

405+
def kept_action_after_pull_request_ignore(self) -> Optional[str]:
406+
"""The action an ignore comment leaves on this alert, or None when it removes it."""
407+
action = getattr(self, "action_after_pull_request_ignore", None)
408+
return action if action in ("error", "warn") else None
409+
402410
def __str__(self):
403411
return json.dumps(self.__dict__)
404412

‎socketsecurity/core/messages.py‎

Lines changed: 61 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from datetime import datetime, timezone
66
from html import escape
77
from pathlib import Path
8+
from typing import Optional
89

910
from mdutils import MdUtils
1011
from prettytable import PrettyTable
@@ -965,6 +966,24 @@ def get_view_report_url(diff: Diff) -> str:
965966
return ""
966967

967968
QUALIFIED_ALERT_MARKER_PREFIX = "package:"
969+
# Rows an ignore comment can't remove. They carry no "@", so no ignore command
970+
# matches them, in this version or an older one.
971+
KEPT_ERROR_ALERT_MARKER = "kept-error"
972+
LOWERED_WARN_ALERT_MARKER = "lowered-warn"
973+
KEPT_WARN_ALERT_MARKER = "kept-warn"
974+
KEPT_ALERT_MARKERS = (KEPT_ERROR_ALERT_MARKER, LOWERED_WARN_ALERT_MARKER, KEPT_WARN_ALERT_MARKER)
975+
976+
@staticmethod
977+
def kept_alert_marker(alerts: list) -> Optional[str]:
978+
"""The marker for a row an ignore comment can't remove, or None when it removes it."""
979+
kept = {alert.kept_action_after_pull_request_ignore() for alert in alerts}
980+
if not kept - {None}:
981+
return None
982+
if not any(alert.error for alert in alerts):
983+
return Messages.KEPT_WARN_ALERT_MARKER
984+
if "error" in kept:
985+
return Messages.KEPT_ERROR_ALERT_MARKER
986+
return Messages.LOWERED_WARN_ALERT_MARKER
968987

969988
@staticmethod
970989
def alert_package_marker(alert: Issue, coordinate: str) -> str:
@@ -984,7 +1003,11 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st
9841003

9851004
package = f"{first_alert.package_name_with_namespace()}@{first_alert.pkg_version}"
9861005
license_label = Messages.html_text(package)
987-
license_marker = Messages.alert_package_marker(first_alert, package)
1006+
kept_marker = Messages.kept_alert_marker(alerts)
1007+
license_marker = kept_marker or Messages.alert_package_marker(first_alert, package)
1008+
show_ignore = show_ignore and kept_marker not in (
1009+
Messages.KEPT_ERROR_ALERT_MARKER, Messages.KEPT_WARN_ALERT_MARKER,
1010+
)
9881011

9891012
# Build license findings list
9901013
license_findings = []
@@ -1047,7 +1070,11 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10471070
manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config)
10481071
package = f"{alert.package_name_with_namespace()}@{alert.pkg_version}"
10491072
pkg_label = Messages.html_text(package)
1050-
pkg_marker = Messages.alert_package_marker(alert, package)
1073+
kept_marker = Messages.kept_alert_marker([alert])
1074+
pkg_marker = kept_marker or Messages.alert_package_marker(alert, package)
1075+
show_ignore = show_ignore and kept_marker not in (
1076+
Messages.KEPT_ERROR_ALERT_MARKER, Messages.KEPT_WARN_ALERT_MARKER,
1077+
)
10511078
alert_title = Messages.alert_title_with_advisory(alert)
10521079
ignore_html = (
10531080
f"<p><em>Mark as acceptable risk:</em> To ignore this alert only in this pull request, reply with:<br/>"
@@ -1144,12 +1171,17 @@ def security_comment_template(diff: Diff, config=None) -> str:
11441171
{table_open}"""
11451172
existing_footer = table_close + "<!-- end-socket-existing-alerts -->\n"
11461173

1174+
new_groups = Messages.comment_alert_groups(new_alerts)
1175+
new_groups.sort(key=lambda group: group[0].type == "licenseSpdxDisj")
1176+
existing_groups = Messages.comment_alert_groups(existing_alerts)
1177+
existing_groups.sort(key=lambda group: not any(alert.error for alert in group))
1178+
11471179
# Reserve the full table structure and the largest possible omission notices
11481180
# before adding rows, so a large new section cannot displace the footer.
11491181
reserved = (
11501182
new_header, new_footer, existing_header, existing_footer,
1151-
Messages.omitted_comment_alerts("new", len(new_alerts)),
1152-
Messages.omitted_comment_alerts("existing", len(existing_alerts)),
1183+
Messages.omitted_comment_alerts("new", len(new_alerts), new_groups),
1184+
Messages.omitted_comment_alerts("existing", len(existing_alerts), existing_groups),
11531185
)
11541186
budget = Messages.SECURITY_COMMENT_SIZE_BUDGET - sum(len(part.encode()) for part in reserved)
11551187
report_link = f"\n[View full report]({view_report_url}?action=error%2Cwarn)\n" if view_report_url else ""
@@ -1159,37 +1191,46 @@ def security_comment_template(diff: Diff, config=None) -> str:
11591191
report_link_size = 0
11601192
budget -= report_link_size
11611193

1162-
new_groups = Messages.comment_alert_groups(new_alerts)
1163-
new_groups.sort(key=lambda group: group[0].type == "licenseSpdxDisj")
1164-
existing_groups = Messages.comment_alert_groups(existing_alerts)
1165-
existing_groups.sort(key=lambda group: not any(alert.error for alert in group))
1166-
new_rows, new_count = Messages.comment_alert_rows(new_groups, diff, config, budget)
1167-
existing_rows, existing_count = Messages.comment_alert_rows(
1194+
new_rows, new_count, new_omitted = Messages.comment_alert_rows(new_groups, diff, config, budget)
1195+
existing_rows, existing_count, existing_omitted = Messages.comment_alert_rows(
11681196
existing_groups, diff, config, budget - len(new_rows.encode())
11691197
)
11701198
return Messages.normalize_comment_html(
11711199
new_header + new_rows + new_footer
1172-
+ Messages.omitted_comment_alerts("new", len(new_alerts) - new_count)
1200+
+ Messages.omitted_comment_alerts("new", len(new_alerts) - new_count, new_omitted)
11731201
+ existing_header + existing_rows + existing_footer
1174-
+ Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count)
1202+
+ Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count, existing_omitted)
11751203
+ report_link
11761204
)
11771205

11781206
# Use UTF-8 bytes so multibyte text counts toward the comment size budget.
11791207
SECURITY_COMMENT_SIZE_BUDGET = 60000
11801208
NEW_ALERTS_TRUNCATED_MARKER = "<!-- socket-new-alerts-truncated -->"
11811209
EXISTING_ALERTS_TRUNCATED_MARKER = "<!-- socket-existing-alerts-truncated -->"
1210+
KEPT_ERROR_ALERTS_TRUNCATED_MARKER = "<!-- socket-kept-error-alerts-truncated -->"
1211+
LOWERED_WARN_ALERTS_TRUNCATED_MARKER = "<!-- socket-lowered-warn-alerts-truncated -->"
1212+
KEPT_WARN_ALERTS_TRUNCATED_MARKER = "<!-- socket-kept-warn-alerts-truncated -->"
11821213

11831214
@staticmethod
1184-
def omitted_comment_alerts(section: str, count: int) -> str:
1215+
def omitted_comment_alerts(section: str, count: int, omitted_groups: list = ()) -> str:
11851216
if not count:
11861217
return ""
11871218
marker = (
11881219
Messages.NEW_ALERTS_TRUNCATED_MARKER if section == "new"
11891220
else Messages.EXISTING_ALERTS_TRUNCATED_MARKER
11901221
)
1222+
kept_markers = {Messages.kept_alert_marker(group) for group in omitted_groups}
1223+
truncated_kept = "".join(
1224+
f"{truncated}\n"
1225+
for kept, truncated in (
1226+
(Messages.KEPT_ERROR_ALERT_MARKER, Messages.KEPT_ERROR_ALERTS_TRUNCATED_MARKER),
1227+
(Messages.LOWERED_WARN_ALERT_MARKER, Messages.LOWERED_WARN_ALERTS_TRUNCATED_MARKER),
1228+
(Messages.KEPT_WARN_ALERT_MARKER, Messages.KEPT_WARN_ALERTS_TRUNCATED_MARKER),
1229+
)
1230+
if kept in kept_markers
1231+
)
11911232
return (
1192-
f"\n{marker}\n\n{count} more {section} alert(s) are not shown here "
1233+
f"\n{marker}\n{truncated_kept}\n{count} more {section} alert(s) are not shown here "
11931234
"to keep this comment within GitHub's size limit.\n"
11941235
)
11951236

@@ -1244,25 +1285,25 @@ def comment_alert_groups(alerts: list) -> list:
12441285
return entries
12451286

12461287
@staticmethod
1247-
def comment_alert_rows(groups: list, diff: Diff, config, budget: int) -> tuple[str, int]:
1248-
"""Keep the row order when the size budget cuts a table short."""
1288+
def comment_alert_rows(groups: list, diff: Diff, config, budget: int) -> tuple[str, int, list]:
1289+
"""Keep the row order when the size budget cuts a table short; also return the groups cut."""
12491290
show_ignore = not (config and getattr(config, "disable_ignore", False))
12501291
rows = []
12511292
shown = 0
1252-
for group in groups:
1293+
for index, group in enumerate(groups):
12531294
if budget <= 0:
1254-
break
1295+
return "".join(rows), shown, groups[index:]
12551296
if group[0].type == "licenseSpdxDisj":
12561297
row = Messages.license_group_row(group, diff, config, show_ignore)
12571298
else:
12581299
row = Messages.security_alert_row(group[0], diff, config, show_ignore)
12591300
row_size = len(row.encode())
12601301
if row_size > budget:
1261-
break
1302+
return "".join(rows), shown, groups[index:]
12621303
rows.append(row)
12631304
budget -= row_size
12641305
shown += len(group)
1265-
return "".join(rows), shown
1306+
return "".join(rows), shown, []
12661307

12671308
@staticmethod
12681309
def get_severity_icon(severity: str) -> str:

‎socketsecurity/core/scm/base.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from abc import ABC, abstractmethod
2-
from typing import Dict
2+
from typing import Dict, Optional
33

44
from ..classes import Comment
55
from .client import ScmClient
@@ -32,6 +32,6 @@ def get_comments_for_pr(self, repo: str, pr: str) -> Dict[str, Comment]:
3232
pass
3333

3434
@abstractmethod
35-
def remove_comment_alerts(self, comments: Dict[str, Comment]) -> None:
36-
"""Process and remove alerts from comments"""
35+
def remove_comment_alerts(self, comments: Dict[str, Comment]) -> Optional[str]:
36+
"""Process and remove alerts from comments; return the security comment's body afterwards"""
3737
pass

‎socketsecurity/core/scm/github.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -378,14 +378,17 @@ def add_socket_comments(
378378
log.debug("No Previous version of Security Issue comment, posting")
379379
self.post_comment(security_comment)
380380

381-
def remove_comment_alerts(self, comments: dict) -> None:
381+
def remove_comment_alerts(self, comments: dict) -> Optional[str]:
382+
security_alert = comments.get("security")
382383
if not comments.get("ignore"):
383384
log.info("No @SocketSecurity ignore commands to process on this pull request")
384-
return
385-
if security_alert := comments.get("security"):
385+
return security_alert.body if security_alert else None
386+
if security_alert:
386387
new_body = Comments.process_security_comment(security_alert, comments)
387-
self.handle_ignore_reactions(comments)
388+
self.handle_ignore_reactions(Comments.effective_ignores(comments))
388389
self.update_comment(new_body, str(security_alert.id))
390+
return new_body
391+
return None
389392

390393
def handle_ignore_reactions(self, comments: dict) -> None:
391394
for comment in comments.get("ignore", []):

‎socketsecurity/core/scm/gitlab.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -479,13 +479,15 @@ def handle_ignore_reactions(self, comments: dict) -> None:
479479
if "SocketSecurity ignore" in comment.body and not self.has_thumbsup_reaction(comment.id):
480480
self.post_thumbsup_reaction(comment.id)
481481

482-
def remove_comment_alerts(self, comments: dict):
482+
def remove_comment_alerts(self, comments: dict) -> Optional[str]:
483+
security_alert = comments.get("security")
483484
if not comments.get("ignore"):
484485
log.info("No @SocketSecurity ignore commands to process on this merge request")
485-
return
486-
security_alert = comments.get("security")
486+
return security_alert.body if security_alert is not None else None
487487
if security_alert is not None:
488488
# Type narrowing: after None check, mypy knows this is Comment
489489
new_body = Comments.process_security_comment(security_alert, comments)
490-
self.handle_ignore_reactions(comments)
490+
self.handle_ignore_reactions(Comments.effective_ignores(comments))
491491
self.update_comment(new_body, str(security_alert.id))
492+
return new_body
493+
return None

0 commit comments

Comments
 (0)