fix(security): prevent path traversal and add memory-efficient file handling #1066
+145
−14
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.
Summary
Fixes two HIGH priority security and performance issues in file directory handling.
1. Path Traversal Vulnerability (HIGH)
The
files_from_dir()andasync_files_from_dir()functions did not check for symlinks, allowing path traversal attacks:/etc/passwdcould be read and uploadedevil_link/passwdFix: Resolve all paths and verify they remain within the root directory.
2. Memory Exhaustion (MEDIUM)
The functions loaded entire directory trees into memory simultaneously:
read_bytes()and stored in a listFix: Added new streaming iterator versions that yield files one at a time:
files_from_dir_iter()- synchronous generatorasync_files_from_dir_iter()- async generatorOriginal functions preserved for backwards compatibility.
Implementation Details
Python 3.8 Compatibility
_is_path_within_root()helper functionpath.relative_to()+ try/except instead ofPath.is_relative_to()is_relative_to()was added in Python 3.9, but this SDK supports Python 3.8+Async Path Handling
await anyio.Path.resolve()returns a standardpathlib.Path, notanyio.Pathawaitusage on synchronous Path methodsanyio.PathandPathtypesError Handling
PermissionErrorandOSErrorChanges
src/anthropic/lib/_files.py:_is_path_within_root()for Python 3.8-compatible containment checkspath.resolve()and containment validation to all functionsfiles_from_dir_iter()for memory-efficient streamingasync_files_from_dir_iter()for async streamingTesting
Impact