diff --git a/CHANGELOG.md b/CHANGELOG.md index fdd5c26..e7d7f13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,14 @@ review run the PR scan. - GitHub pull request comment runs exit `0` and leave the Socket security comment unchanged when there are no Socket ignore commands to process. +- Under `--strict-blocking --disable-blocking`, the PR/MR comment and console + summary no longer say that existing Block alerts fail the run. +- The "This package" link in GitHub and GitLab security comments opens the + affected package version on socket.dev. License findings for different + namespaces appear in separate rows, and generated ignore commands identify + the package by its scope or namespace. +- Large PR/MR security comments fit within GitHub's size limit and show how many + new or existing findings were omitted. Policy checks and reports use all findings. ### Documentation diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3824cb2..29939bd 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -664,7 +664,16 @@ Security issues detected by Socket Security: - **With `--reach`**. With no explicit baseline, the CLI looks for a default-branch head scan with reachability enabled. If none exists, the CLI compares against an empty baseline and classifies all findings as new. Scan the default branch with `--reach` too. - **Policy actions**. Warn findings are reported. If the same finding has both Warn and Block actions, Block takes precedence. - **Existing alerts come from the full scan**. The CLI fetches the current full scan when the comparison leaves out alerts on unchanged packages or when a dependency version changes. A failed fetch or a missing package in that response triggers the infrastructure-error exit code. -- **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first, with license violations grouped per package. `@SocketSecurity ignore` applies to them too. Very large sets are cut off before the comment reaches GitHub's size limit, with a link to the full report. Ignoring every displayed alert preserves the warning about omitted findings; `ignore-all` also clears omitted findings. +- **PR/MR comments**. The comment lists new alerts first, then existing alerts + with Block findings first in the existing-alerts table. License findings are + grouped by package, including its scope or namespace. **This package** opens + the affected version on socket.dev. Use the generated `@SocketSecurity ignore` + command to target the package's exact scope or namespace. +- **Comment size**. Large comments show how many new and existing alerts were + omitted to fit GitHub's size limit and link to the full report. + Policy checks and reports still use all findings. If you ignore every visible + alert, the comment keeps the omission notice. Use `@SocketSecurity ignore-all` + to clear all findings, including omitted ones. - **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass. - **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode. diff --git a/socketsecurity/core/classes.py b/socketsecurity/core/classes.py index 92e9eea..bdea4b4 100644 --- a/socketsecurity/core/classes.py +++ b/socketsecurity/core/classes.py @@ -359,6 +359,13 @@ def __init__(self, **kwargs): if not hasattr(self, "ignore"): self.ignore = False + def package_name_with_namespace(self) -> str: + """Read the name from the CLI's `[namespace/]name@version` coordinate.""" + name, _, _ = (getattr(self, "purl", "") or "").rpartition("@") + if name and not name.startswith("pkg:"): + return name + return self.pkg_name + def advisory_id(self) -> str: """The preferred GHSA or CVE identifier, upper-cased, or "". diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index ee0e382..3b475de 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -964,6 +964,14 @@ def get_view_report_url(diff: Diff) -> str: return diff.report_url return "" + QUALIFIED_ALERT_MARKER_PREFIX = "package:" + + @staticmethod + def alert_package_marker(alert: Issue, coordinate: str) -> str: + if coordinate != f"{alert.pkg_name}@{alert.pkg_version}": + coordinate = f"{Messages.QUALIFIED_ALERT_MARKER_PREFIX}{alert.pkg_type}/{coordinate}" + return Messages.comment_marker_text(coordinate) + @staticmethod def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> str: """One row of the security comment table for a package's license policy violations.""" @@ -974,12 +982,9 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st # Use orange diamond for license policy violations license_icon = "🔶" - license_label = Messages.html_text( - f"{first_alert.pkg_name}@{first_alert.pkg_version}" - ) - license_marker = Messages.comment_marker_text( - f"{first_alert.pkg_name}@{first_alert.pkg_version}" - ) + 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) # Build license findings list license_findings = [] @@ -1005,7 +1010,7 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st license_manifest_url = Messages.get_manifest_file_url(diff, first_alert.manifests, config) license_ignore_html = ( - f"

