Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changelog

## 3.6.5

### Fixed: reject duplicate multipart upload keys

- Manifest uploads and full scans now raise `ValueError` before sending a
request when multiple files map to the same multipart field name. The error
includes the colliding key and both source paths; files are never silently
dropped. Key calculation is shared by lazy and eager manifest uploads.

## 3.6.4

### Fixed: every advisory on a package is kept
Expand Down
4 changes: 3 additions & 1 deletion socketdev/dependencies/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ def __init__(self, api):

def post(self, files: list, params: dict, use_lazy_loading: bool = True, workspace: str = None, base_path: str = None) -> dict:
if use_lazy_loading:
loaded_files = Utils.load_files_for_sending_lazy(files, workspace, base_path=base_path)
loaded_files = Utils.load_files_for_sending_lazy(
files, workspace, base_path=base_path, reject_duplicate_keys=False
)
else:
loaded_files = []
loaded_files = load_files(files, loaded_files)
Expand Down
4 changes: 3 additions & 1 deletion socketdev/diffscans/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ def create_from_repo(self, org_slug: str, repo_slug: str, files: list, params: O

# Use lazy loading if requested
if use_lazy_loading:
prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files, base_path, base_paths)
prepared_files = Utils.load_files_for_sending_lazy(
files, workspace, max_open_files, base_path, base_paths, reject_duplicate_keys=False
)
else:
prepared_files = files

Expand Down
24 changes: 22 additions & 2 deletions socketdev/fullscans/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,7 @@ def post(
Create a new full scan by uploading manifest files.

Args:
files: List of file paths to upload for scanning
files: Multipart entries for Requests, or file paths when using lazy loading
params: FullScanParams object containing scan configuration
use_types: Whether to return typed response objects (default: False)
use_lazy_loading: Whether to use lazy file loading to prevent "too many open files"
Expand All @@ -871,6 +871,9 @@ def post(
Returns:
dict or CreateFullScanResponse: API response containing scan results

Raises:
ValueError: If two files have the same multipart upload key.

Note:
When use_lazy_loading=True, files are opened only when needed during upload,
preventing file descriptor exhaustion. The max_open_files parameter controls how many
Expand Down Expand Up @@ -902,7 +905,24 @@ def post(
if use_lazy_loading:
prepared_files = Utils.load_files_for_sending_lazy(files, workspace, max_open_files, base_path, base_paths)
else:
prepared_files = files
is_mapping = hasattr(files, "items")
entries = list(files.items()) if is_mapping else list(files or [])
key_sources = []
for key, value in entries:
if isinstance(value, (tuple, list)):
filename, content = value[:2]
source = filename if filename is not None else key
else:
content = value
source = getattr(content, "name", None) or key
# Requests omits parts with no content and decodes byte field names as UTF-8.
if content is None:
continue
normalized_key = key.decode("utf-8") if isinstance(key, bytes) else key
key_sources.append((normalized_key, source))
Utils.validate_upload_keys(key_sources)
# Forward the collected entries for one-shot iterables.
prepared_files = files if files is None or is_mapping or isinstance(files, (list, tuple)) else entries

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

Expand Down
82 changes: 7 additions & 75 deletions socketdev/uploadmanifests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,77 +11,8 @@ def __init__(self, api):
self.api = api

def _calculate_key_name(self, file_path: str, workspace: Optional[str] = None, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None) -> str:
"""
Calculate the key name for a file using the same logic as load_files_for_sending_lazy.
This ensures consistency between lazy and non-lazy loading modes.
"""
# Normalize file path
if "\\" in file_path:
file_path = file_path.replace("\\", "/")

# Normalize paths
if workspace and "\\" in workspace:
workspace = workspace.replace("\\", "/")
if base_path and "\\" in base_path:
base_path = base_path.replace("\\", "/")
if base_paths:
base_paths = [bp.replace("\\", "/") if "\\" in bp else bp for bp in base_paths]

# Calculate the key name for the form data
key = file_path
path_stripped = False

# If base_paths is provided, try to strip one of the paths from the file path
if base_paths:
for bp in base_paths:
normalized_base_path = bp.rstrip("/") + "/" if not bp.endswith("/") else bp
if key.startswith(normalized_base_path):
key = key[len(normalized_base_path):]
path_stripped = True
break
elif key.startswith(bp.rstrip("/")):
stripped_base = bp.rstrip("/")
if key.startswith(stripped_base + "/") or key == stripped_base:
key = key[len(stripped_base):]
key = key.lstrip("/")
path_stripped = True
break
elif base_path:
normalized_base_path = base_path.rstrip("/") + "/" if not base_path.endswith("/") else base_path
if key.startswith(normalized_base_path):
key = key[len(normalized_base_path):]
path_stripped = True
elif key.startswith(base_path.rstrip("/")):
stripped_base = base_path.rstrip("/")
if key.startswith(stripped_base + "/") or key == stripped_base:
key = key[len(stripped_base):]
key = key.lstrip("/")
path_stripped = True

# If workspace is provided and no base paths matched, fall back to workspace logic
if not path_stripped and workspace and file_path.startswith(workspace):
key = file_path[len(workspace):]
# Remove all leading slashes (for absolute paths)
while key.startswith("/"):
key = key[1:]
path_stripped = True

# Clean up relative path prefixes, but preserve filename dots
while key.startswith("./"):
key = key[2:]
while key.startswith("../"):
key = key[3:]
# Remove any remaining leading slashes (for absolute paths)
while key.startswith("/"):
key = key[1:]

# Remove Windows drive letter if present (C:/...)
if len(key) > 2 and key[1] == ':' and (key[2] == '/' or key[2] == '\\'):
key = key[2:]
while key.startswith("/"):
key = key[1:]

return key
"""Calculate a multipart key using the shared upload path logic."""
return Utils.calculate_upload_key(file_path, workspace, base_path, base_paths)

def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace: Optional[str] = None, base_path: Optional[str] = None, base_paths: Optional[List[str]] = None, use_lazy_loading: bool = True) -> str:
"""
Expand All @@ -99,6 +30,7 @@ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace:
str: The tarHash from the upload response

Raises:
ValueError: If two source paths produce the same upload key.
Exception: If upload fails
"""
# Filter to only existing files
Expand All @@ -118,9 +50,9 @@ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace:
else:
# Fallback to basic file loading if needed
loaded_files = []
for file_path in valid_files:
# Use the same key generation logic as lazy loading for consistency
key = self._calculate_key_name(file_path, workspace, base_path, base_paths)
key_sources = Utils.calculate_upload_keys(valid_files, workspace, base_path, base_paths)
Utils.validate_upload_keys(key_sources)
for key, file_path in key_sources:
with open(file_path, 'rb') as f:
loaded_files.append((key, (key, f.read())))

Expand All @@ -138,4 +70,4 @@ def upload_manifest_files(self, org_slug: str, file_paths: List[str], workspace:
raise Exception("Server did not return a tarHash")

log.info(f"Successfully uploaded {len(valid_files)} manifest files, tarHash: {tar_hash}")
return tar_hash
return tar_hash
Loading