Skip to content
Open
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
109 changes: 106 additions & 3 deletions sentry_sdk/integrations/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,111 @@
import sentry_sdk
from sentry_sdk.integrations import Integration
from sentry_sdk.scope import add_global_event_processor
from sentry_sdk.serializer import serialize
from sentry_sdk.utils import _get_installed_modules

if TYPE_CHECKING:
from typing import Any
from typing import Any, Callable, Dict, Optional, Tuple

from sentry_sdk._types import Event

_ModulesCacheEntry = Tuple[
Dict[str, str],
Optional[int],
Optional[Callable[..., Optional[str]]],
Optional[Dict[str, Any]],
]


class _SerializedModules(dict): # type: ignore[type-arg]
"""Pre-serialized modules dict that returns a fresh plain dict to serialize()."""

def __init__(
self,
data: "Dict[str, Any]",
max_value_length: "Optional[int]" = None,
custom_repr: "Optional[Callable[..., Optional[str]]]" = None,
) -> None:
super().__init__(data)
self._max_value_length = max_value_length
self._custom_repr = custom_repr
self._mutated = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dict subclass rejects no-arg construction

Medium Severity

_SerializedModules.__init__ requires data, so same-type construction with no arguments fails. Standard dict operations that do that (copy(), |, copy.copy(), deepcopy) raise TypeError on event["modules"]. If an event processor hits one of those, the callback error drops the event.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7472999. Configure here.


