Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
# Changelog

## 2.16.0

### Changed: `@SocketSecurity ignore` follows the organization's Policies

- On an organization that uses the new Socket Policies, an
`@SocketSecurity ignore` or `@SocketSecurity ignore-all` comment removes only
the alerts the organization's policy lets an ignore pass. An alert the policy
keeps at Block still fails the run; one it lowers to Warn is reported as Warn.
This applies to new alerts and, with `--strict-blocking`, existing ones.
- In the pull or merge request comment, a row an ignore would leave unchanged
shows no ignore command. A comment-triggered run leaves the rows of alerts the
policy keeps in place; the next pipeline run updates them. On GitLab with
`--enable-commit-status`, that comment-triggered run sets no commit status
while the comment lists a Block alert the policy keeps or lowers to Warn; the
next pipeline run sets it. With `--disable-ignore`, the comment-triggered run
sets the status as before.
- A Block alert an ignore lowers to Warn counts as ignored: the ignore comment
gets its +1 reaction. An ignore comment that changes nothing gets no +1 and
sends no ignore event.
- Other organizations see no change.
- Requires `socketdev` 3.7.0.

## 2.15.8

### Changed: bump pinned Coana CLI to 15.15.10
Expand Down
16 changes: 16 additions & 0 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,12 @@ only from a commenter with write access to the repository. A command from anyone
else is skipped, logged with the author's name, and the alerts it named stay
reported. `--disable-ignore` turns the feature off entirely.

On an organization that uses the new Socket Policies, an honored command still
removes only what the organization's policy lets an ignore pass. An alert the
policy keeps stays in the reports with the action the policy gives it. When an
ignore would leave an alert unchanged, its row in the pull or merge request
comment shows no ignore command.

| Provider | How access is determined | If it cannot be determined |
|:---------|:-------------------------|:---------------------------|
| 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. |
Expand Down Expand Up @@ -917,6 +923,16 @@ reports, including the GitLab report. With `--strict-blocking`, it also removes
matching existing alerts from blocking checks and reports. Without strict blocking,
the GitLab report still includes existing findings.

On an organization that uses the new Socket Policies, the command removes only the
alerts the organization's policy lets an ignore pass. An alert the policy keeps at
Block still fails the run, and one the policy lowers to Warn is reported as Warn.
A comment-triggered run (`issue_comment`) leaves the rows of alerts the policy
keeps in the comment; the next pipeline run updates them. On GitLab with
`--enable-commit-status`, that comment-triggered run sets no commit status while
the comment lists a Block alert the policy keeps or lowers to Warn; the next
pipeline run sets it. With `--disable-ignore`, the comment-triggered run sets the
status as before.