Mark the package as acceptable risk: To ignore this alert only in this pull request, reply with the comment " + f"

Mark the package as acceptable risk: To ignore findings for this package version in this pull request, reply with " f"@SocketSecurity ignore {Messages.html_text(first_alert.pkg_type)}/{license_label}. " f"You can also ignore all packages with @SocketSecurity ignore-all. " f"To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

" @@ -1013,7 +1018,7 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st row += f"""

From: Manifest File

{Messages.introduced_by_html(first_alert)} -

ℹ️ Read more on: This package | What is a license policy violation?

+

ℹ️ Read more on: This package | What is a license policy violation?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: Find a package that does not violate your license policy or adjust your policy to allow this package's license.

@@ -1040,8 +1045,9 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s ) # Generate proper manifest URL manifest_url = Messages.get_manifest_file_url(diff, alert.manifests, config) - pkg_label = Messages.html_text(f"{alert.pkg_name}@{alert.pkg_version}") - pkg_marker = Messages.comment_marker_text(f"{alert.pkg_name}@{alert.pkg_version}") + package = f"{alert.package_name_with_namespace()}@{alert.pkg_version}" + pkg_label = Messages.html_text(package) + pkg_marker = Messages.alert_package_marker(alert, package) 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:
" @@ -1064,8 +1070,7 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s

Source: Manifest File

{Messages.introduced_by_html(alert)}

ℹ️ Read more on: - This package | - This alert | + This package | What is known malware?

Suggestion: {Messages.html_text(alert.suggestion)}

