From c818ec3bbef87dc041cdad9345cacdd87570dec8 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Mon, 23 Nov 2026 17:47:18 -0700 Subject: [PATCH] fix(api): refuse deeply nested cache payloads by depth, not RecursionError --- tests/remote/unit/test_cache_payload_safety.py | 1 + unshackle/core/api/sanitize.py | 14 +++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/tests/remote/unit/test_cache_payload_safety.py b/tests/remote/unit/test_cache_payload_safety.py index d1a90623..18bdd8c9 100644 --- a/tests/remote/unit/test_cache_payload_safety.py +++ b/tests/remote/unit/test_cache_payload_safety.py @@ -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", "py/state": {}}', pytest.param("[" * 100000 + "]" * 100000, id="deep-nesting"), + pytest.param("[" * 200 + "]" * 200, id="over-depth-limit"), ], ) def test_unsafe_payload_is_refused(text) -> None: diff --git a/unshackle/core/api/sanitize.py b/unshackle/core/api/sanitize.py index e2478001..e37c4056 100644 --- a/unshackle/core/api/sanitize.py +++ b/unshackle/core/api/sanitize.py @@ -48,23 +48,27 @@ SAFE_PICKLE_TAGS = frozenset({"py/object", "py/type", "py/reduce", "py/tuple", " SAFE_PICKLE_TYPES = frozenset( {"datetime.datetime", "datetime.date", "datetime.time", "datetime.timedelta", "datetime.timezone"} ) +MAX_CACHE_PAYLOAD_DEPTH = 100 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. ``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: root = json.loads(text) except (ValueError, RecursionError): return False - stack = [root] + stack = [(root, 0)] while stack: - node = stack.pop() + node, depth = stack.pop() + if depth > MAX_CACHE_PAYLOAD_DEPTH: + return False if isinstance(node, list): - stack.extend(node) + stack.extend((item, depth + 1) for item in node) elif isinstance(node, dict): for key, value in node.items(): 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"} ): return False - stack.append(value) + stack.append((value, depth + 1)) return True