Skip to content
Merged
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 10 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 7 additions & 0 deletions socketsecurity/core/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "".

Expand Down
229 changes: 118 additions & 111 deletions socketsecurity/core/messages.py

Large diffs are not rendered by default.

47 changes: 32 additions & 15 deletions socketsecurity/core/scm_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -247,18 +257,8 @@ def process_updated_security_comment(

# Detect the start of an alert section
if stripped.startswith("<!-- start-socket-alert-"):
# Extract package name and version from the comment
try:
start_marker = stripped[len("<!-- start-socket-alert-"):-4] # Strip the comment markers
pkg_name, pkg_version = start_marker.rsplit("@", 1)
except ValueError:
pkg_name, pkg_version = "", ""

# Determine if we should ignore this alert
ignore_section = ignore_all or any(
Comments.is_ignore(pkg_name, pkg_version, name, version)
for name, version in ignore_commands
)
marker = stripped.removeprefix("<!-- start-socket-alert-").removesuffix(" -->")
ignore_section = ignore_all or Comments.matches_alert_marker(marker, ignore_commands)

# If not ignored, include this start marker
if not ignore_section:
Expand All @@ -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:
"""
Expand Down
7 changes: 5 additions & 2 deletions socketsecurity/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 1 addition & 7 deletions socketsecurity/socketcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
]
Expand Down
42 changes: 37 additions & 5 deletions tests/core/test_existing_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"<!-- start-socket-alert-(.*?) -->", 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
Expand All @@ -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

Expand Down
Loading