Skip to content

Commit 45ee085

Browse files
committed
Fix multipart upload validation edge cases
1 parent 833ebd9 commit 45ee085

6 files changed

Lines changed: 87 additions & 26 deletions

File tree

‎socketdev/dependencies/__init__.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ def __init__(self, api):
1515

1616
def post(self, files: list, params: dict, use_lazy_loading: bool = True, workspace: str = None, base_path: str = None) -> dict:
1717
if use_lazy_loading:
18-
loaded_files = Utils.load_files_for_sending_lazy(files, workspace, base_path=base_path)
18+
loaded_files = Utils.load_files_for_sending_lazy(
19+
files, workspace, base_path=base_path, reject_duplicate_keys=False
20+
)
1921
else:
2022
loaded_files = []
2123
loaded_files = load_files(files, loaded_files)

‎socketdev/diffscans/__init__.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,9 @@ def create_from_repo(self, org_slug: str, repo_slug: str, files: list, params: O
9999

100100
# Use lazy loading if requested
101101
if use_lazy_loading:
102-
prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files, base_path, base_paths)
102+
prepared_files = Utils.load_files_for_sending_lazy(
103+
files, workspace, max_open_files, base_path, base_paths, reject_duplicate_keys=False
104+
)
103105
else:
104106
prepared_files = files
105107

