Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(py): send Content-Type on S3 PUTs and parse Content-Length (#4168)
Alberto Schiabelb1c6671b205a
diff --git a/python/composio/core/models/_files.py b/python/composio/core/models/_files.pyindex cd3dcbd5a..245a0c9c7 100644--- a/python/composio/core/models/_files.py+++ b/python/composio/core/models/_files.py@@ -1,7 +1,6 @@from __future__ import annotationsimport hashlib-import loggingimport osimport typing as tfrom pathlib import Path@@ -27,7 +26,11 @@ from composio.exceptions import (from composio.utils import mimetypesfrom composio.utils.json_schema import dereference_json_schemafrom composio.utils.safe_path import secure_basename_join, secure_join-from composio.utils.url_safety import assert_safe_fetch_target, safe_request+from composio.utils.url_safety import (+ assert_safe_fetch_target,+ parse_content_length,+ safe_request,+)from composio.utils.sensitive_file_upload_paths import (assert_safe_local_file_upload_path,)@@ -55,8 +58,6 @@ Maximum response size in bytes when fetching files from URLs.Prevents memory exhaustion attacks from malicious URLs pointing to large files."""-_logger = logging.getLogger(__name__)-_CONNECT_TIMEOUT = 5 # seconds_READ_TIMEOUT = 60 # seconds"""@@ -191,32 +192,67 @@ def get_md5(file: Path) -> str:return obj.hexdigest()-def upload(url: str, file: Path) -> bool:+def _upload_to_presigned_url(+ url: str, data: t.Union[bytes, t.IO[bytes]], mimetype: str+) -> None:+ """PUT ``data`` to a presigned S3 URL with the content type it was signed with.++ The presign request carries ``mimetype``, so the PUT must send the same+ value as ``Content-Type``: when the signature covers the content type, a+ mismatched or missing header is rejected with ``403 SignatureDoesNotMatch``.+ Routing every presigned PUT through one helper keeps the file and bytes+ upload paths from drifting apart again, mirroring ``uploadFileToS3`` in+ the TypeScript SDK, which funnels path, URL, and File inputs through a+ single uploader.++ Raises:+ ErrorUploadingFile: On transport failure or a non-200 response,+ including the HTTP status when one was received.+ """+ try:+ response = safe_request(+ "PUT",+ url,+ data=data,+ headers={"Content-Type": mimetype},+ timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),+ )+ except requests.exceptions.RequestException as e:+ raise ErrorUploadingFile(+ "Failed to upload to S3: "+ f"{_sanitize_url_for_logging(url)}. Error: {type(e).__name__}"+ ) from e+ if response.status_code != 200:+ raise ErrorUploadingFile(+ f"Failed to upload to S3. Status: {response.status_code}. "+ "This may indicate an expired presigned URL or permission issue."+ )+++def upload(url: str, file: Path, mimetype: t.Optional[str] = None) -> bool:"""Upload file to presigned S3 URL.Args:url: Presigned S3 upload URLfile: Path to file to upload+ mimetype: Content type to send with the upload. Defaults to the type+ guessed from ``file``. This must match the ``mimetype`` the+ presigned URL was requested with, otherwise S3 rejects the PUT+ with ``403 SignatureDoesNotMatch`` when the signature covers the+ content type.Returns:- True if upload succeeded (HTTP 200), False otherwise+ True if the upload succeeded.++ Raises:+ ErrorUploadingFile: If the upload fails; the message includes the+ HTTP status when one was received."""+ if mimetype is None:+ mimetype = mimetypes.guess(file=file)with file.open("rb") as data:- try:- response = safe_request(- "PUT",- url,- data=data,- timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),- )- except requests.exceptions.RequestException as e:- _logger.debug(- "Upload to %s failed: %s",- _sanitize_url_for_logging(url),- type(e).__name__,- )- return False- return response.status_code == 200+ _upload_to_presigned_url(url=url, data=data, mimetype=mimetype)+ return Trueclass _FileUploadResponse(_ComposioBaseModel):@@ -226,6 +262,33 @@ class _FileUploadResponse(_ComposioBaseModel):new_presigned_url: str+def _request_presigned_upload(+ client: HttpClient,+ *,+ filename: str,+ md5: str,+ mimetype: str,+ tool: str,+ toolkit: str,+) -> _FileUploadResponse:+ """Request a presigned S3 upload URL from the backend.++ Single-sources the presign wire shape so the file and bytes upload paths+ request the same fields they later send.+ """+ return client.post(+ path=_FILE_UPLOAD,+ body={+ "md5": md5,+ "filename": filename,+ "mimetype": mimetype,+ "tool_slug": tool,+ "toolkit_slug": toolkit,+ },+ cast_to=_FileUploadResponse,+ )++def _is_url(value: str) -> bool:"""Check if a string is a valid HTTP/HTTPS URL."""try:@@ -371,12 +434,15 @@ def _fetch_file_from_url(f"Status: {response.status_code}")- # Check Content-Length header first (early abort for oversized files)- content_length = response.headers.get("Content-Length")- if content_length and int(content_length) > max_size:+ # Check Content-Length header first (early abort for oversized files).+ # The header is a hint from the remote server: `parse_content_length`+ # returns None for anything untrustworthy, and the streaming guard below+ # is the authoritative limit.+ content_length = parse_content_length(response.headers.get("Content-Length"))+ if content_length is not None and content_length > max_size:response.close()raise ResponseTooLargeError(- f"File size ({int(content_length)} bytes) exceeds maximum allowed "+ f"File size ({content_length} bytes) exceeds maximum allowed "f"size ({max_size} bytes)")@@ -435,42 +501,17 @@ def _upload_bytes_to_s3(toolkit: str,) -> str:"""Upload bytes content to S3 and return the S3 key."""- md5_hash = hashlib.md5(content, usedforsecurity=False).hexdigest()-- s3meta = client.post(- path=_FILE_UPLOAD,- body={- "md5": md5_hash,- "filename": filename,- "mimetype": mimetype,- "tool_slug": tool,- "toolkit_slug": toolkit,- },- cast_to=_FileUploadResponse,+ s3meta = _request_presigned_upload(+ client,+ filename=filename,+ md5=hashlib.md5(content, usedforsecurity=False).hexdigest(),+ mimetype=mimetype,+ tool=tool,+ toolkit=toolkit,+ )+ _upload_to_presigned_url(+ url=s3meta.new_presigned_url, data=content, mimetype=mimetype)-- # Upload the content directly to S3- try:- upload_response = safe_request(- "PUT",- s3meta.new_presigned_url,- data=content,- headers={"Content-Type": mimetype},- timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),- )- except requests.exceptions.RequestException as e:- raise ErrorUploadingFile(- "Failed to upload to S3: "- f"{_sanitize_url_for_logging(s3meta.new_presigned_url)}. "- f"Error: {type(e).__name__}"- ) from e-- if upload_response.status_code != 200:- raise ErrorUploadingFile(- f"Failed to upload to S3. Status: {upload_response.status_code}. "- f"This may indicate an expired presigned URL or permission issue."- )-return s3meta.key@@ -611,19 +652,15 @@ class FileUploadable(BaseModel):)mimetype = mimetypes.guess(file=file)- s3meta = client.post(- path=_FILE_UPLOAD,- body={- "md5": get_md5(file=file),- "filename": file.name,- "mimetype": mimetype,- "tool_slug": tool,- "toolkit_slug": toolkit,- },- cast_to=_FileUploadResponse,+ s3meta = _request_presigned_upload(+ client,+ filename=file.name,+ md5=get_md5(file=file),+ mimetype=mimetype,+ tool=tool,+ toolkit=toolkit,)- if not upload(url=s3meta.new_presigned_url, file=file):- raise ErrorUploadingFile(f"Error uploading file: {file}")+ upload(url=s3meta.new_presigned_url, file=file, mimetype=mimetype)return cls(name=file.name, mimetype=mimetype, s3key=s3meta.key)diff --git a/python/composio/core/models/tool_router_session_files.py b/python/composio/core/models/tool_router_session_files.pyindex 4f4d117ff..1668e6d65 100644--- a/python/composio/core/models/tool_router_session_files.py+++ b/python/composio/core/models/tool_router_session_files.py@@ -29,7 +29,11 @@ from composio.exceptions import ()from composio.utils.mimetypes import get_extension_from_mime_typefrom composio.utils.safe_path import secure_basename_join-from composio.utils.url_safety import assert_safe_fetch_target, safe_request+from composio.utils.url_safety import (+ assert_safe_fetch_target,+ parse_content_length,+ safe_request,+)from composio.utils.uuid import generate_short_idDEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID = "files"@@ -107,12 +111,12 @@ def _fetch_url_bytes(url: str) -> t.Tuple[bytes, str]:status_code=response.status_code, status_text=response.reason)- content_length = response.headers.get("Content-Length")- if content_length and int(content_length) > _MAX_RESPONSE_SIZE:+ content_length = parse_content_length(response.headers.get("Content-Length"))+ if content_length is not None and content_length > _MAX_RESPONSE_SIZE:response.close()raise _UrlFetchError(size_detail=(- f"File size ({int(content_length)} bytes) exceeds maximum allowed "+ f"File size ({content_length} bytes) exceeds maximum allowed "f"size ({_MAX_RESPONSE_SIZE} bytes)"))diff --git a/python/composio/utils/url_safety.py b/python/composio/utils/url_safety.pyindex 67d00a2e8..bdfd599b6 100644--- a/python/composio/utils/url_safety.py+++ b/python/composio/utils/url_safety.py@@ -15,6 +15,11 @@ pass this check and still connect to the private address. Closing that windowrequires pinning the validated address and connecting to it directly (a custom``requests`` transport adapter), which is out of scope for this module; theTypeScript guard carries the same limitation.++Also parses response headers that gate how much of a body the SDK reads:+``parse_content_length`` treats ``Content-Length`` as the untrusted hint it+is, so a malformed value degrades to an unknown size under a streamed byte+count instead of crashing the fetch."""from __future__ import annotations@@ -91,6 +96,27 @@ def assert_safe_fetch_target(url: str) -> None:)+def parse_content_length(value: t.Optional[str]) -> t.Optional[int]:+ """Parse a ``Content-Length`` header into a non-negative ``int``.++ ``Content-Length`` is supplied by the remote server and is therefore+ untrusted: it may be absent, non-numeric (``"abc"``), fractional+ (``"12.5"``), thousands-separated (``"1,024"``) or negative. Anything+ untrustworthy returns ``None`` so the caller treats the size as unknown+ and falls through to a streamed byte count, which stays authoritative+ because the header can also be absent or understated. Mirrors+ ``readResponseBodyWithLimit`` in the TypeScript SDK, which only trusts+ values matching ``/^\\d+$/``.+ """+ if value is None:+ return None+ try:+ size = int(value.strip())+ except ValueError:+ return None+ return size if size >= 0 else None++def safe_request(method: str,url: str,diff --git a/python/tests/test_file_upload_robustness.py b/python/tests/test_file_upload_robustness.pynew file mode 100644index 000000000..2361f6749--- /dev/null+++ b/python/tests/test_file_upload_robustness.py@@ -0,0 +1,221 @@+"""Regression tests for file upload and URL fetch robustness.++Covers https://github.com/ComposioHQ/composio/issues/4153: a malformed+``Content-Length`` response header must not crash the URL fetch helpers with+a raw ``ValueError``, and the local-file presigned PUT must send the+``Content-Type`` it was signed with. The shared helpers under test keep the+fetch and upload paths from drifting apart again.+"""++import typing as t+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+import requests++from composio.core.models._files import (+ FileUploadable,+ _fetch_file_from_url,+ upload,+)+from composio.core.models.base import allow_tracking+from composio.exceptions import ErrorUploadingFile, ResponseTooLargeError+from composio.utils import mimetypes+from composio.utils.url_safety import parse_content_length++[email protected](autouse=True)+def disable_telemetry():+ """Disable telemetry for all tests to prevent thread issues."""+ token = allow_tracking.set(False)+ yield+ allow_tracking.reset(token)+++def _stream_response(+ headers: t.Dict[str, str],+ chunks: t.Optional[t.List[bytes]] = None,+) -> MagicMock:+ """A streaming `requests` response double, as `_fetch_file_from_url` reads it."""+ response = MagicMock()+ response.ok = True+ response.status_code = 200+ response.headers = headers+ response.iter_content.return_value = chunks if chunks is not None else [b"payload"]+ response.close = MagicMock()+ return response+++def _s3_client(presigned_url: str = "https://s3.example.com/upload") -> MagicMock:+ """A mock HTTP client whose presign POST answers a fresh upload URL."""+ client = MagicMock()+ s3meta = MagicMock()+ s3meta.key = "s3-key-123"+ s3meta.new_presigned_url = presigned_url+ client.post.return_value = s3meta+ return client+++class TestPresignedUploadContentType:+ """The PUT must send the content type the presigned URL was signed with."""++ @patch("composio.core.models._files.safe_request")+ def test_upload_sends_explicit_mimetype(+ self, mock_safe_request: MagicMock, tmp_path: Path+ ):+ mock_safe_request.return_value = MagicMock(status_code=200)+ source = tmp_path / "report.pdf"+ source.write_bytes(b"%PDF-1.4")++ assert upload(+ url="https://s3.example.com/upload",+ file=source,+ mimetype="application/pdf",+ )++ assert mock_safe_request.call_args.args == (+ "PUT",+ "https://s3.example.com/upload",+ )+ assert mock_safe_request.call_args.kwargs["headers"] == {+ "Content-Type": "application/pdf"+ }+ assert mock_safe_request.call_args.kwargs["timeout"] == (5, 60)++ @patch("composio.core.models._files.safe_request")+ def test_upload_guesses_mimetype_when_omitted(+ self, mock_safe_request: MagicMock, tmp_path: Path+ ):+ """Back-compat: two-argument callers still send a Content-Type."""+ mock_safe_request.return_value = MagicMock(status_code=200)+ source = tmp_path / "notes.txt"+ source.write_text("hello")++ assert upload(url="https://s3.example.com/upload", file=source)++ assert mock_safe_request.call_args.kwargs["headers"] == {+ "Content-Type": mimetypes.guess(file=source)+ }++ @patch("composio.core.models._files.safe_request")+ def test_from_path_put_matches_presigned_mimetype(+ self, mock_safe_request: MagicMock, tmp_path: Path+ ):+ """The PUT content type must match the mimetype used to mint the URL.++ S3 answers ``403 SignatureDoesNotMatch`` when a presigned URL is+ signed over a content type the subsequent PUT does not send, which+ made the local-file path fail where the bytes path succeeded.+ """+ mock_safe_request.return_value = MagicMock(status_code=200)+ client = _s3_client()+ source = tmp_path / "photo.jpg"+ source.write_bytes(b"jpeg bytes")++ result = FileUploadable.from_path(+ client=client,+ file=source,+ tool="TEST_TOOL",+ toolkit="test_toolkit",+ )++ presigned_mimetype = client.post.call_args.kwargs["body"]["mimetype"]+ assert presigned_mimetype == mimetypes.guess(file=source)+ assert mock_safe_request.call_args.kwargs["headers"] == {+ "Content-Type": presigned_mimetype+ }+ assert result.mimetype == presigned_mimetype+ assert result.s3key == "s3-key-123"++ @patch("composio.core.models._files.safe_request")+ def test_upload_surfaces_http_status(+ self, mock_safe_request: MagicMock, tmp_path: Path+ ):+ """A rejected PUT raises with the status instead of returning False."""+ mock_safe_request.return_value = MagicMock(status_code=403)+ source = tmp_path / "report.pdf"+ source.write_bytes(b"%PDF-1.4")++ with pytest.raises(ErrorUploadingFile, match="403"):+ upload(url="https://s3.example.com/upload", file=source)++ @patch("composio.core.models._files.safe_request")+ def test_upload_wraps_transport_errors_without_leaking_the_url(+ self, mock_safe_request: MagicMock, tmp_path: Path+ ):+ mock_safe_request.side_effect = requests.exceptions.Timeout(+ "HTTPSConnectionPool(host='s3.example.com', port=443): "+ "Max retries exceeded with url: /upload?token=abc"+ )+ source = tmp_path / "report.pdf"+ source.write_bytes(b"%PDF-1.4")++ with pytest.raises(ErrorUploadingFile) as exc_info:+ upload(url="https://s3.example.com/upload?token=abc", file=source)++ assert "Failed to upload to S3" in str(exc_info.value)+ assert "token=abc" not in str(exc_info.value)+++class TestParseContentLength:+ """``Content-Length`` is remote-controlled input and must not crash a fetch."""++ @pytest.mark.parametrize(+ "value, expected",+ [+ ("0", 0),+ ("1024", 1024),+ (" 2048 ", 2048),+ ],+ )+ def test_accepts_valid_sizes(self, value: str, expected: int):+ assert parse_content_length(value) == expected++ @pytest.mark.parametrize(+ "value",+ [None, "", " ", "abc", "12.5", "1,024", "1e3", "0x10", "100 200", "-1"],+ )+ def test_untrustworthy_values_mean_unknown_size(self, value: t.Optional[str]):+ assert parse_content_length(value) is None+++class TestMalformedContentLength:+ """A malformed header degrades to unknown size under the streaming cap."""++ @pytest.mark.parametrize(+ "header", ["abc", "12.5", "1,024", "1e3", "0x10", "100 200", ""]+ )+ @patch("composio.core.models._files.assert_safe_fetch_target")+ @patch("composio.core.models._files.requests.get")+ def test_malformed_header_does_not_raise(+ self, mock_get: MagicMock, _mock_assert: MagicMock, header: str+ ):+ """A malformed header must not surface a raw ValueError to the caller."""+ mock_get.return_value = _stream_response(+ {"content-type": "image/jpeg", "Content-Length": header}+ )++ filename, content, mimetype = _fetch_file_from_url(+ "https://example.com/image.jpg"+ )++ assert filename == "image.jpg"+ assert content == b"payload"+ assert mimetype == "image/jpeg"++ @patch("composio.core.models._files.assert_safe_fetch_target")+ @patch("composio.core.models._files.requests.get")+ def test_negative_header_still_enforced_while_streaming(+ self, mock_get: MagicMock, _mock_assert: MagicMock+ ):+ """A negative header means unknown size, not a trusted "small" value."""+ mock_get.return_value = _stream_response(+ {"Content-Length": "-1"},+ [b"x" * 1024 * 1024 for _ in range(20)],+ )++ with pytest.raises(ResponseTooLargeError):+ _fetch_file_from_url(+ "https://example.com/large.zip", max_size=10 * 1024 * 1024+ )diff --git a/python/tests/test_tool_router_session_files.py b/python/tests/test_tool_router_session_files.pyindex 562d0920e..7d795a0be 100644--- a/python/tests/test_tool_router_session_files.py+++ b/python/tests/test_tool_router_session_files.py@@ -376,6 +376,24 @@ class TestResponseDerivedUrlsAreGuarded:assert mock_get.call_args.kwargs["allow_redirects"] is False+ def test_buffer_tolerates_malformed_content_length(self):+ """A malformed `Content-Length` means unknown size, not a crash.++ The header is remote-controlled; `_fetch_url_bytes` must fall through+ to the streamed byte count instead of raising `ValueError` out of+ `int()` (the crash class issue #4153 fixed for `_files.py`).+ """+ rf = self._remote_file("https://s3.example.com/download")+ malformed = mock_stream_response()+ malformed.headers = {+ "content-type": "text/plain",+ "Content-Length": "1,024",+ }++ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch("requests.get", return_value=malformed):+ assert rf.buffer() == b"file content"+def test_buffer_caps_response_size(self):"""The body is streamed against a cap rather than read whole."""rf = self._remote_file("https://s3.example.com/download")diff --git a/python/tests/test_upload_dir_allowlist.py b/python/tests/test_upload_dir_allowlist.pyindex 0c6127075..ed9826a6a 100644--- a/python/tests/test_upload_dir_allowlist.py+++ b/python/tests/test_upload_dir_allowlist.py@@ -239,7 +239,7 @@ class TestFileUploadableAllowlistWiring:mock_client.post.return_value = Mock(new_presigned_url="https://example/upload", key="k")- monkeypatch.setattr(files_mod, "upload", lambda url, file: True)+ monkeypatch.setattr(files_mod, "upload", lambda url, file, mimetype=None: True)result = FileUploadable.from_path(client=mock_client,