Skip to content

Commit 97ea93b

Browse files
committed
Merge remote-tracking branch 'origin/main' into lelia/tag-stable-on-release
2 parents d5c695c + 61cff79 commit 97ea93b

5 files changed

Lines changed: 199 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,27 @@
22

33
## 2.13.2
44

5+
### Added
6+
7+
- Security and license alerts on a transitive dependency now name the direct
8+
dependency that introduced it, under the manifest link. Up to five are listed.
9+
510
### Changed
611

12+
- Manifest file links in PR comments and reports pick the source host only from
13+
`--scm`. The fallback that guessed GitHub, GitLab, or Bitbucket from the Socket
14+
diff URL never produced a link and has been removed.
715
- Each release now also tags `socketdev/cli:stable`, so `stable` and `latest`
816
both point at the newest release. Previously `stable` moved only when someone
917
promoted a release by hand. Pin `socketdev/cli:<version>` for reproducible CI
1018
runs.
1119

20+
### Fixed
21+
22+
- Scoped npm packages and Maven artifacts named as the introducing dependency
23+
keep their scope or group ID (`npm/@acme/widgets@1.2.0`, not
24+
`npm/widgets@1.2.0`).
25+
1226
## 2.13.1
1327

1428
### Documentation

‎socketsecurity/core/__init__.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2795,7 +2795,12 @@ def get_source_data(package: Package, packages: dict) -> list:
27952795
top_package = packages.get(top_id)
27962796
if top_package:
27972797
manifests = ""
2798-
top_purl = f"{top_package.type}/{top_package.name}@{top_package.version}"
2798+
ancestor_name = (
2799+
f"{top_package.namespace}/{top_package.name}"
2800+
if top_package.namespace
2801+
else top_package.name
2802+
)
2803+
top_purl = f"{top_package.type}/{ancestor_name}@{top_package.version}"
27992804
if hasattr(top_package, "manifestFiles") and top_package.manifestFiles:
28002805
for manifest_data in top_package.manifestFiles:
28012806
manifest_file = manifest_data.get("file")

‎socketsecurity/core/messages.py‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,18 +78,10 @@ def get_manifest_file_url(diff: Diff, manifest_path: str, config=None) -> str:
7878
# Remove leading slashes
7979
clean_path = clean_path.lstrip('/')
8080

81-
# Determine SCM type from config or diff_url
82-
scm_type = "api" # Default to API
81+
# diff.diff_url points at Socket, not the SCM, so only config decides.
82+
scm_type = "api"
8383
if config and hasattr(config, 'scm'):
8484
scm_type = config.scm.lower()
85-
elif hasattr(diff, 'diff_url') and diff.diff_url:
86-
diff_url = diff.diff_url.lower()
87-
if 'github.com' in diff_url or 'github' in diff_url:
88-
scm_type = "github"
89-
elif 'gitlab' in diff_url:
90-
scm_type = "gitlab"
91-
elif 'bitbucket' in diff_url:
92-
scm_type = "bitbucket"
9385