@@ -1092,36 +1097,13 @@ def alert_title_with_advisory(alert: Issue) -> str: @staticmethod def security_comment_template(diff: Diff, config=None) -> str: - """ - Generates the security comment template in the new required format. - Dynamically determines placement of the alerts table if markers like `` are used. - - :param diff: Diff - Contains the detected vulnerabilities and warnings. - :param config: Optional configuration object to determine SCM type. - :return: str - The formatted Markdown/HTML string. - """ - # Group license policy violations by PURL (ecosystem/package@version) - license_groups = {} - security_alerts = [] - - for alert in diff.new_alerts: - if alert.type == "licenseSpdxDisj": - purl_key = f"{alert.pkg_type}/{alert.pkg_name}@{alert.pkg_version}" - if purl_key not in license_groups: - license_groups[purl_key] = [] - license_groups[purl_key].append(alert) - else: - security_alerts.append(alert) - + """Render the PR/MR security comment within the provider's size limit.""" view_report_url = Messages.get_view_report_url(diff) + new_alerts = diff.new_alerts existing_alerts = Messages.existing_comment_alerts(diff, config) - - # Without this the caution banner would sit above a table with no rows, - # which is how a comment looks once every alert it raised is resolved. - if not security_alerts and not license_groups and not existing_alerts: + if not new_alerts and not existing_alerts: return Messages.security_comment_no_alerts_template(view_report_url) - # Start of the comment comment = """ > **❗️ Caution** @@ -1131,7 +1113,8 @@ def security_comment_template(diff: Diff, config=None) -> str: > Learn more about [Socket](https://socket.dev). - +""" + table_open = """
@@ -1139,49 +1122,95 @@ def security_comment_template(diff: Diff, config=None) -> str: - - """ - - show_ignore = not (config and getattr(config, 'disable_ignore', False)) - - # Loop through security alerts (non-license), dynamically generating rows - for alert in security_alerts: - comment += Messages.security_alert_row(alert, diff, config, show_ignore) - - # Add license policy violation entries grouped by PURL - for purl_key, alerts in license_groups.items(): - comment += Messages.license_group_row(alerts, diff, config, show_ignore) - - if not security_alerts and not license_groups: - comment += """ + """ + table_close = """ + +
ActionAlert (click for details)
+""" + new_header = comment + table_open + new_footer = table_close + "\n" + if not new_alerts: + new_header += """ No new alerts in this change. """ - - # Close table - comment += """ - - - -""" + existing_header = existing_footer = "" if existing_alerts: - comment += Messages.existing_alerts_section( - existing_alerts, diff, config, show_ignore, view_report_url, len(comment) - ) + existing_header = f""" + +**Existing alerts ({len(existing_alerts)}).** The baseline also contains these findings. {Messages.existing_alerts_effect(existing_alerts, config)} - comment += f""" -[View full report]({view_report_url}?action=error%2Cwarn) - """ +{table_open}""" + existing_footer = table_close + "\n" - return Messages.normalize_comment_html(comment) + # 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)), + ) + 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 "" + report_link_size = len(report_link.encode()) + if report_link_size > budget: + report_link = "" + 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( + 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) + + existing_header + existing_rows + existing_footer + + Messages.omitted_comment_alerts("existing", len(existing_alerts) - existing_count) + + report_link + ) - # GitHub rejects comment bodies over 65,536 characters. The existing-alerts - # section is the open-ended part of the security comment, so it stops adding - # rows at this size and links to the full report for the rest. + # Use UTF-8 bytes so multibyte text counts toward the comment size budget. SECURITY_COMMENT_SIZE_BUDGET = 60000 + NEW_ALERTS_TRUNCATED_MARKER = "" EXISTING_ALERTS_TRUNCATED_MARKER = "" + @staticmethod + def omitted_comment_alerts(section: str, count: int) -> str: + if not count: + return "" + marker = ( + Messages.NEW_ALERTS_TRUNCATED_MARKER if section == "new" + else Messages.EXISTING_ALERTS_TRUNCATED_MARKER + ) + return ( + f"\n{marker}\n\n{count} more {section} alert(s) are not shown here " + "to keep this comment within GitHub's size limit.\n" + ) + + @staticmethod + def existing_alerts_effect(existing_alerts: list, config) -> str: + """Say whether the existing alerts fail this run. + + Under ``--disable-blocking`` they are listed but don't change the exit code, + so the comment must not claim they fail the run. + """ + blocking = sum(1 for alert in existing_alerts if alert.error) + if not blocking: + return "None has a **Block** action, so they don't fail the run." + if getattr(config, "disable_blocking", False): + verb = "has" if blocking == 1 else "have" + return ( + f"{blocking} {verb} a **Block** action but don't fail the run, " + "because `--disable-blocking` is set." + ) + return f"`--strict-blocking` fails the run on the {blocking} with a **Block** action." + @staticmethod def existing_comment_alerts(diff: Diff, config) -> list: """Existing alerts to show in the PR comment. @@ -1198,64 +1227,42 @@ def existing_comment_alerts(diff: Diff, config) -> list: ] @staticmethod - def existing_alerts_section( - alerts: list, diff: Diff, config, show_ignore: bool, view_report_url: str, size_so_far: int - ) -> str: - """Table of existing alerts, with blocking alerts first. - - License policy violations are grouped per package, as in the table of new - alerts. - """ + def comment_alert_groups(alerts: list) -> list: + """Group license findings by package, keeping each security alert in its own row.""" entries = [] license_groups: dict = {} for alert in alerts: if alert.type == "licenseSpdxDisj": - purl_key = f"{alert.pkg_type}/{alert.pkg_name}@{alert.pkg_version}" + coordinate = getattr(alert, "purl", "") or f"{alert.pkg_name}@{alert.pkg_version}" + purl_key = (alert.pkg_type, coordinate) if purl_key not in license_groups: license_groups[purl_key] = [] entries.append(license_groups[purl_key]) license_groups[purl_key].append(alert) else: entries.append([alert]) - entries.sort(key=lambda group: not any(alert.error for alert in group)) + return entries - blocking = sum(1 for alert in alerts if alert.error) - section = f""" - -**Existing alerts ({len(alerts)}).** The baseline also contains these findings. `--strict-blocking` fails the run on the {blocking} with a **Block** action. - - - - - - - - - - -""" - closing = """ - -
ActionSeverityAlert (click for details)
-""" + @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.""" + show_ignore = not (config and getattr(config, "disable_ignore", False)) + rows = [] shown = 0 - for group in entries: + for group in groups: + if budget <= 0: + break 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) - if size_so_far + len(section) + len(row) + len(closing) > Messages.SECURITY_COMMENT_SIZE_BUDGET: + row_size = len(row.encode()) + if row_size > budget: break - section += row + rows.append(row) + budget -= row_size shown += len(group) - section += closing - if shown < len(alerts): - section += ( - f"\n{Messages.EXISTING_ALERTS_TRUNCATED_MARKER}\n" - f"\n{len(alerts) - shown} more existing alert(s) are not shown here to keep " - f"this comment within GitHub's size limit. See the [full report]({view_report_url}?action=error%2Cwarn).\n" - ) - return section + "\n" + return "".join(rows), shown @staticmethod def get_severity_icon(severity: str) -> str: diff --git a/socketsecurity/core/scm_comments.py b/socketsecurity/core/scm_comments.py index 66826a6..0ddb922 100644 --- a/socketsecurity/core/scm_comments.py +++ b/socketsecurity/core/scm_comments.py @@ -45,7 +45,7 @@ def remove_alerts(comments: dict, new_alerts: list) -> list: break else: if any( - Comments.is_ignore(alert.pkg_name, alert.pkg_version, name, version, alert.pkg_type) + Comments.matches_issue(alert, name, version) for name, version in ignore_commands ): log.info(f"Alerts for {alert.pkg_name}@{alert.pkg_version} ignored") @@ -83,6 +83,13 @@ def get_ignore_options(comments: dict) -> [bool, list]: log.error(error) return ignore_all, ignore_commands + @staticmethod + def matches_issue(alert: Issue, name: str, version: str) -> bool: + return any( + Comments.is_ignore(package_name, alert.pkg_version, name, version, alert.pkg_type) + for package_name in {alert.pkg_name, alert.package_name_with_namespace()} + ) + @staticmethod def is_ignore( pkg_name: str, pkg_version: str, name: str, version: str, @@ -234,9 +241,12 @@ def process_updated_security_comment( # 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( - Messages.EXISTING_ALERTS_TRUNCATED_MARKER in line for line in comment.body_list + line.strip() in ( + Messages.NEW_ALERTS_TRUNCATED_MARKER, + Messages.EXISTING_ALERTS_TRUNCATED_MARKER, + ) + for line in comment.body_list ) - pkg_name = pkg_version = "" # Track current package and version # Loop through the comment lines for line in comment.body_list: @@ -247,18 +257,8 @@ 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) # If not ignored, include this start marker if not ignore_section: @@ -284,6 +284,23 @@ def process_updated_security_comment( return Messages.normalize_comment_html("\n".join(lines)) + @staticmethod + def matches_alert_marker(marker: str, ignore_commands: list[tuple[str, str]]) -> bool: + coordinate, separator, pkg_version = marker.rpartition("@") + if not separator: + return False + prefix = Messages.QUALIFIED_ALERT_MARKER_PREFIX + if coordinate.startswith(prefix): + pkg_type, _, pkg_name = coordinate.removeprefix(prefix).partition("/") + names = {pkg_name, pkg_name.rsplit("/", 1)[-1]} + else: + pkg_type, names = "", {coordinate} + return any( + Comments.is_ignore(pkg_name, pkg_version, name, version, pkg_type) + for name, version in ignore_commands + for pkg_name in names + ) + @staticmethod def extract_alert_details_from_row(row: str, ignore_all: bool, ignore_commands: list[tuple[str, str]]) -> tuple: """ diff --git a/socketsecurity/output.py b/socketsecurity/output.py index 566e4d3..e3a5b03 100644 --- a/socketsecurity/output.py +++ b/socketsecurity/output.py @@ -276,9 +276,12 @@ def build_summary_text(self, diff_report: Diff) -> str: if new_warning > 0: lines.append(f" - {warning_label}: {new_warning}") if unchanged_blocking > 0: - lines.append( - f" - EXISTING blocking issues: {unchanged_blocking} (causing failure due to --strict-blocking)" + reason = ( + "not failing the run: --disable-blocking is set" + if getattr(self.config, "disable_blocking", False) + else "causing failure due to --strict-blocking" ) + lines.append(f" - EXISTING blocking issues: {unchanged_blocking} ({reason})") if unchanged_warning > 0: lines.append(f" - EXISTING warning issues: {unchanged_warning}") if is_full_scan: diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py index ce48e22..f7e3a29 100644 --- a/socketsecurity/socketcli.py +++ b/socketsecurity/socketcli.py @@ -160,13 +160,7 @@ def _match_ignored_alerts_for_telemetry( alert for alert in ignored_alerts if any( - Comments.is_ignore( - alert.pkg_name, - alert.pkg_version, - name, - version, - alert.pkg_type, - ) + Comments.matches_issue(alert, name, version) for name, version in ignore_commands ) ] diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index 33a4e5f..d184c6c 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -579,20 +579,52 @@ def test_pr_comment_stays_within_the_size_budget(monkeypatch): comment = Messages.security_comment_template(diff, _config()) - assert len(comment) < 6500 + assert len(comment.encode()) <= Messages.SECURITY_COMMENT_SIZE_BUDGET assert "more existing alert(s) are not shown" in comment assert "Existing alerts (20)" in comment -@pytest.mark.parametrize("budget", [6000, 1]) +def test_existing_comment_truncation_keeps_the_blocking_first_order(monkeypatch): + monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000) + large_blocker = _issue("large-blocker") + large_blocker.description = "é" * 3000 + diff = _comment_diff(existing=[ + _issue("later-warning", error=False, warn=True), + _issue("first-blocker"), + large_blocker, + ]) + + comment = Messages.security_comment_template(diff, _config()) + + assert "first-blocker@1.0.0" in comment + assert "large-blocker@1.0.0" not in comment + assert "later-warning@1.0.0" not in comment + assert "2 more existing alert(s) are not shown" in comment + assert "[View full report](https://socket.dev/diff?action=error%2Cwarn)" in comment + + +def test_omitted_existing_blocker_still_fails_strict_blocking(monkeypatch): + monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000) + new = [_issue(f"new-{index}", error=False, warn=True) for index in range(20)] + diff = _comment_diff(new=new, existing=[_issue("existing-blocker")]) + diff.unchanged_alerts[0].description = "é" * 3000 + + comment = Messages.security_comment_template(diff, _config()) + + assert Messages.EXISTING_ALERTS_TRUNCATED_MARKER in comment + assert "existing-blocker@1.0.0" not in comment + assert _handler().return_exit_code(diff) == 1 + assert _handler(strict_blocking=False).return_exit_code(diff) == 0 + + +@pytest.mark.parametrize("budget", [6000, 1500]) def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budget): monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", budget) diff = _comment_diff(existing=[_issue(f"pkg{i}") for i in range(20)]) body = Messages.security_comment_template(diff, _config()) visible = re.findall(r"", body) assert len(visible) < len(diff.unchanged_alerts) - if budget > 1: - assert visible + assert bool(visible) == (budget == 6000) comments = {"ignore": [ Comment(body_list=[f"@SocketSecurity ignore npm/{package}"]) for package in visible @@ -603,7 +635,7 @@ def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budge assert "No dependency alerts to report" not in updated assert "more existing alert(s) are not shown" in updated - assert "[full report](https://socket.dev/diff?action=error%2Cwarn)" in updated + assert "[View full report](https://socket.dev/diff?action=error%2Cwarn)" in updated # Reprocessing the comment must not lose the undisplayed findings either. assert Comments.process_security_comment(Comment(body_list=updated.splitlines()), comments) == updated diff --git a/tests/unit/test_comment_package_links.py b/tests/unit/test_comment_package_links.py new file mode 100644 index 0000000..68c1a73 --- /dev/null +++ b/tests/unit/test_comment_package_links.py @@ -0,0 +1,222 @@ +"""Package links and size limits in security comments rendered from diff artifacts.""" + +import re +from dataclasses import dataclass +from types import SimpleNamespace + +import pytest + +from socketsecurity.core import Core +from socketsecurity.core.classes import Comment, Diff, Package +from socketsecurity.core.messages import Messages +from socketsecurity.core.scm_comments import Comments + + +@dataclass +class _FakeConfig: + disable_ignore: bool = False + scm: str = "github" + strict_blocking: bool = True + + +ECOSYSTEMS = { + "npm": ( + dict(type="npm", name="handlebars", version="4.0.11"), + "https://socket.dev/npm/package/handlebars/overview/4.0.11", + ), + "npm-scoped": ( + dict(type="npm", namespace="@babel", name="traverse", version="7.22.5"), + "https://socket.dev/npm/package/@babel/traverse/overview/7.22.5", + ), + "pypi": ( + dict(type="pypi", name="django", version="2.2"), + "https://socket.dev/pypi/package/django/overview/2.2", + ), + "maven": ( + dict(type="maven", namespace="org.apache.logging.log4j", name="log4j-core", version="2.14.1"), + "https://socket.dev/maven/package/org.apache.logging.log4j/log4j-core/overview/2.14.1", + ), + "golang": ( + dict(type="golang", namespace="github.com/gin-gonic", name="gin", version="v1.6.0"), + "https://socket.dev/golang/package/github.com/gin-gonic/gin/overview/v1.6.0", + ), + "nuget": ( + dict(type="nuget", name="Newtonsoft.Json", version="12.0.1"), + "https://socket.dev/nuget/package/Newtonsoft.Json/overview/12.0.1", + ), + "gem": ( + dict(type="gem", name="rails", version="5.2.0"), + "https://socket.dev/gem/package/rails/overview/5.2.0", + ), + "cargo": ( + dict(type="cargo", name="smallvec", version="0.6.9"), + "https://socket.dev/cargo/package/smallvec/overview/0.6.9", + ), +} + +CVE_ALERT = {"type": "criticalCVE", "key": "cve-key", "severity": "critical", "action": "error"} +LICENSE_ALERT = {"type": "licenseSpdxDisj", "key": "license-key", "severity": "low", "action": "error"} + + +def _issues(artifact: dict, alert: dict) -> list: + package = Package.from_diff_artifact({ + "id": f"{artifact['type']}-{artifact['name']}", + "score": {}, + "topLevelAncestors": [], + "direct": True, + "manifestFiles": [{"file": "manifest"}], + "alerts": [alert], + **artifact, + }) + package = Core.update_package_values(package) + core = Core.__new__(Core) + core.config = SimpleNamespace(all_issues=SimpleNamespace()) + collection = core.add_package_alerts_to_collection(package, {}, {package.id: package}) + return collection[alert["key"]] + + +def _this_package_hrefs(body: str) -> list: + return re.findall(r'This package', body) + + +def _diff(alerts: list) -> Diff: + diff = Diff() + diff.id = "scan" + diff.diff_url = "https://socket.dev/dashboard/org/acme/diff/abc" + diff.new_alerts = alerts + diff.unchanged_alerts = [] + return diff + + +@pytest.mark.parametrize("ecosystem", ECOSYSTEMS) +def test_alert_row_links_the_package_page(ecosystem): + artifact, expected = ECOSYSTEMS[ecosystem] + alerts = _issues(artifact, CVE_ALERT) + + body = Messages.security_comment_template(_diff(alerts), _FakeConfig()) + + assert _this_package_hrefs(body) == [expected] + assert body.count(f'href="{expected}"') == 1 + + +@pytest.mark.parametrize("ecosystem", ECOSYSTEMS) +def test_license_row_links_the_package_page(ecosystem): + artifact, expected = ECOSYSTEMS[ecosystem] + alerts = _issues(artifact, LICENSE_ALERT) + + body = Messages.security_comment_template(_diff(alerts), _FakeConfig()) + + assert _this_package_hrefs(body) == [expected] + + +@pytest.mark.parametrize("alert", [CVE_ALERT, LICENSE_ALERT], ids=["alert", "license"]) +def test_existing_alerts_table_links_the_package_page(alert): + artifact, expected = ECOSYSTEMS["npm-scoped"] + diff = _diff([]) + diff.unchanged_alerts = _issues(artifact, alert) + + body = Messages.security_comment_template(diff, _FakeConfig()) + + assert _this_package_hrefs(body) == [expected] + + +@pytest.mark.parametrize("section", ["new_alerts", "unchanged_alerts"]) +@pytest.mark.parametrize("alert", [CVE_ALERT, LICENSE_ALERT], ids=["security", "license"]) +def test_rows_keep_package_namespaces_distinct(section, alert): + issues = [] + for scope in ("@alpha", "@beta"): + artifact = dict(type="npm", namespace=scope, name="widgets", version="1.0.0") + issues += _issues(artifact, alert) + diff = _diff([]) + setattr(diff, section, issues) + + body = Messages.security_comment_template(diff, _FakeConfig()) + + assert _this_package_hrefs(body) == [ + "https://socket.dev/npm/package/@alpha/widgets/overview/1.0.0", + "https://socket.dev/npm/package/@beta/widgets/overview/1.0.0", + ] + assert "@alpha/widgets@1.0.0" in body + assert "@beta/widgets@1.0.0" in body + command = "@SocketSecurity ignore npm/@alpha/widgets@1.0.0" + assert f"{command}" in body + comment = Comment(body_list=body.splitlines()) + comments = {"ignore": [Comment(body_list=[command])]} + assert Comments.remove_alerts(comments, issues) == [issues[1]] + updated = Comments.process_security_comment(comment, comments) + assert _this_package_hrefs(updated) == _this_package_hrefs(body)[1:] + + legacy = {"ignore": [Comment(body_list=["@SocketSecurity ignore npm/widgets@1.0.0"])]} + assert Comments.remove_alerts(legacy, issues) == [] + assert "No dependency alerts to report" in Comments.process_security_comment(comment, legacy) + + +@pytest.mark.parametrize("with_existing", [False, True]) +def test_large_comments_keep_omission_counts_and_the_full_report(with_existing): + new_issues = [ + _issues(dict(type="npm", name=f"widget-{i}", version="1.0.0"), CVE_ALERT)[0] + for i in range(60) + ] + for issue in new_issues: + issue.description = "説明" * 200 + diff = _diff(new_issues) + if with_existing: + artifact = dict(type="npm", name="existing-widget", version="1.0.0") + diff.unchanged_alerts = _issues(artifact, CVE_ALERT) + diff.unchanged_alerts[0].description = "説明" * 500 + + body = Messages.security_comment_template(diff, _FakeConfig()) + + visible = re.findall(r"", body) + assert 0 < len(visible) < len(new_issues) + assert f"{len(new_issues) - len(visible)} more new alert(s) are not shown" in body + assert len(body.encode()) <= Messages.SECURITY_COMMENT_SIZE_BUDGET + assert body.count("") == (2 if with_existing else 1) + if with_existing: + assert "1 more existing alert(s) are not shown" in body + assert "Existing alerts (1)" in body + report_link = f"[View full report]({diff.diff_url}?action=error%2Cwarn)" + assert report_link in body + assert len(diff.new_alerts) == 60 + assert len(diff.unchanged_alerts) == int(with_existing) + + comment = Comment(body_list=body.splitlines()) + individual_ignores = [ + Comment(body_list=[f"@SocketSecurity ignore npm/{coordinate}"]) + for coordinate in visible + ] + updated = Comments.process_security_comment(comment, {"ignore": individual_ignores}) + assert "more new alert(s) are not shown" in updated + assert "No dependency alerts to report" not in updated + assert report_link in updated + + ignore_all = Comment(body_list=["@SocketSecurity ignore-all"]) + cleared = Comments.process_security_comment(comment, {"ignore": [ignore_all]}) + assert "No dependency alerts to report" in cleared + assert "more new alert(s)" not in cleared + + +@pytest.mark.parametrize("scm", ["github", "gitlab"]) +def test_no_relative_package_links_on_either_scm(scm): + alerts = [ + alert + for artifact, _ in ECOSYSTEMS.values() + for alert in _issues(artifact, CVE_ALERT) + _issues(artifact, LICENSE_ALERT) + ] + + body = Messages.security_comment_template(_diff(alerts), _FakeConfig(scm=scm)) + + hrefs = _this_package_hrefs(body) + assert len(hrefs) == 2 * len(ECOSYSTEMS) + assert all(href.startswith("https://socket.dev/") for href in hrefs) + + +def test_package_url_is_attribute_escaped(): + artifact = dict(type="npm", name='evil">