fix(api): refuse deeply nested cache payloads by depth, not RecursionError

This commit is contained in:
imSp4rky
2026-11-23 17:50:50 -07:00
parent 530f78ecf5
commit c818ec3bbe
2 changed files with 10 additions and 5 deletions
@@ -38,6 +38,7 @@ def test_plain_json_is_safe(text) -> None:
'{"py/object": "datetime.datetime", "__reduce__": [{"py/type": "collections.OrderedDict"}, []]}', '{"py/object": "datetime.datetime", "__reduce__": [{"py/type": "collections.OrderedDict"}, []]}',
'{"py/object": "datetime.datetime", "py/state": {}}', '{"py/object": "datetime.datetime", "py/state": {}}',
pytest.param("[" * 100000 + "]" * 100000, id="deep-nesting"), pytest.param("[" * 100000 + "]" * 100000, id="deep-nesting"),
pytest.param("[" * 200 + "]" * 200, id="over-depth-limit"),
], ],
) )
def test_unsafe_payload_is_refused(text) -> None: def test_unsafe_payload_is_refused(text) -> None:
+9 -5
View File
@@ -48,23 +48,27 @@ SAFE_PICKLE_TAGS = frozenset({"py/object", "py/type", "py/reduce", "py/tuple", "
SAFE_PICKLE_TYPES = frozenset( SAFE_PICKLE_TYPES = frozenset(
{"datetime.datetime", "datetime.date", "datetime.time", "datetime.timedelta", "datetime.timezone"} {"datetime.datetime", "datetime.date", "datetime.time", "datetime.timedelta", "datetime.timezone"}
) )
MAX_CACHE_PAYLOAD_DEPTH = 100
def safe_cache_payload(text: str) -> bool: def safe_cache_payload(text: str) -> bool:
"""True when a peer-supplied cache file is JSON that jsonpickle decodes to plain data and datetimes only. """True when a peer-supplied cache file is JSON that jsonpickle decodes to plain data and datetimes only.
``Cacher`` decodes cache files with jsonpickle, which imports and calls any type a file names, ``Cacher`` decodes cache files with jsonpickle, which imports and calls any type a file names,
so a file from another machine may name the datetime types and nothing else. so a file from another machine may name the datetime types and nothing else. Nesting deeper than
``MAX_CACHE_PAYLOAD_DEPTH`` is refused, because the jsonpickle decode is recursive.
""" """
try: try:
root = json.loads(text) root = json.loads(text)
except (ValueError, RecursionError): except (ValueError, RecursionError):
return False return False
stack = [root] stack = [(root, 0)]
while stack: while stack:
node = stack.pop() node, depth = stack.pop()
if depth > MAX_CACHE_PAYLOAD_DEPTH:
return False
if isinstance(node, list): if isinstance(node, list):
stack.extend(node) stack.extend((item, depth + 1) for item in node)
elif isinstance(node, dict): elif isinstance(node, dict):
for key, value in node.items(): for key, value in node.items():
if key.startswith("py/") and key not in SAFE_PICKLE_TAGS: if key.startswith("py/") and key not in SAFE_PICKLE_TAGS:
@@ -75,5 +79,5 @@ def safe_cache_payload(text: str) -> bool:
isinstance(value, list) and value and isinstance(value[0], dict) and value[0].keys() == {"py/type"} isinstance(value, list) and value and isinstance(value[0], dict) and value[0].keys() == {"py/type"}
): ):
return False return False
stack.append(value) stack.append((value, depth + 1))
return True return True