‎socketdev/fullscans/__init__.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -856,7 +856,7 @@ def post(
856856
Create a new full scan by uploading manifest files.
857857
858858
Args:
859-
files: List of file paths to upload for scanning
859+
files: Multipart entries for Requests, or file paths when using lazy loading
860860
params: FullScanParams object containing scan configuration
861861
use_types: Whether to return typed response objects (default: False)
862862
use_lazy_loading: Whether to use lazy file loading to prevent "too many open files"
@@ -905,24 +905,23 @@ def post(
905905
if use_lazy_loading:
906906
prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files, base_path, base_paths)
907907
else:
908-
# This mode accepts requests-style multipart entries already prepared by callers.
909908
is_mapping = hasattr(files, "items")
910909
entries = list(files.items()) if is_mapping else list(files or [])
911910
key_sources = []
912911
for key, value in entries:
913912
if isinstance(value, (tuple, list)):
914913
filename, content = value[:2]
915-
source = getattr(content, "name", filename)
914+
source = filename if filename is not None else key
916915
else:
917916
content = value
918-
source = getattr(content, "name", key)
917+
source = getattr(content, "name", None) or key
919918
# Requests omits parts with no content and decodes byte field names as UTF-8.
920919
if content is None:
921920
continue
922921
normalized_key = key.decode("utf-8") if isinstance(key, bytes) else key
923922
key_sources.append((normalized_key, source))
924923
Utils.validate_upload_keys(key_sources)
925-
# Validation must not consume a one-shot iterable before Requests encodes it.
924+
# Forward the collected entries for one-shot iterables.
926925
prepared_files = files if files is None or is_mapping or isinstance(files, (list, tuple)) else entries
927926

928927
response = self.api.do_request(path=path, method="POST", files=prepared_files)

‎socketdev/uploadmanifests/__init__.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace:
5050
else:
5151
# Fallback to basic file loading if needed
5252
loaded_files = []
53-
key_sources = Utils.prepare_upload_keys(valid_files, workspace, base_path, base_paths)
53+
key_sources = Utils.calculate_upload_keys(valid_files, workspace, base_path, base_paths)
54+
Utils.validate_upload_keys(key_sources)
5455
for key, file_path in key_sources:
5556
with open(file_path, 'rb') as f:
5657
loaded_files.append((key, (key, f.read())))
@@ -69,4 +70,4 @@ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace:
6970
raise Exception("Server did not return a tarHash")
7071

7172
log.info(f"Successfully uploaded {len(valid_files)} manifest files, tarHash: {tar_hash}")
72-
return tar_hash
73+
return tar_hash

‎socketdev/utils/__init__.py‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,9 @@ def _normalize_upload_options(workspace, base_path, base_paths):
255255

256256
@staticmethod
257257
def _calculate_normalized_upload_key(file_path, workspace, base_path, base_paths):
258-
# Calculate the key name for the form data
259258
key = file_path
260259
path_stripped = False
261260

262-
# If base_paths is provided, try to strip one of the paths from the file path
263261
if base_paths:
264262
for bp in base_paths:
265263
normalized_base_path = bp.rstrip("/") + "/" if not bp.endswith("/") else bp
@@ -286,10 +284,9 @@ def _calculate_normalized_upload_key(file_path, workspace, base_path, base_paths
286284
key = key.lstrip("/")
287285
path_stripped = True
288286

289-
# If workspace is provided and no base paths matched, fall back to workspace logic
287+
# Use the workspace when no base path matched.
290288
if not path_stripped and workspace and file_path.startswith(workspace):
291289
key = file_path[len(workspace):]
292-
# Remove all leading slashes (for absolute paths)
293290
while key.startswith("/"):
294291
key = key[1:]
295292
path_stripped = True
@@ -299,7 +296,6 @@ def _calculate_normalized_upload_key(file_path, workspace, base_path, base_paths
299296
key = key[2:]
300297
while key.startswith("../"):
301298
key = key[3:]
302-
# Remove any remaining leading slashes (for absolute paths)
303299
while key.startswith("/"):
304300
key = key[1:]
305301

@@ -319,7 +315,7 @@ def validate_upload_keys(key_sources: List[Tuple[str, str]]) -> None:
319315
for key, source in key_sources:
320316
if key is None:
321317
continue
322-
# Use the installed encoder's escaping rules; the result is name="<key>".
318+
# Extract the escaped value from the encoder's name="<key>" parameter.
323319
wire_key = formatter("name", key)[6:-1]
324320
if wire_key in seen:
325321
raise ValueError(
@@ -328,18 +324,24 @@ def validate_upload_keys(key_sources: List[Tuple[str, str]]) -> None:
328324
seen[wire_key] = source
329325

330326
@staticmethod
331-
def prepare_upload_keys(files: List[str], workspace: Optional[str] = None, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None) -> List[Tuple[str, str]]:
332-
"""Compute and validate all keys before reading any file contents."""
327+
def calculate_upload_keys(files: List[str], workspace: Optional[str] = None, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None) -> List[Tuple[str, str]]:
328+
"""Pair each multipart field name with its original source path."""
333329
workspace, base_path, base_paths = Utils._normalize_upload_options(workspace, base_path, base_paths)
334-
key_sources = [
330+
return [
335331
(Utils._calculate_normalized_upload_key(path.replace("\\", "/"), workspace, base_path, base_paths), path)
336332
for path in files
337333
]
338-
Utils.validate_upload_keys(key_sources)
339-
return key_sources
340334

341335
@staticmethod
342-
def load_files_for_sending_lazy(files: List[str], workspace: Optional[str] = None, max_open_files: int = 100, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
336+
def load_files_for_sending_lazy(
337+
files: List[str],
338+
workspace: Optional[str] = None,
339+
max_open_files: int = 100,
340+
base_path: Optional[str] = None,
341+
base_paths: Optional[List[str]] = None,
342+
*,
343+
reject_duplicate_keys: bool = True,
344+
) -> List[Tuple[str, Tuple[str, LazyFileLoader]]]:
343345
"""
344346
Prepares files for sending to the Socket API using lazy loading.
345347
@@ -354,21 +356,24 @@ def load_files_for_sending_lazy(files: List[str], workspace: Optional[str] = Non
354356
max_open_files: Maximum number of files to keep open simultaneously (default: 100)
355357
base_path: Optional base path to strip from key names for cleaner file organization
356358
base_paths: Optional list of base paths to strip from key names (takes precedence over base_path)
359+
reject_duplicate_keys: Whether to reject repeated multipart field names
357360
358361
Returns:
359362
List of tuples formatted for requests multipart upload:
360363
[(field_name, (filename, lazy_file_object)), ...]
361364
362365
Raises:
363-
ValueError: If two source paths produce the same upload key.
366+
ValueError: If duplicate-key rejection is enabled and two paths produce the same key.
364367
"""
365-
# Configure the file descriptor manager with the specified limit
368+
upload_files = [path for path in files if not os.path.isdir(path.replace("\\", "/"))]
369+
key_sources = Utils.calculate_upload_keys(upload_files, workspace, base_path, base_paths)
370+
if reject_duplicate_keys:
371+
Utils.validate_upload_keys(key_sources)
372+
373+
# Changing the shared limit can close files belonging to other uploads.
366374
_fd_manager.set_max_open_files(max_open_files)
367375

368376
send_files = []
369-
# Directories do not produce multipart parts, so exclude them before validating keys.
370-
upload_files = [path for path in files if not os.path.isdir(path.replace("\\", "/"))]
371-
key_sources = Utils.prepare_upload_keys(upload_files, workspace, base_path, base_paths)
372377
for key, source_path in key_sources:
373378
file_path = source_path.replace("\\", "/")
374379

‎tests/unit/test_duplicate_upload_keys.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@
22

33
from collections import UserDict
44
from io import BytesIO
5+
from tempfile import SpooledTemporaryFile
56
from unittest.mock import Mock, patch
67

78
import pytest
89
from requests import Request
910
from urllib3.fields import RequestField
1011

12+
from socketdev.dependencies import Dependencies
13+
from socketdev.diffscans import DiffScans
1114
from socketdev.fullscans import FullScans, FullScanParams
1215
from socketdev.uploadmanifests import UploadManifests
1316
from socketdev.utils import Utils
@@ -40,6 +43,13 @@ def test_lazy_utility_rejects_collisions_before_creating_loaders(paths, options,
4043
loader.assert_not_called()
4144

4245

46+
def test_lazy_utility_rejects_collisions_before_changing_descriptor_limit():
47+
with patch("socketdev.utils._fd_manager") as manager:
48+
with pytest.raises(ValueError, match="Duplicate upload key"):
49+
Utils.load_files_for_sending_lazy(["package.json"] * 2, max_open_files=1)
50+
manager.set_max_open_files.assert_not_called()
51+
52+
4353
@pytest.mark.parametrize("paths,options,key", COLLISIONS)
4454
@pytest.mark.parametrize("lazy", [True, False])
4555
def test_manifest_upload_rejects_collisions_before_reading_or_sending(paths, options, key, lazy):
@@ -107,6 +117,22 @@ def test_lazy_utility_skips_directories(tmp_path):
107117
assert Utils.load_files_for_sending_lazy([directory, directory]) == []
108118

109119

120+
@pytest.mark.parametrize("endpoint", ["dependencies", "diffscans"])
121+
def test_other_lazy_endpoints_preserve_repeated_fields(endpoint, tmp_path):
122+
path = tmp_path / "package.json"
123+
path.write_bytes(b"{}")
124+
files = [str(path)] * 2
125+
api = Mock()
126+
api.do_request.return_value.status_code = 200
127+
if endpoint == "dependencies":
128+
Dependencies(api).post(files, {}, base_path=str(tmp_path))
129+
else:
130+
DiffScans(api).create_from_repo("org", "repo", files, use_lazy_loading=True, base_path=str(tmp_path))
131+
forwarded = api.do_request.call_args.kwargs["files"]
132+
body = Request("POST", "https://example.test", files=forwarded).prepare().body
133+
assert body.count(b'name="package.json";') == 2
134+
135+
110136
def test_prepared_fullscan_rejects_duplicate_keys():
111137
api = Mock()
112138
files = [("package.json", (path, BytesIO(b"{}"))) for path in ("/a/package.json", "/b/package.json")]
@@ -117,6 +143,32 @@ def test_prepared_fullscan_rejects_duplicate_keys():
117143
api.do_request.assert_not_called()
118144

119145

146+
def test_prepared_fullscan_reports_explicit_filenames_for_spooled_parts():
147+
api = Mock()
148+
paths = ["/a/package.json", "/b/package.json"]
149+
with SpooledTemporaryFile() as first, SpooledTemporaryFile() as second:
150+
files = [("package.json", (paths[0], first)), ("package.json", (paths[1], second))]
151+
with pytest.raises(ValueError) as error:
152+
FullScans(api).post(files, FullScanParams(repo="repo", org_slug="org"))
153+
assert_collision(error, "package.json", paths)
154+
api.do_request.assert_not_called()
155+
156+
157+
def test_prepared_fullscan_uses_explicit_filename_without_accessing_stream_name():
158+
class Stream(BytesIO):
159+
@property
160+
def name(self):
161+
raise RuntimeError("Stream name is unavailable")
162+
163+
api = Mock()
164+
api.do_request.return_value.status_code = 201
165+
files = [("package.json", ("package.json", Stream(b"{}")))]
166+
FullScans(api).post(files, FullScanParams(repo="repo", org_slug="org"))
167+
forwarded = api.do_request.call_args.kwargs["files"]
168+
body = Request("POST", "https://example.test", files=forwarded).prepare().body
169+
assert b'name="package.json"; filename="package.json"' in body
170+
171+
120172
@pytest.mark.parametrize("mapping", [True, False])
121173
def test_prepared_fullscan_preserves_valid_files(mapping):
122174
api = Mock()

0 commit comments

Comments
 (0)