From 2d20c40641812515359a4164b12791cdb0857602 Mon Sep 17 00:00:00 2001 From: Khaleel Al-Adhami Date: Mon, 13 Jan 2025 17:16:39 -0800 Subject: [PATCH 1/2] add defensive checks against data being funny --- reflex/app.py | 25 +++++++++++++++++++++++-- reflex/utils/exceptions.py | 4 ++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/reflex/app.py b/reflex/app.py index 08cb4314e2..d0cfe37650 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -1563,10 +1563,31 @@ async def on_event(self, sid, data): Args: sid: The Socket.IO session id. data: The event data. + + Raises: + EventDeserializationError: If the event data is not a dictionary. """ fields = data - # Get the event. - event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS}) + + if isinstance(fields, str): + fields = json.loads(fields) + console.warn( + "Received event data as a string. This generally should not happen and may indicate a bug." + f" Event data: {fields}" + ) + + if not isinstance(fields, dict): + raise exceptions.EventDeserializationError( + f"Event data must be a dictionary, but received {fields} of type {type(fields)}." + ) + + try: + # Get the event. + event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS}) + except (TypeError, ValueError) as ex: + raise exceptions.EventDeserializationError( + f"Failed to deserialize event data: {fields}." + ) from ex self.token_to_sid[event.token] = sid self.sid_to_token[sid] = event.token diff --git a/reflex/utils/exceptions.py b/reflex/utils/exceptions.py index bceadc977e..be858bc62e 100644 --- a/reflex/utils/exceptions.py +++ b/reflex/utils/exceptions.py @@ -167,6 +167,10 @@ class SystemPackageMissingError(ReflexError): """Raised when a system package is missing.""" +class EventDeserializationError(ReflexError, ValueError): + """Raised when an event cannot be deserialized.""" + + def raise_system_package_missing_error(package: str) -> NoReturn: """Raise a SystemPackageMissingError. From c2af297b3016fa6728f3916d965615a594a9be49 Mon Sep 17 00:00:00 2001 From: Khaleel Al-Adhami Date: Mon, 13 Jan 2025 17:17:38 -0800 Subject: [PATCH 2/2] be even more defensive --- reflex/app.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/reflex/app.py b/reflex/app.py index d0cfe37650..b9500f5a74 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -1570,11 +1570,16 @@ async def on_event(self, sid, data): fields = data if isinstance(fields, str): - fields = json.loads(fields) console.warn( "Received event data as a string. This generally should not happen and may indicate a bug." f" Event data: {fields}" ) + try: + fields = json.loads(fields) + except json.JSONDecodeError as ex: + raise exceptions.EventDeserializationError( + f"Failed to deserialize event data: {fields}." + ) from ex if not isinstance(fields, dict): raise exceptions.EventDeserializationError(