`--disable-ignore` disables these commands. See [Who can ignore an alert](#who-can-ignore-an-alert)
for authorization rules. To suppress a finding across future PRs, update its policy
or triage state in Socket's dashboard.
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "hatchling.build"

[project]
name = "socketsecurity"
version = "2.15.8"
version = "2.16.0"
requires-python = ">= 3.11"
license = {"file" = "LICENSE"}
dependencies = [
Expand All @@ -16,7 +16,7 @@ dependencies = [
"gitpython==3.2.1",
"packaging==26.3",
"python-dotenv==1.2.4",
"socketdev==3.6.4",
"socketdev==3.7.0",
"beautifulsoup4==4.15.0",
"markdown==3.11.3",
"brotli==1.2.1; platform_python_implementation == 'CPython'",
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__author__ = 'socket.dev'
__version__ = '2.15.8'
__version__ = '2.16.0'
USER_AGENT_NAME = 'socket-python-cli'
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
10 changes: 10 additions & 0 deletions socketsecurity/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from socketsecurity.config import CliConfig
from git import Repo
from socketdev import socketdev
from socketdev.core.dedupe import Dedupe
from socketdev.exceptions import (
APIFailure,
APIInsufficientQuota,
Expand Down Expand Up @@ -2958,6 +2959,9 @@ def add_package_alerts_to_collection(self, package: Package, alerts_collection:
if 'action' in alert_item and alert_item['action']:
action = alert_item['action']
setattr(issue_alert, action, True)
action_after_ignore = alert_item.get("actionAfterPullRequestIgnore")
if isinstance(action_after_ignore, str) and action_after_ignore:
issue_alert.action_after_pull_request_ignore = action_after_ignore

if issue_alert.key not in alerts_collection:
alerts_collection[issue_alert.key] = [issue_alert]
Expand Down Expand Up @@ -3060,12 +3064,18 @@ def get_unchanged_alerts(
def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, str, str, str], Issue]:
"""Keep the strongest reportable action for each finding across manifests and scan results."""
findings: Dict[Tuple[str, str, str, str], Issue] = {}
after_ignore: Dict[Tuple[str, str, str, str], str] = {}
for alert in alerts:
if alert.error or alert.warn:
key = alert.consolidation_key()
previous = findings.get(key)
if previous is None or (alert.error and not previous.error):
findings[key] = alert
action = getattr(alert, "action_after_pull_request_ignore", None)
if Dedupe.action_rank(action) > Dedupe.action_rank(after_ignore.get(key)):
after_ignore[key] = action
for key, action in after_ignore.items():
findings[key].action_after_pull_request_ignore = action
return findings

@staticmethod
Expand Down
8 changes: 8 additions & 0 deletions socketsecurity/core/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,9 @@ class Issue:
# introduced_by chain, but its manifest is still known.
manifest_files: list
direct: bool
# Set only when the API sent one, so an Issue without it compares and
# serializes as before.
action_after_pull_request_ignore: str

def __init__(self, **kwargs):
if kwargs:
Expand Down Expand Up @@ -399,6 +402,11 @@ def consolidation_key(self) -> Tuple[str, str, str, str]:
self.advisory_id(),
)

def kept_action_after_pull_request_ignore(self) -> Optional[str]:
"""The action an ignore comment leaves on this alert, or None when it removes it."""
action = getattr(self, "action_after_pull_request_ignore", None)
return action if action in ("error", "warn") else None

def __str__(self):
return json.dumps(self.__dict__)

Expand Down
81 changes: 61 additions & 20 deletions socketsecurity/core/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datetime import datetime, timezone
from html import escape
from pathlib import Path
from typing import Optional

from mdutils import MdUtils
from prettytable import PrettyTable
Expand Down Expand Up @@ -965,6 +966,24 @@ def get_view_report_url(diff: Diff) -> str:
return ""

QUALIFIED_ALERT_MARKER_PREFIX = "package:"
# Rows an ignore comment can't remove. They carry no "@", so no ignore command
# matches them, in this version or an older one.
KEPT_ERROR_ALERT_MARKER = "kept-error"
LOWERED_WARN_ALERT_MARKER = "lowered-warn"
KEPT_WARN_ALERT_MARKER = "kept-warn"
KEPT_ALERT_MARKERS = (KEPT_ERROR_ALERT_MARKER, LOWERED_WARN_ALERT_MARKER, KEPT_WARN_ALERT_MARKER)

@staticmethod
def kept_alert_marker(alerts: list) -> Optional[str]:
"""The marker for a row an ignore comment can't remove, or None when it removes it."""
kept = {alert.kept_action_after_pull_request_ignore() for alert in alerts}
if not kept - {None}:
return None
if not any(alert.error for alert in alerts):
return Messages.KEPT_WARN_ALERT_MARKER
if "error" in kept:
return Messages.KEPT_ERROR_ALERT_MARKER
return Messages.LOWERED_WARN_ALERT_MARKER

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

package = f"{first_alert.package_name_with_namespace()}@{first_alert.pkg_version}"
license_label = Messages.html_text(package)
license_marker = Messages.alert_package_marker(first_alert, package)
kept_marker = Messages.kept_alert_marker(alerts)
license_marker = kept_marker or Messages.alert_package_marker(first_alert, package)
show_ignore = show_ignore and kept_marker not in (
Messages.KEPT_ERROR_ALERT_MARKER, Messages.KEPT_WARN_ALERT_MARKER,
)

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

new_groups = Messages.comment_alert_groups(new_alerts)
new_groups.sort(key=lambda group: group[0].type == "licenseSpdxDisj")
existing_groups = Messages.comment_alert_groups(existing_alerts)
existing_groups.sort(key=lambda group: not any(alert.error for alert in group))

# Reserve the full table structure and the largest possible omission notices
# before adding rows, so a large new section cannot displace the footer.
reserved = (
new_header, new_footer, existing_header, existing_footer,
Messages.omitted_comment_alerts("new", len(new_alerts)),
Messages.omitted_comment_alerts("existing", len(existing_alerts)),
Messages.omitted_comment_alerts("new", len(new_alerts), new_groups),
Messages.omitted_comment_alerts("existing", len(existing_alerts), existing_groups),
)
budget = Messages.SECURITY_COMMENT_SIZE_BUDGET - sum(len(part.encode()) for part in reserved)
report_link = f"\n[View full report]({view_report_url}?action=error%2Cwarn)\n" if view_report_url else ""
Expand All @@ -1159,37 +1191,46 @@ def security_comment_template(diff: Diff, config=None) -> str:
report_link_size = 0
budget -= report_link_size

new_groups = Messages.comment_alert_groups(new_alerts)
new_groups.sort(key=lambda group: group[0].type == "licenseSpdxDisj")
existing_groups = Messages.comment_alert_groups(existing_alerts)
existing_groups.sort(key=lambda group: not any(alert.error for alert in group))
new_rows, new_count = Messages.comment_alert_rows(new_groups, diff, config, budget)
existing_rows, existing_count = Messages.comment_alert_rows(
new_rows, new_count, new_omitted = Messages.comment_alert_rows(new_groups, diff, config, budget)
existing_rows, existing_count, existing_omitted = Messages.comment_alert_rows(
existing_groups, diff, config, budget - len(new_rows.encode())
)
return Messages.normalize_comment_html(
new_header + new_rows + new_footer
+ Messages.omitted_comment_alerts("new", len(new_alerts) - new_count)
+ Messages.omitted_comment_alerts("new", len(new_alerts) - new_count, new_omitted)
+ existing_header + existing_rows + existing_footer
+ Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count)
+ Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count, existing_omitted)
+ report_link
)

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

@staticmethod
def omitted_comment_alerts(section: str, count: int) -> str:
def omitted_comment_alerts(section: str, count: int, omitted_groups: list = ()) -> str:
if not count:
return ""
marker = (
Messages.NEW_ALERTS_TRUNCATED_MARKER if section == "new"
else Messages.EXISTING_ALERTS_TRUNCATED_MARKER
)
kept_markers = {Messages.kept_alert_marker(group) for group in omitted_groups}
truncated_kept = "".join(
f"{truncated}\n"
for kept, truncated in (
(Messages.KEPT_ERROR_ALERT_MARKER, Messages.KEPT_ERROR_ALERTS_TRUNCATED_MARKER),
(Messages.LOWERED_WARN_ALERT_MARKER, Messages.LOWERED_WARN_ALERTS_TRUNCATED_MARKER),
(Messages.KEPT_WARN_ALERT_MARKER, Messages.KEPT_WARN_ALERTS_TRUNCATED_MARKER),
)
if kept in kept_markers
)
return (
f"\n{marker}\n\n{count} more {section} alert(s) are not shown here "
f"\n{marker}\n{truncated_kept}\n{count} more {section} alert(s) are not shown here "
"to keep this comment within GitHub's size limit.\n"
)

Expand Down Expand Up @@ -1244,25 +1285,25 @@ def comment_alert_groups(alerts: list) -> list:
return entries

@staticmethod
def comment_alert_rows(groups: list, diff: Diff, config, budget: int) -> tuple[str, int]:
"""Keep the row order when the size budget cuts a table short."""
def comment_alert_rows(groups: list, diff: Diff, config, budget: int) -> tuple[str, int, list]:
"""Keep the row order when the size budget cuts a table short; also return the groups cut."""
show_ignore = not (config and getattr(config, "disable_ignore", False))
rows = []
shown = 0
for group in groups:
for index, group in enumerate(groups):
if budget <= 0:
break
return "".join(rows), shown, groups[index:]
if group[0].type == "licenseSpdxDisj":
row = Messages.license_group_row(group, diff, config, show_ignore)
else:
row = Messages.security_alert_row(group[0], diff, config, show_ignore)
row_size = len(row.encode())
if row_size > budget:
break
return "".join(rows), shown, groups[index:]
rows.append(row)
budget -= row_size
shown += len(group)
return "".join(rows), shown
return "".join(rows), shown, []

@staticmethod
def get_severity_icon(severity: str) -> str:
Expand Down
6 changes: 3 additions & 3 deletions socketsecurity/core/scm/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
from typing import Dict
from typing import Dict, Optional

from ..classes import Comment
from .client import ScmClient
Expand Down Expand Up @@ -32,6 +32,6 @@ def get_comments_for_pr(self, repo: str, pr: str) -> Dict[str, Comment]:
pass

@abstractmethod
def remove_comment_alerts(self, comments: Dict[str, Comment]) -> None:
"""Process and remove alerts from comments"""
def remove_comment_alerts(self, comments: Dict[str, Comment]) -> Optional[str]:
"""Process and remove alerts from comments; return the security comment's body afterwards"""
pass
11 changes: 7 additions & 4 deletions socketsecurity/core/scm/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,14 +378,17 @@ def add_socket_comments(
log.debug("No Previous version of Security Issue comment, posting")
self.post_comment(security_comment)

def remove_comment_alerts(self, comments: dict) -> None:
def remove_comment_alerts(self, comments: dict) -> Optional[str]:
security_alert = comments.get("security")
if not comments.get("ignore"):
log.info("No @SocketSecurity ignore commands to process on this pull request")
return
if security_alert := comments.get("security"):
return security_alert.body if security_alert else None
if security_alert:
new_body = Comments.process_security_comment(security_alert, comments)
self.handle_ignore_reactions(comments)
self.handle_ignore_reactions(Comments.effective_ignores(comments))
self.update_comment(new_body, str(security_alert.id))
return new_body
return None

def handle_ignore_reactions(self, comments: dict) -> None:
for comment in comments.get("ignore", []):
Expand Down
10 changes: 6 additions & 4 deletions socketsecurity/core/scm/gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,13 +479,15 @@ def handle_ignore_reactions(self, comments: dict) -> None:
if "SocketSecurity ignore" in comment.body and not self.has_thumbsup_reaction(comment.id):
self.post_thumbsup_reaction(comment.id)

def remove_comment_alerts(self, comments: dict):
def remove_comment_alerts(self, comments: dict) -> Optional[str]:
security_alert = comments.get("security")
if not comments.get("ignore"):
log.info("No @SocketSecurity ignore commands to process on this merge request")
return
security_alert = comments.get("security")
return security_alert.body if security_alert is not None else None
if security_alert is not None:
# Type narrowing: after None check, mypy knows this is Comment
new_body = Comments.process_security_comment(security_alert, comments)
self.handle_ignore_reactions(comments)
self.handle_ignore_reactions(Comments.effective_ignores(comments))
self.update_comment(new_body, str(security_alert.id))
return new_body
return None
Loading
Loading