-
Notifications
You must be signed in to change notification settings - Fork 1.8k
AVRO-4328: [python] Bound decode recursion depth #3929
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
iemejia
wants to merge
2
commits into
apache:main
Choose a base branch
from
iemejia:AVRO-4328-python-bound-decode-recursion-depth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+180
−8
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| ## | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """AVRO-4302: bound decode recursion depth to prevent stack exhaustion.""" | ||
|
|
||
| import io | ||
| import json | ||
| import unittest | ||
|
|
||
| import avro.errors | ||
| import avro.io | ||
| import avro.schema | ||
|
|
||
|
|
||
| def _encode_long(value: int) -> bytes: | ||
| """Zig-zag + varint encode a long, matching BinaryEncoder.write_long.""" | ||
| datum = (value << 1) ^ (value >> 63) | ||
| out = bytearray() | ||
| while (datum & ~0x7F) != 0: | ||
| out.append((datum & 0x7F) | 0x80) | ||
| datum >>= 7 | ||
| out.append(datum) | ||
| return bytes(out) | ||
|
|
||
|
|
||
| class TestDecodeRecursionDepth(unittest.TestCase): | ||
| # A self-referencing linked-list schema: the classic recursion-bomb shape. | ||
| NODE = avro.schema.parse(json.dumps({"type": "record", "name": "Node", "fields": [{"name": "next", "type": ["null", "Node"]}]})) | ||
|
|
||
| @staticmethod | ||
| def _linked_list(depth: int) -> bytes: | ||
| """Encode a Node linked list nested ``depth`` levels deep. | ||
|
|
||
| Each level selects the ``Node`` union branch (index 1); the final level | ||
| selects ``null`` (index 0) to terminate. ~1 byte per level. | ||
| """ | ||
| return _encode_long(1) * depth + _encode_long(0) | ||
|
|
||
| def _read(self, data: bytes) -> object: | ||
| reader = avro.io.DatumReader(self.NODE, self.NODE) | ||
| return reader.read(avro.io.BinaryDecoder(io.BytesIO(data))) | ||
|
|
||
| def test_deeply_nested_input_rejected_with_bounded_error(self) -> None: | ||
| # ~100k levels: far beyond the default depth limit and enough to overflow | ||
| # the stack if it were left unbounded, yet only ~100kB of input. Must fail | ||
| # with a bounded AvroException rather than a RecursionError / crash. | ||
| bomb = self._linked_list(100_000) | ||
| self.assertRaises(avro.errors.AvroException, self._read, bomb) | ||
|
|
||
| def test_moderately_nested_input_within_limit_still_decodes(self) -> None: | ||
| # Two structural descents (union + record) are counted per list level, so | ||
| # keep the level count well under half the default limit. | ||
| result = self._read(self._linked_list(20)) | ||
| self.assertIsInstance(result, dict) | ||
|
|
||
| def test_deeply_nested_input_rejected_when_skipped(self) -> None: | ||
| # The skip path (a writer-only field during resolution) descends | ||
| # recursively too and must be bounded as well. | ||
| bomb = self._linked_list(100_000) | ||
| reader = avro.io.DatumReader(self.NODE, self.NODE) | ||
| decoder = avro.io.BinaryDecoder(io.BytesIO(bomb)) | ||
| self.assertRaises(avro.errors.AvroException, reader.skip_data, self.NODE, decoder) | ||
|
|
||
| def test_custom_depth_limit_env_is_honored(self) -> None: | ||
| import os | ||
|
|
||
| prior = os.environ.get(avro.io.MAX_DECODE_DEPTH_ENV) | ||
| os.environ[avro.io.MAX_DECODE_DEPTH_ENV] = "6" | ||
| try: | ||
| # 6 allows only 3 list levels (2 descents each); 10 levels must fail. | ||
| self.assertRaises(avro.errors.AvroException, self._read, self._linked_list(10)) | ||
| finally: | ||
| # Restore any pre-existing value instead of unconditionally clearing it. | ||
| if prior is None: | ||
| del os.environ[avro.io.MAX_DECODE_DEPTH_ENV] | ||
| else: | ||
| os.environ[avro.io.MAX_DECODE_DEPTH_ENV] = prior | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.