Skip to content

Commit 4dc1065

Browse files
authored
add defensive checks against data being funny (#4633)
1 parent 2855ed4 commit 4dc1065

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

reflex/app.py

+28-2
Original file line numberDiff line numberDiff line change
@@ -1557,10 +1557,36 @@ async def on_event(self, sid, data):
15571557
Args:
15581558
sid: The Socket.IO session id.
15591559
data: The event data.
1560+
1561+
Raises:
1562+
EventDeserializationError: If the event data is not a dictionary.
15601563
"""
15611564
fields = data
1562-
# Get the event.
1563-
event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS})
1565+
1566+
if isinstance(fields, str):
1567+
console.warn(
1568+
"Received event data as a string. This generally should not happen and may indicate a bug."
1569+
f" Event data: {fields}"
1570+
)
1571+
try:
1572+
fields = json.loads(fields)
1573+
except json.JSONDecodeError as ex:
1574+
raise exceptions.EventDeserializationError(
1575+
f"Failed to deserialize event data: {fields}."
1576+
) from ex
1577+
1578+
if not isinstance(fields, dict):
1579+
raise exceptions.EventDeserializationError(
1580+
f"Event data must be a dictionary, but received {fields} of type {type(fields)}."
1581+
)
1582+
1583+
try:
1584+
# Get the event.
1585+
event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS})
1586+
except (TypeError, ValueError) as ex:
1587+
raise exceptions.EventDeserializationError(
1588+
f"Failed to deserialize event data: {fields}."
1589+
) from ex
15641590

15651591
self.token_to_sid[event.token] = sid
15661592
self.sid_to_token[sid] = event.token

reflex/utils/exceptions.py

+4
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,10 @@ class SystemPackageMissingError(ReflexError):
187187
"""Raised when a system package is missing."""
188188

189189

190+
class EventDeserializationError(ReflexError, ValueError):
191+
"""Raised when an event cannot be deserialized."""
192+
193+
190194
def raise_system_package_missing_error(package: str) -> NoReturn:
191195
"""Raise a SystemPackageMissingError.
192196

0 commit comments

Comments
 (0)