def __sentry_repr__(self) -> "Dict[str, Any]":
if self._mutated:
return serialize(
{"modules": dict(self)},
max_value_length=self._max_value_length,
custom_repr=self._custom_repr,
)["modules"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mutation path drops truncation metadata

Medium Severity

When an event processor mutates event["modules"], __sentry_repr__ re-serializes through a nested serialize() call and returns only the inner modules mapping. Truncation annotations from that call never reach the outer event, so _meta for shortened module values is omitted. The cache path already falls back to a plain copy to preserve those annotations.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7472999. Configure here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nested serialize clears capture-event guard

Low Severity

Mutated modules call serialize() from inside the outer serialize(). The inner finally sets disable_capture_event back to False while the outer walk is still running, so later event fields serialize with capture enabled again.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7472999. Configure here.

return dict(self)

def __setitem__(self, key: "Any", value: "Any") -> None:
self._mutated = True
super().__setitem__(key, value)

def __delitem__(self, key: "Any") -> None:
self._mutated = True
super().__delitem__(key)

def clear(self) -> None:
self._mutated = True
super().clear()

def pop(self, *args: "Any") -> "Any":
self._mutated = True
return super().pop(*args)

def popitem(self) -> "Tuple[Any, Any]":
self._mutated = True
return super().popitem()

def setdefault(self, *args: "Any") -> "Any":
self._mutated = True
return super().setdefault(*args)

def update(self, *args: "Any", **kwargs: "Any") -> None:
self._mutated = True
super().update(*args, **kwargs)


_cached_modules: "Optional[_ModulesCacheEntry]" = None


def _get_serialized_modules(
raw_modules: "Dict[str, str]",
max_value_length: "Optional[int]",
custom_repr: "Optional[Callable[..., Optional[str]]]",
) -> "Dict[str, Any]":
global _cached_modules
cached = _cached_modules
if (
cached is None
or cached[0] is not raw_modules
or cached[1] != max_value_length
or cached[2] != custom_repr
or (cached[3] is not None and len(cached[3]) != len(raw_modules))
):
serialized = serialize(
{"modules": raw_modules},
max_value_length=max_value_length,
custom_repr=custom_repr,
)
pre_serialized: "Optional[Dict[str, Any]]" = (
None if serialized.get("_meta") else serialized["modules"]
)
cached = (raw_modules, max_value_length, custom_repr, pre_serialized)
_cached_modules = cached

if cached[3] is None:
return dict(raw_modules)

return _SerializedModules(
cached[3],
max_value_length=max_value_length,
custom_repr=custom_repr,
)


class ModulesIntegration(Integration):
identifier = "modules"
Expand All @@ -21,8 +119,13 @@ def processor(event: "Event", hint: "Any") -> "Event":
if event.get("type") == "transaction":
return event

if sentry_sdk.get_client().get_integration(ModulesIntegration) is None:
client = sentry_sdk.get_client()
if client.get_integration(ModulesIntegration) is None:
return event

event["modules"] = _get_installed_modules()
event["modules"] = _get_serialized_modules(
_get_installed_modules(),
client.options.get("max_value_length"),
client.options.get("custom_repr"),
)
return event
114 changes: 114 additions & 0 deletions tests/integrations/modules/test_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,117 @@ def test_basic(sentry_init, capture_events):
(event,) = events
assert "sentry-sdk" in event["modules"]
assert "pytest" in event["modules"]


def test_modules_not_reserialized_per_event(sentry_init, capture_events, monkeypatch):
from sentry_sdk.serializer import _Serializer

fake_modules = {f"package-{i}": f"{i}.0.0" for i in range(50)}
monkeypatch.setattr(
"sentry_sdk.integrations.modules._get_installed_modules",
lambda: fake_modules,
)

sentry_init(integrations=[ModulesIntegration()])
events = capture_events()

module_node_calls = 0
orig_serialize_node = _Serializer._serialize_node

def counting_serialize_node(self, obj, *args, **kwargs):
nonlocal module_node_calls
if self.path == ["modules"]:
module_node_calls += 1
return orig_serialize_node(self, obj, *args, **kwargs)

monkeypatch.setattr(_Serializer, "_serialize_node", counting_serialize_node)

for _ in range(3):
sentry_sdk.capture_message("hello")

assert len(events) == 3
for event in events:
assert type(event["modules"]) is dict
assert event["modules"] == fake_modules

# Modules should be serialized at most once when populating the cache.
assert module_node_calls <= len(fake_modules)


def test_modules_mutation_isolation(sentry_init, capture_events, monkeypatch):
fake_modules = {"pkg-a": "1.0.0", "pkg-b": "2.0.0"}
monkeypatch.setattr(
"sentry_sdk.integrations.modules._get_installed_modules",
lambda: fake_modules,
)

call_count = 0

def before_send(event, hint):
nonlocal call_count
call_count += 1
if call_count == 1:
event["modules"]["injected"] = "9.9.9"
del event["modules"]["pkg-a"]
return event

sentry_init(integrations=[ModulesIntegration()], before_send=before_send)
events = capture_events()

sentry_sdk.capture_message("first")
sentry_sdk.capture_message("second")

assert len(events) == 2
assert events[0]["modules"] == {"pkg-b": "2.0.0", "injected": "9.9.9"}
assert events[1]["modules"] == {"pkg-a": "1.0.0", "pkg-b": "2.0.0"}


def test_modules_event_processor_mutation(sentry_init, capture_events, monkeypatch):
fake_modules = {"pkg-a": "1.0.0"}
monkeypatch.setattr(
"sentry_sdk.integrations.modules._get_installed_modules",
lambda: fake_modules,
)

sentry_init(integrations=[ModulesIntegration()], max_value_length=10)
events = capture_events()

class CustomObj:
def __repr__(self):
return "<custom>"

scope = sentry_sdk.get_isolation_scope()

@scope.add_event_processor
def mutate_modules(event, hint):
if event.get("message") == "mutate":
event["modules"]["extra"] = CustomObj()
event["modules"]["long-pkg"] = "123456789012345"
return event

sentry_sdk.capture_message("mutate")
sentry_sdk.capture_message("clean")

assert len(events) == 2
assert events[0]["modules"] == {
"pkg-a": "1.0.0",
"extra": "<custom>",
"long-pkg": "1234567...",
}
assert "_meta" not in events[0]["modules"]
assert events[1]["modules"] == {"pkg-a": "1.0.0"}


def test_modules_respects_max_value_length(sentry_init, capture_events, monkeypatch):
fake_modules = {"pkg-long": "1234567890"}
monkeypatch.setattr(
"sentry_sdk.integrations.modules._get_installed_modules",
lambda: fake_modules,
)

sentry_init(integrations=[ModulesIntegration()], max_value_length=5)
events = capture_events()

sentry_sdk.capture_message("hello")
(event,) = events
assert event["modules"] == {"pkg-long": "12..."}
Loading