Skip to content

Commit fc32e83

Browse files
committed
Harden dataclass utils
1 parent cbab8bf commit fc32e83

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

mesop/dataclass_utils/dataclass_utils.py

+4
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,10 @@ def update_dataclass_from_json(instance: Any, json_string: str):
129129

130130
def _recursive_update_dataclass_from_json_obj(instance: Any, json_dict: Any):
131131
for key, value in json_dict.items():
132+
if key.startswith("__") and key.endswith("__"):
133+
raise MesopDeveloperException(
134+
f"Cannot use dunder property: {key} in stateclass"
135+
)
132136
if hasattr(instance, key):
133137
attr = getattr(instance, key)
134138
if isinstance(value, dict):

mesop/dataclass_utils/dataclass_utils_test.py

+19
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
serialize_dataclass,
1515
update_dataclass_from_json,
1616
)
17+
from mesop.exceptions import MesopDeveloperException
1718

1819

1920
@dataclass
@@ -593,5 +594,23 @@ class ChildClass(ParentClass):
593594
assert has_parent(ParentClass) is False
594595

595596

597+
def test_globals_pollution():
598+
@dataclass
599+
class A:
600+
val: str
601+
602+
initial_name = __name__
603+
obj = A(val="default")
604+
with pytest.raises(MesopDeveloperException) as exc_info:
605+
update_dataclass_from_json(
606+
obj, '{"__init__": {"__globals__": {"__name__": "polluted"}}}'
607+
)
608+
assert "Cannot use dunder property: __init__ in stateclass" in str(
609+
exc_info.value
610+
)
611+
# Make sure __name__ has not been modified via the __globals__ pollution attempt
612+
assert __name__ == initial_name
613+
614+
596615
if __name__ == "__main__":
597616
raise SystemExit(pytest.main(["-vv", __file__]))

0 commit comments

Comments
 (0)