9486
# Generate URL based on SCM type using config information
9587
# NEVER use diff.diff_url for SCM URLs - those are Socket URLs for "View report" links
@@ -861,6 +853,35 @@ def html_text(value) -> str:
861853
"""
862854
return escape(Messages.inline_html_text(value))
863855

856+
# Enough to name the usual one or two ancestors without letting a package
857+
# pulled in by dozens of direct dependencies swamp the alert row.
858+
INTRODUCED_BY_LIMIT = 5
859+
860+
@staticmethod
861+
def introduced_by_html(alert: Issue) -> str:
862+
"""Name the direct dependencies that pulled a transitive package in.
863+
864+
Returns an empty string for a direct dependency, or for a transitive one
865+
whose ancestors are not in this scan, so the row only gains a line when
866+
there is an ancestor to name.
867+
"""
868+
ancestors = []
869+
for entry in getattr(alert, "introduced_by", None) or []:
870+
if not isinstance(entry, (list, tuple)) or not entry:
871+
continue
872+
source = entry[0]
873+
if source and source != "direct" and source not in ancestors:
874+
ancestors.append(source)
875+
if not ancestors:
876+
return ""
877+
878+
shown = ancestors[:Messages.INTRODUCED_BY_LIMIT]
879+
names = ", ".join(f"<code>{Messages.html_text(name)}</code>" for name in shown)
880+
hidden = len(ancestors) - len(shown)
881+
if hidden:
882+
names += f" and {hidden} more"
883+
return f"<p><strong>Introduced by:</strong> {names}</p>"
884+
864885
@staticmethod
865886
def html_attr(value) -> str:
866887
"""Escape a value for an HTML attribute, quotes included.
@@ -990,6 +1011,7 @@ def license_group_row(alerts: list, diff: Diff, config, show_ignore: bool) -> st
9901011
) if show_ignore else ""
9911012
row += f""" </ul>
9921013
<p><strong>From:</strong> <a href="{Messages.html_attr(license_manifest_url)}">Manifest File</a></p>
1014+
{Messages.introduced_by_html(first_alert)}
9931015
<p>ℹ️ Read more on: <a href="{Messages.html_attr(first_alert.purl)}">This package</a> | <a href="https://socket.dev/alerts/license">What is a license policy violation?</a></p>
9941016
<blockquote>
9951017
<p><em>Next steps:</em> 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 <strong>support@socket.dev</strong>.</p>
@@ -1039,6 +1061,7 @@ def security_alert_row(alert: Issue, diff: Diff, config, show_ignore: bool) -> s
10391061
<p><strong>Note:</strong> {Messages.html_text(alert.description)}</p>
10401062
{patched_version_html}
10411063
<p><strong>Source:</strong> <a href="{Messages.html_attr(manifest_url)}">Manifest File</a></p>
1064+
{Messages.introduced_by_html(alert)}
10421065
<p>ℹ️ Read more on:
10431066
<a href="{Messages.html_attr(alert.purl)}">This package</a> |
10441067
<a href="{Messages.html_attr(alert.url)}">This alert</a> |

‎tests/unit/test_messages.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,21 @@ def test_manifest_link_falls_back_to_the_report_without_a_repository_url():
102102
url = Messages.get_manifest_file_url(diff, "app/package.json", config)
103103

104104
assert url == "https://socket.dev/report/123?tab=files&file=app%2Fpackage.json"
105+
106+
107+
108+
def test_manifest_link_does_not_guess_the_scm_from_the_diff_url():
109+
"""Without an explicit scm, a GitHub-looking diff_url falls back to the report."""
110+
111+
class _NoScmConfig:
112+
branch = "main"
113+
repository_url = "https://github.com/acme/widgets"
114+
115+
diff = Diff(
116+
diff_url="https://github.com/acme/widgets/pull/1",
117+
report_url="https://socket.dev/report/123",
118+
)
119+
120+
url = Messages.get_manifest_file_url(diff, "app/package.json", _NoScmConfig())
121+
122+
assert url == "https://socket.dev/report/123?tab=files&file=app%2Fpackage.json"

‎tests/unit/test_pr_comment_rendering.py‎

Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111

1212
import pytest
1313

14-
from socketsecurity.core.classes import Comment, Diff, Issue
14+
from socketsecurity.core import Core
15+
from socketsecurity.core.classes import Comment, Diff, Issue, Package
1516
from socketsecurity.core.messages import Messages
1617
from socketsecurity.core.scm_comments import Comments
1718

@@ -503,3 +504,129 @@ def test_plain_style_is_left_verbatim(self):
503504
manifest_str, _ = Messages.create_sources(alert, "plain")
504505

505506
assert "<img src=x>/package.json" in manifest_str
507+
508+
509+
class TestIntroducedBy:
510+
"""The default comment names the direct dependency behind a transitive alert."""
511+
512+
def _body(self, alert: Issue) -> str:
513+
return Messages.security_comment_template(_make_diff([alert]), _FakeConfig())
514+
515+
def test_transitive_alert_names_its_ancestor(self):
516+
alert = _make_alert(
517+
manifests="",
518+
introduced_by=[("npm/@acme/widgets@1.2.0", "package.json")],
519+
)
520+
521+
body = self._body(alert)
522+
523+
assert (
524+
"<p><strong>Introduced by:</strong> <code>npm/@acme/widgets@1.2.0</code></p>"
525+
in body
526+
)
527+
assert_html_block_intact(body)
528+
529+
def test_direct_dependency_gets_no_line(self):
530+
alert = _make_alert(manifests="", introduced_by=[("direct", "package.json")])
531+
532+
body = self._body(alert)
533+
534+
assert "Introduced by" not in body
535+
assert_html_block_intact(body)
536+
537+
def test_transitive_without_known_ancestors_gets_no_line(self):
538+
body = self._body(_make_alert())
539+
540+
assert "Introduced by" not in body
541+
assert_html_block_intact(body)
542+
543+
def test_repeated_ancestors_are_listed_once(self):
544+
"""One ancestor declared in two manifests yields two entries."""
545+
alert = _make_alert(
546+
manifests="",
547+
introduced_by=[
548+
("npm/express@4.0.0", "a/package.json"),
549+
("npm/express@4.0.0", "b/package.json"),
550+
],
551+
)
552+
553+
assert Messages.introduced_by_html(alert).count("npm/express@4.0.0") == 1
554+
555+
def test_long_ancestor_lists_are_capped(self):
556+
limit = Messages.INTRODUCED_BY_LIMIT
557+
alert = _make_alert(
558+
manifests="",
559+
introduced_by=[(f"npm/root-{i}@1.0.0", "package.json") for i in range(limit + 3)],
560+
)
561+
562+
html = Messages.introduced_by_html(alert)
563+
564+
assert html.count("<code>") == limit
565+
assert html.endswith(" and 3 more</p>")
566+
567+
def test_ancestor_name_is_escaped(self):
568+
alert = _make_alert(
569+
manifests="",
570+
introduced_by=[("npm/<img src=x>@1.0.0", "package.json")],
571+
)
572+
573+
body = self._body(alert)
574+
575+
assert "<img src=x>" not in body
576+
assert "npm/&lt;img src=x&gt;@1.0.0" in body
577+
578+
def test_license_row_names_its_ancestor(self):
579+
alert = _make_alert(
580+
type="licenseSpdxDisj",
581+
title="License Policy Violation",
582+
manifests="",
583+
introduced_by=[("pypi/requests@2.31.0", "requirements.txt")],
584+
)
585+
586+
body = self._body(alert)
587+
588+
assert "has a License Policy Violation" in body
589+
assert "<code>pypi/requests@2.31.0</code>" in body
590+
assert_html_block_intact(body)
591+
592+
593+
def _package(package_id: str, **overrides):
594+
fields = dict(
595+
type="npm",
596+
namespace=None,
597+
name="widget",
598+
version="1.0.0",
599+
id=package_id,
600+
score={},
601+
alerts=[],
602+
direct=False,
603+
topLevelAncestors=[],
604+
manifestFiles=[],
605+
purl="",
606+
)
607+
fields.update(overrides)
608+
return Package(**fields)
609+
610+
611+
def test_ancestor_labels_keep_their_namespace():
612+
"""Two scoped npm roots with the same name, and a Maven root, must render as
613+
distinct, correctly named ancestors in the comment."""
614+
packages = {
615+
"one": _package("one", namespace="@one", manifestFiles=[{"file": "package.json"}]),
616+
"two": _package("two", namespace="@two", manifestFiles=[{"file": "package.json"}]),
617+
"mvn": _package(
618+
"mvn", type="maven", namespace="com.acme", name="core",
619+
manifestFiles=[{"file": "pom.xml"}],
620+
),
621+
"plain": _package("plain", name="express", manifestFiles=[{"file": "package.json"}]),
622+
}
623+
child = _package("child", name="leaf", topLevelAncestors=["one", "two", "mvn", "plain"])
624+
625+
sources = [source for source, _ in Core.get_source_data(child, packages)]
626+
627+
assert sources == [
628+
"npm/@one/widget@1.0.0",
629+
"npm/@two/widget@1.0.0",
630+
"maven/com.acme/core@1.0.0",
631+
"npm/express@1.0.0",
632+
]

0 commit comments

Comments
 (0)