diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c2a741d..d2b401d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 921e8622..0e8be73d 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -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. | @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 96b1a964..a5d97e9a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ @@ -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'", diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 9e817a06..b81e67ea 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -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__}' diff --git a/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index 9fc1ec3f..7929a09d 100644 --- a/socketsecurity/core/__init__.py +++ b/socketsecurity/core/__init__.py @@ -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, @@ -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] @@ -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 diff --git a/socketsecurity/core/classes.py b/socketsecurity/core/classes.py index bdea4b41..00f7b5fc 100644 --- a/socketsecurity/core/classes.py +++ b/socketsecurity/core/classes.py @@ -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: @@ -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__) diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 3b475dee..2ab5b9a9 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -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 @@ -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: @@ -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 = [] @@ -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"
Mark as acceptable risk: To ignore this alert only in this pull request, reply with:
"
@@ -1144,12 +1171,17 @@ def security_comment_template(diff: Diff, config=None) -> str:
{table_open}"""
existing_footer = table_close + "\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 ""
@@ -1159,19 +1191,15 @@ 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
)
@@ -1179,17 +1207,30 @@ def security_comment_template(diff: Diff, config=None) -> str:
SECURITY_COMMENT_SIZE_BUDGET = 60000
NEW_ALERTS_TRUNCATED_MARKER = ""
EXISTING_ALERTS_TRUNCATED_MARKER = ""
+ KEPT_ERROR_ALERTS_TRUNCATED_MARKER = ""
+ LOWERED_WARN_ALERTS_TRUNCATED_MARKER = ""
+ KEPT_WARN_ALERTS_TRUNCATED_MARKER = ""
@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"
)
@@ -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:
diff --git a/socketsecurity/core/scm/base.py b/socketsecurity/core/scm/base.py
index 715f6de5..14229a2e 100644
--- a/socketsecurity/core/scm/base.py
+++ b/socketsecurity/core/scm/base.py
@@ -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
@@ -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
diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py
index f5445f9b..626273be 100644
--- a/socketsecurity/core/scm/github.py
+++ b/socketsecurity/core/scm/github.py
@@ -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", []):
diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py
index d661a897..5f1f11c2 100644
--- a/socketsecurity/core/scm/gitlab.py
+++ b/socketsecurity/core/scm/gitlab.py
@@ -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
diff --git a/socketsecurity/core/scm_comments.py b/socketsecurity/core/scm_comments.py
index 0ddb9225..746cf5eb 100644
--- a/socketsecurity/core/scm_comments.py
+++ b/socketsecurity/core/scm_comments.py
@@ -1,3 +1,4 @@
+import copy
import json
import re
from typing import Callable, Optional
@@ -41,19 +42,42 @@ def remove_alerts(comments: dict, new_alerts: list) -> list:
ignore_all, ignore_commands = Comments.get_ignore_options(comments)
for alert in new_alerts:
alert: Issue
- if ignore_all:
- break
- else:
- if any(
- Comments.matches_issue(alert, name, version)
- for name, version in ignore_commands
- ):
- log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored")
- else:
- log.info(f"Adding alert {alert.type} for {alert.pkg_name}@{alert.pkg_version}")
- alerts.append(alert)
+ if not ignore_all and not any(
+ Comments.matches_issue(alert, name, version)
+ for name, version in ignore_commands
+ ):
+ log.info(f"Adding alert {alert.type} for {alert.pkg_name}@{alert.pkg_version}")
+ alerts.append(alert)
+ continue
+ kept = Comments.alert_after_ignore(alert)
+ if kept is not None:
+ log.info(
+ f"Alert {alert.type} for {alert.pkg_name}@{alert.pkg_version} "
+ f"stays {'error' if kept.error else 'warn'}: "
+ "the organization's policy doesn't let an ignore remove it"
+ )
+ alerts.append(kept)
+ elif not ignore_all:
+ log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored")
return alerts
+ @staticmethod
+ def alert_after_ignore(alert: Issue) -> Optional[Issue]:
+ """The alert as an ignore comment leaves it, or None when the ignore removes it.
+
+ A Block the policy lowers is returned as a copy, so the original still
+ compares unequal to it and counts as ignored.
+ """
+ action = alert.kept_action_after_pull_request_ignore()
+ if action is None:
+ return None
+ if action == "warn" and alert.error:
+ lowered = copy.copy(alert)
+ lowered.error = False
+ lowered.warn = True
+ return lowered
+ return alert
+
@staticmethod
def get_ignore_options(comments: dict) -> [bool, list]:
ignore_commands = []
@@ -239,9 +263,15 @@ def process_updated_security_comment(
kept_alert = False # Whether any alert row survived the ignore commands
# Individual ignore commands only account for the rows we can see. A
# truncated comment still has undisplayed findings unless ignore-all was
- # explicitly requested, even after its last visible row is removed.
- has_undisplayed_alerts = not ignore_all and any(
+ # explicitly requested, even after its last visible row is removed. Cut rows
+ # an ignore can't remove count under ignore-all too.
+ has_undisplayed_alerts = any(
line.strip() in (
+ Messages.KEPT_ERROR_ALERTS_TRUNCATED_MARKER,
+ Messages.LOWERED_WARN_ALERTS_TRUNCATED_MARKER,
+ Messages.KEPT_WARN_ALERTS_TRUNCATED_MARKER,
+ )
+ or not ignore_all and line.strip() in (
Messages.NEW_ALERTS_TRUNCATED_MARKER,
Messages.EXISTING_ALERTS_TRUNCATED_MARKER,
)
@@ -258,7 +288,9 @@ def process_updated_security_comment(
# Detect the start of an alert section
if stripped.startswith("")
- ignore_section = ignore_all or Comments.matches_alert_marker(marker, ignore_commands)
+ ignore_section = marker not in Messages.KEPT_ALERT_MARKERS and (
+ ignore_all or Comments.matches_alert_marker(marker, ignore_commands)
+ )
# If not ignored, include this start marker
if not ignore_section:
@@ -284,6 +316,44 @@ def process_updated_security_comment(
return Messages.normalize_comment_html("\n".join(lines))
+ @staticmethod
+ def effective_ignores(comments: dict) -> dict:
+ """The comments with only the ignore comments that change the security comment on their own.
+
+ Kept rows carry no package, so without them every command counts, as before.
+ """
+ security = comments.get("security")
+ kept = (
+ *(f"" for marker in Messages.KEPT_ALERT_MARKERS),
+ Messages.KEPT_ERROR_ALERTS_TRUNCATED_MARKER,
+ Messages.LOWERED_WARN_ALERTS_TRUNCATED_MARKER,
+ Messages.KEPT_WARN_ALERTS_TRUNCATED_MARKER,
+ )
+ if security is None or not any(line.strip() in kept for line in security.body_list):
+ return comments
+ before = Messages.normalize_comment_html("\n".join(line.rstrip("\r") for line in security.body_list))
+ effective = []
+ for comment in comments.get("ignore", []):
+ ignore_all, ignore_commands = Comments.get_ignore_options({"ignore": [comment]})
+ after = Comments.process_updated_security_comment(security, ignore_all, ignore_commands)
+ if Messages.normalize_comment_html(after) != before:
+ effective.append(comment)
+ return {**comments, "ignore": effective}
+
+ @staticmethod
+ def comment_keeps_blocks(body: Optional[str]) -> bool:
+ """Whether the comment lists a Block alert the policy keeps or lowers to Warn.
+
+ Until the next pipeline run renders a lowered one as Warn, it still reads Block.
+ """
+ holding = (
+ f"",
+ f"",
+ Messages.KEPT_ERROR_ALERTS_TRUNCATED_MARKER,
+ Messages.LOWERED_WARN_ALERTS_TRUNCATED_MARKER,
+ )
+ return bool(body) and any(line.strip() in holding for line in body.split("\n"))
+
@staticmethod
def matches_alert_marker(marker: str, ignore_commands: list[tuple[str, str]]) -> bool:
coordinate, separator, pkg_version = marker.rpartition("@")
diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py
index 586d1c0a..4b4aa598 100644
--- a/socketsecurity/socketcli.py
+++ b/socketsecurity/socketcli.py
@@ -771,6 +771,7 @@ def _is_unprocessed(c):
# is already covered by force_api_mode. See the blocking guard after the
# scan for why this is tracked.
comparison_ran = True
+ security_comment_body = None
if scm_event_type == "comment":
# FIXME: This entire flow should be a separate command called "filter_ignored_alerts_in_comments"
# It's not related to scanning or diff generation - it just:
@@ -786,7 +787,7 @@ def _is_unprocessed(c):
# Emit telemetry for ignore comments before +1 reaction is added.
# The +1 reaction (added by remove_comment_alerts) serves as the "processed" marker.
if "ignore" in comments:
- unprocessed = [c for c in comments["ignore"] if _is_unprocessed(c)]
+ unprocessed = [c for c in Comments.effective_ignores(comments)["ignore"] if _is_unprocessed(c)]
if unprocessed:
try:
events = []
@@ -821,7 +822,7 @@ def _is_unprocessed(c):
log.warning(f"Failed to send ignore telemetry: {e}")
log.debug("Removing comment alerts")
- scm.remove_comment_alerts(comments)
+ security_comment_body = scm.remove_comment_alerts(comments)
else:
log.info("Ignore commands disabled (--disable-ignore), skipping comment processing")
@@ -846,6 +847,7 @@ def _is_unprocessed(c):
log.debug("Removing comment alerts")
alerts_before = list(diff.new_alerts)
diff.new_alerts = Comments.remove_alerts(comments, diff.new_alerts)
+ considered = list(alerts_before)
ignored_alerts = [a for a in alerts_before if a not in diff.new_alerts]
# Under --strict-blocking, existing alerts fail the run and appear in
@@ -853,6 +855,7 @@ def _is_unprocessed(c):
# apply to them as well.
if config.strict_blocking and diff.unchanged_alerts:
existing_before = list(diff.unchanged_alerts)
+ considered += existing_before
diff.unchanged_alerts = Comments.remove_alerts(comments, diff.unchanged_alerts)
ignored_alerts += [a for a in existing_before if a not in diff.unchanged_alerts]
# Emit telemetry per-comment so each event carries the comment author.
@@ -910,7 +913,16 @@ def _is_unprocessed(c):
# Mark ignore comments as processed with +1 reaction
if hasattr(scm, "handle_ignore_reactions"):
- scm.handle_ignore_reactions(comments)
+ # A kept alert stays in the comment, so only an ignore that changed something is acknowledged.
+ if any(a.kept_action_after_pull_request_ignore() is not None for a in considered):
+ scm.handle_ignore_reactions({**comments, "ignore": [
+ c for c in comments.get("ignore", [])
+ if _match_ignored_alerts_for_telemetry(
+ ignored_alerts, *Comments.get_ignore_options({"ignore": [c]})
+ )
+ ]})
+ else:
+ scm.handle_ignore_reactions(comments)
except Exception as e:
log.warning(f"Failed to send ignore telemetry: {e}")
else:
@@ -1100,7 +1112,13 @@ def _is_unprocessed(c):
parts.append(f"{unchanged_blocking} existing")
description = f"{blocking_count} blocking alert(s) found ({', '.join(parts)})"
target_url = diff.report_url or diff.diff_url or ""
- scm.set_commit_status(state, description, target_url)
+ if Comments.comment_keeps_blocks(security_comment_body):
+ log.info(
+ "Not setting the commit status: the merge request comment lists a Block alert "
+ "the policy keeps or lowers to Warn. The next pipeline run sets it."
+ )
+ else:
+ scm.set_commit_status(state, description, target_url)
sys.exit(output_handler.return_exit_code(diff))
diff --git a/tests/core/test_action_after_pull_request_ignore.py b/tests/core/test_action_after_pull_request_ignore.py
new file mode 100644
index 00000000..65f98f82
--- /dev/null
+++ b/tests/core/test_action_after_pull_request_ignore.py
@@ -0,0 +1,980 @@
+"""An ignore comment leaves what the organization's policy keeps.
+
+The API's ``actionAfterPullRequestIgnore`` says what an alert keeps when a pull or
+merge request comment ignores its package. These tests serve raw API JSON from a
+local HTTP server to the real SDK, so the alerts go through the SDK's parsing and
+the full-scan stream's dedupe before the CLI reads them.
+"""
+import functools
+import json
+import sys
+import threading
+from contextlib import nullcontext
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+from urllib.parse import urlsplit
+
+import pytest
+from requests.adapters import HTTPAdapter
+from socketdev import socketdev
+from socketdev.fullscans import FullScanParams
+
+from socketsecurity import socketcli
+from socketsecurity.config import CliConfig
+from socketsecurity.core import Core
+from socketsecurity.core.classes import Comment, Diff, Issue
+from socketsecurity.core.messages import Messages
+from socketsecurity.core.scm.github import Github
+from socketsecurity.core.scm.gitlab import Gitlab
+from socketsecurity.core.scm_comments import Comments
+from socketsecurity.core.socket_config import SocketConfig
+
+ORG = "acme"
+BUCKETS = ("added", "removed", "unchanged", "replaced", "updated")
+GOLDEN_DIR = Path(__file__).parent.parent / "data" / "comments"
+
+
+@pytest.fixture(autouse=True)
+def only_localhost(monkeypatch):
+ """Fail the test if anything sends a request off this machine, even when the CLI swallows the error."""
+ attempts = []
+ send = HTTPAdapter.send
+
+ def guarded(self, request, *args, **kwargs):
+ host = urlsplit(request.url).hostname
+ if host not in ("127.0.0.1", "localhost"):
+ attempts.append(request.url)
+ raise ConnectionRefusedError(f"test tried to reach {host}")
+ return send(self, request, *args, **kwargs)
+
+ monkeypatch.setattr(HTTPAdapter, "send", guarded)
+ yield
+ assert attempts == []
+
+
+class SocketApiStub:
+ def __init__(self):
+ self.routes = {}
+ self.requests = []
+ stub = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _serve(self):
+ path = urlsplit(self.path).path.removeprefix("/v0/")
+ length = int(self.headers.get("Content-Length") or 0)
+ if length:
+ self.rfile.read(length)
+ stub.requests.append((self.command, path))
+ status, body, content_type = stub.routes.get(
+ (self.command, path), (404, b'{"error": {"message": "not found"}}', "application/json")
+ )
+ self.send_response(status)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ do_GET = _serve
+ do_POST = _serve
+
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.base_url = f"http://127.0.0.1:{self.server.server_address[1]}/v0"
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+
+ def json(self, method, path, payload, status=200):
+ self.routes[(method, path)] = (status, json.dumps(payload).encode(), "application/json")
+
+ def ndjson(self, path, *records):
+ body = "\n".join(json.dumps(record) for record in records).encode()
+ self.routes[("GET", path)] = (200, body, "application/x-ndjson")
+
+ def sdk(self):
+ sdk = socketdev(token="synthetic-token", timeout=5)
+ sdk.api.api_url = self.base_url
+ return sdk
+
+
+@pytest.fixture
+def socket_api():
+ stub = SocketApiStub()
+ stub.thread.start()
+ stub.json("GET", "organizations", {"organizations": {"org-id": {"id": "org-id", "slug": ORG}}})
+ stub.json("POST", f"orgs/{ORG}/diff-scans/from-ids", {"diff_scan": {"id": "diff-1"}})
+ stub.json("GET", "report/supported", {"npm": {"packagejson": {"pattern": "package.json"}}})
+ yield stub
+ stub.server.shutdown()
+ stub.server.server_close()
+
+
+def _alert(key, alert_type="malware", action="error", after_ignore=None):
+ alert = {
+ "key": key,
+ "type": alert_type,
+ "severity": "critical",
+ "category": "supplyChainRisk",
+ "props": {},
+ "action": action,
+ }
+ if after_ignore is not None:
+ alert["actionAfterPullRequestIgnore"] = after_ignore
+ return alert
+
+
+def _artifact(diff_type, artifact_id, name, alerts=(), version="1.0.0"):
+ ref = {
+ "direct": True,
+ "manifestFiles": [{"file": "package.json", "start": 0, "end": 0}],
+ "topLevelAncestors": [],
+ }
+ removed = diff_type in ("removed", "replaced")
+ return {
+ "diffType": diff_type,
+ "type": "npm",
+ "name": name,
+ "version": version,
+ "id": artifact_id,
+ "head": [] if removed else [ref],
+ "base": [ref] if removed else [],
+ "license": "MIT",
+ "licenseDetails": [],
+ "author": [],
+ "size": 1,
+ "score": {},
+ "alerts": list(alerts),
+ }
+
+
+def _serve_diff_scan(socket_api, **buckets):
+ artifacts = {name: buckets.get(name, []) for name in BUCKETS}
+ socket_api.json("GET", f"orgs/{ORG}/diff-scans/diff-1", {"diff_scan": {"id": "diff-1", "artifacts": artifacts}})
+
+
+def _scan_artifact(artifact_id, name, release, alerts, version="1.0.0"):
+ return {
+ "id": artifact_id,
+ "type": "npm",
+ "name": name,
+ "version": version,
+ "release": release,
+ "inputPurl": f"pkg:npm/{name}@{version}",
+ "direct": True,
+ "manifestFiles": [{"file": "package.json"}],
+ "alerts": list(alerts),
+ }
+
+
+def _core(socket_api, *args):
+ core = Core(
+ config=SocketConfig(api_key="synthetic-token"),
+ sdk=socket_api.sdk(),
+ cli_config=CliConfig.from_args(["--api-token", "test", *args]),
+ )
+ core.resolve_base_full_scan_id = Mock(return_value="head")
+ core.create_full_scan = Mock(return_value=SimpleNamespace(id="new"))
+ return core
+
+
+def _diff(core):
+ params = FullScanParams(repo="repo", branch="feature")
+ params.include_license_details = True
+ return core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"])
+
+
+def _comment(body, comment_id=1):
+ return Comment(
+ id=comment_id,
+ body=body,
+ body_list=body.split("\n"),
+ reactions={"+1": 0},
+ user={"login": "maintainer", "id": 7},
+ )
+
+
+def _ignore(*bodies):
+ return Comments.check_for_socket_comments(
+ {i: _comment(body, i) for i, body in enumerate(bodies, start=1)}
+ )
+
+
+IGNORE_ALPHA = "@SocketSecurity ignore npm/alpha@1.0.0"
+IGNORE_ALL = "@SocketSecurity ignore-all"
+IGNORE_BETA = "@SocketSecurity ignore npm/beta@1.0.0"
+IGNORE_NO_MATCH = "@SocketSecurity ignore npm/nomatch@9.9.9"
+
+
+class TestIssuesFromTheApi:
+ def test_field_is_set_only_when_the_api_sends_it(self, socket_api):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [
+ _alert("k-kept", "malware", after_ignore="error"),
+ _alert("k-lowered", "didYouMean", after_ignore="warn"),
+ _alert("k-removed", "envVars"),
+ ])])
+
+ diff = _diff(_core(socket_api))
+
+ by_type = {alert.type: alert for alert in diff.new_alerts}
+ assert by_type["malware"].action_after_pull_request_ignore == "error"
+ assert by_type["didYouMean"].action_after_pull_request_ignore == "warn"
+ assert "action_after_pull_request_ignore" not in vars(by_type["envVars"])
+ assert ("GET", f"orgs/{ORG}/diff-scans/diff-1") in socket_api.requests
+
+ def test_payload_without_the_field_gives_the_same_issues(self, socket_api):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1")])])
+ without = _diff(_core(socket_api)).new_alerts
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="error")])])
+ with_field = _diff(_core(socket_api)).new_alerts
+
+ assert len(without) == len(with_field) == 1
+ kept = dict(vars(with_field[0]))
+ assert kept.pop("action_after_pull_request_ignore") == "error"
+ assert vars(without[0]) == kept
+
+ def test_sightings_consolidate_to_the_blocking_one_with_the_strictest_after_ignore(self, socket_api):
+ """A Block with no field and a Warn the ignore keeps end as a Block lowered to Warn."""
+ _serve_diff_scan(socket_api, added=[
+ _artifact("added", "a1", "alpha", [_alert("k1")]),
+ _artifact("added", "a2", "alpha", [_alert("k2", action="warn", after_ignore="warn")]),
+ ])
+
+ diff = _diff(_core(socket_api))
+
+ assert len(diff.new_alerts) == 1
+ alert = diff.new_alerts[0]
+ assert alert.error and not alert.warn
+ assert alert.action_after_pull_request_ignore == "warn"
+
+ [lowered] = Comments.remove_alerts(_ignore(IGNORE_ALPHA), diff.new_alerts)
+ assert lowered.warn and not lowered.error
+ assert alert.error
+
+ def test_streamed_full_scan_alerts_carry_the_field_through_the_sdk_dedupe(self, socket_api):
+ """--strict-blocking reads existing alerts from the full-scan stream."""
+ _serve_diff_scan(socket_api, unchanged=[_artifact("unchanged", "u1", "gamma")])
+ socket_api.ndjson(
+ f"orgs/{ORG}/full-scans/new",
+ _scan_artifact("u1", "gamma", "wheel", [_alert("k1")]),
+ _scan_artifact("u1", "gamma", "sdist", [_alert("k1", after_ignore="error")]),
+ )
+
+ diff = _diff(_core(socket_api, "--strict-blocking"))
+
+ assert ("GET", f"orgs/{ORG}/full-scans/new") in socket_api.requests
+ [existing] = diff.unchanged_alerts
+ assert existing.pkg_name == "gamma"
+ assert existing.action_after_pull_request_ignore == "error"
+ assert Comments.remove_alerts(_ignore(IGNORE_ALL), diff.unchanged_alerts) == [existing]
+
+ def test_streamed_diff_fallback_carries_the_field(self, socket_api):
+ socket_api.json("POST", f"orgs/{ORG}/diff-scans/from-ids", {"error": {"message": "boom"}}, status=500)
+ socket_api.json("GET", f"orgs/{ORG}/full-scans/diff", {
+ "before": {"id": "head", "repository_id": "r", "branch": "main", "organization_id": "o", "committers": []},
+ "after": {"id": "new", "repository_id": "r", "branch": "feature", "organization_id": "o", "committers": []},
+ "directDependenciesChanged": False,
+ "diff_report_url": "",
+ "artifacts": {name: [] for name in BUCKETS} | {
+ "added": [_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="warn")])],
+ },
+ })
+
+ diff = _diff(_core(socket_api))
+
+ assert ("GET", f"orgs/{ORG}/full-scans/diff") in socket_api.requests
+ assert [a.action_after_pull_request_ignore for a in diff.new_alerts] == ["warn"]
+
+
+def _issue_with(after_ignore=None, *, error=True, warn=False, name="alpha"):
+ issue = Issue(
+ pkg_type="npm", pkg_name=name, pkg_version="1.0.0", type="malware",
+ purl=f"{name}@1.0.0", key=f"k-{name}", error=error, warn=warn,
+ )
+ if after_ignore is not None:
+ issue.action_after_pull_request_ignore = after_ignore
+ return issue
+
+
+class TestRemoveAlerts:
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_absent_and_monitor_are_removed(self, command):
+ assert Comments.remove_alerts(_ignore(command), [_issue_with(), _issue_with("monitor")]) == []
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_kept_block_is_the_same_object(self, command):
+ alert = _issue_with("error")
+ [kept] = Comments.remove_alerts(_ignore(command), [alert])
+ assert kept is alert
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_block_lowered_to_warn_is_a_copy(self, command):
+ alert = _issue_with("warn")
+ [lowered] = Comments.remove_alerts(_ignore(command), [alert])
+ assert lowered is not alert
+ assert (lowered.error, lowered.warn) == (False, True)
+ assert (alert.error, alert.warn) == (True, False)
+ assert lowered != alert
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_warn_that_stays_warn_is_the_same_object(self, command):
+ alert = _issue_with("warn", error=False, warn=True)
+ [kept] = Comments.remove_alerts(_ignore(command), [alert])
+ assert kept is alert
+
+ def test_unmatched_alerts_are_untouched(self):
+ other = _issue_with(name="beta")
+ assert Comments.remove_alerts(_ignore(IGNORE_ALPHA), [other]) == [other]
+
+ def test_ignore_all_without_the_field_logs_nothing_per_alert(self, caplog):
+ with caplog.at_level("INFO", logger="socketcli"):
+ Comments.remove_alerts(_ignore(IGNORE_ALL), [_issue_with(), _issue_with(name="beta")])
+ assert not [r for r in caplog.records if "alpha" in r.getMessage() or "beta" in r.getMessage()]
+
+
+def _run_pull_request(monkeypatch, socket_api, *commands, extra_args=()):
+ """A pull request run; ignore comments get ids 1, 2, ..."""
+ argv = [
+ "socketcli", "--api-token", "test", "--scm", "github",
+ "--repo", "repo", "--branch", "feature", "--pr-number", "42",
+ "--files", '["package.json"]', *extra_args,
+ ]
+ monkeypatch.setattr(sys, "argv", argv)
+ for key, value in {
+ "GH_API_TOKEN": "test", "GITHUB_EVENT_NAME": "pull_request",
+ "EVENT_ACTION": "synchronize", "GITHUB_REPOSITORY": "acme/repo",
+ "DEFAULT_BRANCH": "false",
+ }.items():
+ monkeypatch.setenv(key, value)
+
+ raw_comments = {i: _comment(body, i) for i, body in enumerate(commands, start=1)}
+ raw_comments[100] = _comment("", comment_id=100)
+ monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: Comments.check_for_socket_comments(
+ raw_comments, is_authorized=lambda comment: True,
+ ))
+ posted = Mock()
+ monkeypatch.setattr(Github, "add_socket_comments", posted)
+ monkeypatch.setattr(Github, "comment_reaction_exists", Mock(return_value=False))
+ reaction = Mock()
+ monkeypatch.setattr(Github, "post_reaction", reaction)
+ monkeypatch.setenv("RUN_ENVIRONMENT", "dev")
+ monkeypatch.setattr(socketcli, "SocketConfig", functools.partial(SocketConfig, api_url=socket_api.base_url))
+ monkeypatch.setattr(socketcli, "build_socket_sdk", lambda config: socket_api.sdk())
+ client = Mock()
+ monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=client))
+ monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()))
+ monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
+ monkeypatch.setattr(socketcli.Core, "resolve_base_full_scan_id", Mock(return_value="head"))
+ monkeypatch.setattr(socketcli.Core, "create_full_scan", Mock(return_value=SimpleNamespace(id="new")))
+ monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True))
+ handle_output = Mock()
+ monkeypatch.setattr(socketcli.OutputHandler, "handle_output", handle_output)
+
+ with pytest.raises(SystemExit) as result:
+ socketcli.cli()
+
+ events = client.post_telemetry_events.call_args.args[1] if client.post_telemetry_events.called else []
+ return SimpleNamespace(
+ code=result.value.code,
+ events=events,
+ reacted=[call.args[0] for call in reaction.call_args_list],
+ new_alerts=handle_output.call_args.args[0].new_alerts,
+ security_comment=posted.call_args.args[0] if posted.called else None,
+ )
+
+
+class TestPullRequestRun:
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_without_the_field_the_ignore_removes_the_block(self, monkeypatch, socket_api, command):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1")])])
+
+ run = _run_pull_request(monkeypatch, socket_api, command)
+
+ assert run.code == 0
+ assert run.new_alerts == []
+ assert [e["alert_action"] for e in run.events] == ["error"]
+ assert run.reacted
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_kept_block_fails_and_is_not_counted_as_ignored(self, monkeypatch, socket_api, command):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="error")])])
+
+ run = _run_pull_request(monkeypatch, socket_api, command)
+
+ assert run.code == 1
+ assert [(a.error, a.warn) for a in run.new_alerts] == [(True, False)]
+ assert run.events == []
+ assert not run.reacted
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_block_lowered_to_warn_passes_and_counts_as_ignored(self, monkeypatch, socket_api, command):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="warn")])])
+
+ run = _run_pull_request(monkeypatch, socket_api, command)
+
+ assert run.code == 0
+ assert [(a.error, a.warn) for a in run.new_alerts] == [(False, True)]
+ assert [e["alert_action"] for e in run.events] == ["error"]
+ assert run.reacted
+
+ def test_monitor_after_ignore_is_removed(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="monitor")])])
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALPHA)
+
+ assert run.code == 0
+ assert run.new_alerts == []
+ assert [e["alert_action"] for e in run.events] == ["error"]
+
+ @pytest.mark.parametrize("command", [IGNORE_ALPHA, IGNORE_ALL])
+ def test_warn_that_stays_warn_is_not_counted_as_ignored(self, monkeypatch, socket_api, command):
+ _serve_diff_scan(socket_api, added=[
+ _artifact("added", "a1", "alpha", [_alert("k1", action="warn", after_ignore="warn")]),
+ ])
+
+ run = _run_pull_request(monkeypatch, socket_api, command)
+
+ assert run.code == 0
+ assert [(a.error, a.warn) for a in run.new_alerts] == [(False, True)]
+ assert run.events == []
+ assert not run.reacted
+
+ def test_only_an_ignore_that_changed_an_alert_gets_a_reaction(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, added=[
+ _artifact("added", "a1", "alpha", [_alert("k1", after_ignore="error")]),
+ _artifact("added", "a2", "beta", [_alert("k2")]),
+ ])
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALPHA, IGNORE_BETA)
+
+ assert run.code == 1
+ assert run.reacted == [2]
+ assert [e["artifact_purl"] for e in run.events] == ["beta@1.0.0"]
+
+ def test_ignore_all_that_changed_an_alert_gets_a_reaction(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, added=[
+ _artifact("added", "a1", "alpha", [_alert("k1", after_ignore="error")]),
+ _artifact("added", "a2", "beta", [_alert("k2")]),
+ ])
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALL)
+
+ assert run.reacted == [1]
+
+ def test_ignore_of_a_lowered_block_gets_a_reaction(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="warn")])])
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALPHA, IGNORE_NO_MATCH)
+
+ assert run.code == 0
+ assert run.reacted == [1]
+ assert [e["artifact_purl"] for e in run.events] == ["alpha@1.0.0"]
+
+ def test_strict_blocking_keeps_an_existing_block(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, unchanged=[_artifact("unchanged", "u1", "alpha")])
+ socket_api.ndjson(
+ f"orgs/{ORG}/full-scans/new",
+ _scan_artifact("u1", "alpha", "wheel", [_alert("k1", after_ignore="error")]),
+ )
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALPHA, extra_args=("--strict-blocking",))
+
+ assert run.code == 1
+ assert run.events == []
+
+ def test_strict_blocking_without_the_field_removes_an_existing_block(self, monkeypatch, socket_api):
+ _serve_diff_scan(socket_api, unchanged=[_artifact("unchanged", "u1", "alpha")])
+ socket_api.ndjson(f"orgs/{ORG}/full-scans/new", _scan_artifact("u1", "alpha", "wheel", [_alert("k1")]))
+
+ run = _run_pull_request(monkeypatch, socket_api, IGNORE_ALPHA, extra_args=("--strict-blocking",))
+
+ assert run.code == 0
+ assert [e["alert_action"] for e in run.events] == ["error"]
+
+
+def _license(key, action="error", after_ignore=None):
+ alert = _alert(key, "licenseSpdxDisj", action=action, after_ignore=after_ignore)
+ alert["category"] = "license"
+ alert["severity"] = "low"
+ return alert
+
+
+def _render(socket_api, *args, **buckets):
+ _serve_diff_scan(socket_api, **buckets)
+ core = _core(socket_api, *args)
+ diff = _diff(core)
+ diff.diff_url = "https://socket.dev/dashboard/org/acme/diff/head/new"
+ return Messages.security_comment_template(diff, core.cli_config), diff
+
+
+def _v1_comments(socket_api):
+ """Payloads without the field; their comments must match what main renders."""
+ small, _ = _render(
+ socket_api, "--strict-blocking",
+ added=[
+ _artifact("added", "a1", "alpha", [_alert("k1"), _alert("k2", "didYouMean", action="warn")]),
+ _artifact("added", "a2", "lic", [_license("k3"), _license("k4", action="warn")]),
+ ],
+ unchanged=[_artifact("unchanged", "u1", "gamma", [_alert("k5")])],
+ )
+ truncated, _ = _render(
+ socket_api,
+ added=[_artifact("added", f"a{i}", f"pkg{i}", [_alert(f"k{i}")]) for i in range(60)]
+ + [_artifact("added", "lic", "lic", [_license("k-lic")])],
+ )
+ return {
+ "v1_security_comment.html": small,
+ "v1_truncated_security_comment.html": truncated,
+ "v1_security_comment_after_named_ignore.html": _process(small, IGNORE_ALPHA),
+ "v1_truncated_security_comment_after_ignore_all.html": _process(truncated, IGNORE_ALL),
+ }
+
+
+def _section(body, marker):
+ start = body.index(f"")
+ end = body.index(f"", start)
+ return body[start:end]
+
+
+def _security(body):
+ return _comment(body, comment_id=100)
+
+
+def _process(body, command):
+ security = _security(body)
+ comments = Comments.check_for_socket_comments({100: security, 1: _comment(command, 1)})
+ return Comments.process_security_comment(security, comments)
+
+
+class TestPullRequestComment:
+ def test_comment_without_the_field_matches_main(self, socket_api):
+ """The golden files are regenerated from main's code, never from this branch's."""
+ for name, body in _v1_comments(socket_api).items():
+ assert body == (GOLDEN_DIR / name).read_text(), name
+ assert Messages.NEW_ALERTS_TRUNCATED_MARKER in (GOLDEN_DIR / "v1_truncated_security_comment.html").read_text()
+
+ def test_kept_block_has_its_own_marker_and_no_ignore_line(self, socket_api):
+ body, _ = _render(socket_api, added=[_artifact("added", "a1", "alpha", [_alert("k1", after_ignore="error")])])
+
+ section = _section(body, Messages.KEPT_ERROR_ALERT_MARKER)
+ assert "
| Action | +Severity | +Alert (click for details) | +
|---|---|---|
| Block | +
+ |
+
+
+
+ alpha@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Warn | +
+ |
+
+
+
+ alpha@1.0.0 - Possible typosquat attack+Note: Package name is similar to other popular packages and may not be the package you want. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +🔶 | +
+
+
+ lic@1.0.0 has a License Policy Violation.+License findings: +
From: Manifest File +ℹ️ Read more on: This package | What is a license policy violation? +++ |
+
| Action | +Severity | +Alert (click for details) | +
|---|---|---|
| Block | +
+ |
+
+
+
+ gamma@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Action | +Severity | +Alert (click for details) | +
|---|---|---|
| Block | +🔶 | +
+
+
+ lic@1.0.0 has a License Policy Violation.+License findings: +
From: Manifest File +ℹ️ Read more on: This package | What is a license policy violation? +++ |
+
| Action | +Severity | +Alert (click for details) | +
|---|---|---|
| Block | +
+ |
+
+
+
+ gamma@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Action | +Severity | +Alert (click for details) | +
|---|---|---|
| Block | +
+ |
+
+
+
+ pkg0@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg1@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg2@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg3@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg4@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg5@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg6@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg7@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg8@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg9@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg10@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg11@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg12@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg13@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg14@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg15@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg16@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg17@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg18@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg19@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg20@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg21@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg22@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg23@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg24@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg25@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg26@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg27@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg28@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg29@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg30@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg31@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg32@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg33@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg34@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg35@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg36@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg37@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg38@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg39@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg40@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg41@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg42@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg43@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg44@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg45@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+
| Block | +
+ |
+
+
+
+ pkg46@1.0.0 - Known malware+Note: This package is malware. We have asked the package registry to remove it. +Source: Manifest File +ℹ️ Read more on: + This package | + What is known malware? +++ |
+