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(files): validate URLs from API responses before fetching them (#4146)
Alberto Schiabel6ba9179b488c
diff --git a/.changeset/guard-response-derived-fetches.md b/.changeset/guard-response-derived-fetches.mdnew file mode 100644index 000000000..d5514848d--- /dev/null+++ b/.changeset/guard-response-derived-fetches.md@@ -0,0 +1,5 @@+---+'@composio/core': patch+---++Validate the URLs that come from API responses before fetching them. Tool-execution downloads (`s3Url`), S3 presigned uploads (`new_presigned_url`), Tool Router session file downloads (`RemoteFile.buffer()` / `blob()` / `text()` / `save()`) and session file uploads (`upload_url`) now go through the same SSRF guard that already covered user-supplied URLs, so a response naming a private, loopback, or link-local address is refused instead of fetched. Redirect hops are re-validated. Edge runtimes keep their current behavior: session file transfers are not blocked there, since a Worker cannot resolve DNS to check and its `fetch` does not originate inside the caller's network.diff --git a/python/composio/core/models/_files.py b/python/composio/core/models/_files.pyindex 2c20d0fd9..dd3c5e84e 100644--- a/python/composio/core/models/_files.py+++ b/python/composio/core/models/_files.py@@ -27,7 +27,7 @@ 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+from composio.utils.url_safety import assert_safe_fetch_target, safe_requestfrom composio.utils.sensitive_file_upload_paths import (assert_safe_local_file_upload_path,)@@ -153,8 +153,9 @@ def upload(url: str, file: Path) -> bool:"""with file.open("rb") as data:try:- response = requests.put(- url=url,+ response = safe_request(+ "PUT",+ url,data=data,timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),)@@ -400,8 +401,9 @@ def _upload_bytes_to_s3(# Upload the content directly to S3try:- upload_response = requests.put(- url=s3meta.new_presigned_url,+ upload_response = safe_request(+ "PUT",+ s3meta.new_presigned_url,data=content,headers={"Content-Type": mimetype},timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),@@ -607,11 +609,13 @@ class FileDownloadable(BaseModel):outfile = secure_basename_join(outdir, self.name, root=root)except UnsafePathComponentError as e:raise ErrorDownloadingFile(str(e)) from e+ assert_safe_fetch_target(self.s3url)outdir.mkdir(exist_ok=True, parents=True)try:response = requests.get(url=self.s3url,stream=True,+ allow_redirects=False,timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),)except requests.exceptions.RequestException as e:diff --git a/python/composio/core/models/tool_router_session_files.py b/python/composio/core/models/tool_router_session_files.pyindex 09b626a54..4f4d117ff 100644--- a/python/composio/core/models/tool_router_session_files.py+++ b/python/composio/core/models/tool_router_session_files.py@@ -29,7 +29,7 @@ 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+from composio.utils.url_safety import assert_safe_fetch_target, safe_requestfrom composio.utils.uuid import generate_short_idDEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID = "files"@@ -50,8 +50,42 @@ def _is_url(value: str) -> bool:return False-def _fetch_from_url(url: str) -> t.Tuple[bytes, str]:- """Fetch file content from URL. Returns (content, mimetype)."""+class _UrlFetchError(Exception):+ """Internal failure raised by :func:`_fetch_url_bytes`.++ Carries the facts rather than a message, so the two callers can keep their+ own public error type and wording while sharing one network body. Neither+ the type nor the instance escapes this module.+ """++ def __init__(+ self,+ *,+ cause: t.Optional[BaseException] = None,+ status_code: t.Optional[int] = None,+ status_text: t.Optional[str] = None,+ redirected: bool = False,+ size_detail: t.Optional[str] = None,+ ) -> None:+ super().__init__(size_detail or "Failed to fetch URL")+ self.cause = cause+ self.status_code = status_code+ self.status_text = status_text+ self.redirected = redirected+ self.size_detail = size_detail+++def _fetch_url_bytes(url: str) -> t.Tuple[bytes, str]:+ """Fetch a URL into memory under the SDK's fetch protections.++ The protections are the point of sharing this: the target is validated+ before connecting, redirects are refused rather than followed, and the body+ is streamed with the size accounted against ``_MAX_RESPONSE_SIZE`` so a+ dishonest ``Content-Length`` cannot exhaust memory. Every caller needs all+ four, whether the URL came from the user or from an API response.++ Returns (content, mimetype). Raises :class:`_UrlFetchError`.+ """assert_safe_fetch_target(url)try:response = requests.get(@@ -61,26 +95,26 @@ def _fetch_from_url(url: str) -> t.Tuple[bytes, str]:timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),)except requests.exceptions.RequestException as e:- raise ValidationError(f"Failed to fetch file from URL: {e}") from e+ raise _UrlFetchError(cause=e) from eif response.status_code in (301, 302, 303, 307, 308):response.close()- raise ValidationError(- "URL returned redirect. Please provide a direct URL to the file."- )+ raise _UrlFetchError(redirected=True)if not response.ok:response.close()- raise ValidationError(- f"Failed to fetch file from URL: {response.status_code} {response.reason}"+ raise _UrlFetchError(+ 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:response.close()- raise ValidationError(- f"File size ({int(content_length)} bytes) exceeds maximum allowed "- f"size ({_MAX_RESPONSE_SIZE} bytes)"+ raise _UrlFetchError(+ size_detail=(+ f"File size ({int(content_length)} bytes) exceeds maximum allowed "+ f"size ({_MAX_RESPONSE_SIZE} bytes)"+ ))chunks: t.List[bytes] = []@@ -90,7 +124,9 @@ def _fetch_from_url(url: str) -> t.Tuple[bytes, str]:total_bytes += len(chunk)if total_bytes > _MAX_RESPONSE_SIZE:response.close()- raise ValidationError("Response size exceeds maximum allowed size")+ raise _UrlFetchError(+ size_detail="Response size exceeds maximum allowed size"+ )chunks.append(chunk)response.close()@@ -99,6 +135,24 @@ def _fetch_from_url(url: str) -> t.Tuple[bytes, str]:return b"".join(chunks), mimetype+def _fetch_from_url(url: str) -> t.Tuple[bytes, str]:+ """Fetch file content from a user-supplied URL. Returns (content, mimetype)."""+ try:+ return _fetch_url_bytes(url)+ except _UrlFetchError as e:+ if e.cause is not None:+ raise ValidationError(f"Failed to fetch file from URL: {e.cause}") from e+ if e.redirected:+ raise ValidationError(+ "URL returned redirect. Please provide a direct URL to the file."+ ) from e+ if e.status_code is not None:+ raise ValidationError(+ f"Failed to fetch file from URL: {e.status_code} {e.status_text}"+ ) from e+ raise ValidationError(str(e)) from e++class RemoteFile:"""Represents a file stored in a tool router session's file mount.@@ -134,30 +188,37 @@ class RemoteFile:return PureWindowsPath(self.mount_relative_path).namedef buffer(self) -> bytes:- """Fetch the file content as bytes."""+ """Fetch the file content as bytes.++ ``self.download_url`` is set by :meth:`from_api_response`, so it is+ untrusted input like every other response field. It goes through+ :func:`_fetch_url_bytes` — the same body that serves user-supplied+ URLs — rather than a bare ``requests.get``: which side of the trust+ boundary the URL arrived from does not change what the fetch needs to+ defend against.+ """try:- response = requests.get(- self.download_url,- timeout=(_CONNECT_TIMEOUT, _READ_TIMEOUT),- )- except requests.exceptions.RequestException as e:- raise RemoteFileDownloadError(- f"Failed to download file: {type(e).__name__}",- download_url=self.download_url,- mount_relative_path=self.mount_relative_path,- filename=self.filename,- ) from e-- if not response.ok:+ content, _ = _fetch_url_bytes(self.download_url)+ except _UrlFetchError as e:+ if e.redirected:+ message = (+ "Failed to download file: the download URL returned a redirect"+ )+ elif e.status_code is not None:+ message = f"Failed to download file: {e.status_code} {e.status_text}"+ elif e.cause is not None:+ message = f"Failed to download file: {type(e.cause).__name__}"+ else:+ message = f"Failed to download file: {e}"raise RemoteFileDownloadError(- f"Failed to download file: {response.status_code} {response.reason}",- status_code=response.status_code,- status_text=response.reason,+ message,+ status_code=e.status_code,+ status_text=e.status_text,download_url=self.download_url,mount_relative_path=self.mount_relative_path,filename=self.filename,- )- return response.content+ ) from (e.cause or e)+ return contentdef text(self) -> str:"""Fetch the file content as UTF-8 text."""@@ -319,8 +380,12 @@ class ToolRouterSessionFilesMount:mimetype=mime,)+ # `upload_url` comes from the API response, so it is validated before+ # the file's bytes are sent to it, and re-validated on every redirect+ # hop. See `composio.utils.url_safety`.try:- upload_resp = requests.put(+ upload_resp = safe_request(+ "PUT",create_resp.upload_url,data=content,headers={"Content-Type": mime},diff --git a/python/composio/utils/url_safety.py b/python/composio/utils/url_safety.pyindex cbceb96d8..67d00a2e8 100644--- a/python/composio/utils/url_safety.py+++ b/python/composio/utils/url_safety.py@@ -1,15 +1,36 @@-"""SSRF protections for user-supplied URL file inputs."""+"""SSRF protections for URLs the SDK fetches.++Applies to URLs the caller supplies *and* to URLs an API response supplies:+under the trust boundary documented in ``python/AGENTS.md`` the backend may be+compromised or the connection MITM'd, so a presigned URL in a response is no+more trusted than one typed by a user. Without a guard, either can point the+SDK at loopback, RFC1918 space, or a link-local cloud-metadata endpoint+(``169.254.169.254``) and turn it into a request proxy for internal+infrastructure.++Known residual — DNS rebinding: the host is resolved here with+``getaddrinfo``, and the HTTP client resolves it again independently when it+connects. A short-TTL record that alternates a public and a private answer can+pass this check and still connect to the private address. Closing that window+requires pinning the validated address and connecting to it directly (a custom+``requests`` transport adapter), which is out of scope for this module; the+TypeScript guard carries the same limitation.+"""from __future__ import annotationsimport ipaddressimport socket-from urllib.parse import urlparse+import typing as t+from urllib.parse import urljoin, urlparseimport requestsfrom composio.exceptions import BlockedInternalUrlError+_REDIRECT_STATUS_CODES = frozenset({301, 302, 303, 307, 308})+_MAX_REDIRECTS = 5+def is_blocked_ip(value: str) -> bool:"""Return whether an address is non-publicly-routable."""@@ -68,3 +89,53 @@ def assert_safe_fetch_target(url: str) -> None:raise BlockedInternalUrlError(f'Refusing to fetch "{parsed.hostname}" because it resolves to a non-public address')+++def safe_request(+ method: str,+ url: str,+ *,+ max_redirects: int = _MAX_REDIRECTS,+ **kwargs: t.Any,+) -> requests.Response:+ """Send a request, validating the target before *every* hop.++ Redirects are followed manually so each new location is validated too.+ Validating only the first URL is not enough: a target that passes the check+ and then answers ``302 Location: http://169.254.169.254/`` would have the+ redirect followed by ``requests`` with no further validation. Mirrors+ ``ssrfSafeFetch`` in the TypeScript SDK.++ Use this where redirects are legitimate (S3 can answer a PUT with a 307+ region redirect). Call sites that require a direct URL should instead call+ :func:`assert_safe_fetch_target` and pass ``allow_redirects=False``.++ :param max_redirects: Hops to follow before giving up.+ :raises BlockedInternalUrlError: If any hop fails validation, or the+ redirect chain is longer than ``max_redirects``.+ """+ body = kwargs.get("data")+ current_url = url++ for _ in range(max_redirects + 1):+ assert_safe_fetch_target(current_url)+ response = requests.request(+ method, current_url, allow_redirects=False, **kwargs+ )++ location = response.headers.get("Location")+ if response.status_code not in _REDIRECT_STATUS_CODES or location is None:+ return response++ response.close()+ current_url = urljoin(current_url, location)++ # `requests` rewinds the body itself when it follows a redirect; doing+ # it manually means doing that too, or a retried upload sends nothing.+ seek = getattr(body, "seek", None)+ if callable(seek):+ seek(0)++ raise BlockedInternalUrlError(+ f"Refusing to fetch: too many redirects (max {max_redirects})"+ )diff --git a/python/tests/test_files.py b/python/tests/test_files.pyindex 550910cc7..c4a7bd60c 100644--- a/python/tests/test_files.py+++ b/python/tests/test_files.py@@ -16,6 +16,7 @@ from composio.core.models._files import (FileDownloadable,FileHelper,FileUploadable,+ upload,_is_url,_get_extension_from_mimetype,_generate_timestamped_filename,@@ -27,6 +28,7 @@ from composio.core.models._files import ()from composio.core.models.base import allow_trackingfrom composio.exceptions import (+ BlockedInternalUrlError,ErrorDownloadingFile,ErrorUploadingFile,ResponseTooLargeError,@@ -1704,8 +1706,8 @@ class TestFetchFileFromUrl:class TestUploadBytesToS3:"""Test cases for _upload_bytes_to_s3 function."""- @patch("composio.core.models._files.requests.put")- def test_upload_bytes_to_s3_success(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_upload_bytes_to_s3_success(self, mock_safe_request):"""Test successful upload to S3."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -1715,7 +1717,7 @@ class TestUploadBytesToS3:mock_put_response = MagicMock()mock_put_response.status_code = 200- mock_put.return_value = mock_put_response+ mock_safe_request.return_value = mock_put_responseresult = _upload_bytes_to_s3(client=mock_client,@@ -1728,15 +1730,16 @@ class TestUploadBytesToS3:assert result == "s3-key-123"mock_client.post.assert_called_once()- mock_put.assert_called_once_with(- url="https://s3.example.com/upload",+ mock_safe_request.assert_called_once_with(+ "PUT",+ "https://s3.example.com/upload",data=b"file content",headers={"Content-Type": "image/jpeg"},timeout=(5, 60),)- @patch("composio.core.models._files.requests.put")- def test_upload_bytes_to_s3_failure(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_upload_bytes_to_s3_failure(self, mock_safe_request):"""Test error handling when S3 upload fails."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -1746,7 +1749,7 @@ class TestUploadBytesToS3:mock_put_response = MagicMock()mock_put_response.status_code = 500- mock_put.return_value = mock_put_response+ mock_safe_request.return_value = mock_put_responsewith pytest.raises(ErrorUploadingFile) as exc_info:_upload_bytes_to_s3(@@ -1760,8 +1763,8 @@ class TestUploadBytesToS3:assert "Failed to upload to S3" in str(exc_info.value)- @patch("composio.core.models._files.requests.put")- def test_upload_bytes_to_s3_timeout(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_upload_bytes_to_s3_timeout(self, mock_safe_request):"""Test request timeouts are reported as upload errors."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -1770,7 +1773,7 @@ class TestUploadBytesToS3:mock_client.post.return_value = mock_s3_response# The exception text itself carries the presigned URL (incl. token), as# real urllib3 errors do — the SDK must not surface it in the message.- mock_put.side_effect = requests.exceptions.Timeout(+ mock_safe_request.side_effect = requests.exceptions.Timeout("HTTPSConnectionPool(host='s3.example.com', port=443): ""Max retries exceeded with url: /upload?token=abc")@@ -2424,8 +2427,8 @@ class TestRedirectHandling:class TestS3UploadErrorHandling:"""Test S3 upload error handling."""- @patch("composio.core.models._files.requests.put")- def test_403_is_treated_as_error(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_403_is_treated_as_error(self, mock_safe_request):"""HTTP 403 should be treated as upload failure."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -2435,7 +2438,7 @@ class TestS3UploadErrorHandling:mock_put_response = MagicMock()mock_put_response.status_code = 403- mock_put.return_value = mock_put_response+ mock_safe_request.return_value = mock_put_responsewith pytest.raises(ErrorUploadingFile, match="403"):_upload_bytes_to_s3(@@ -2447,8 +2450,8 @@ class TestS3UploadErrorHandling:toolkit="test",)- @patch("composio.core.models._files.requests.put")- def test_200_is_success(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_200_is_success(self, mock_safe_request):"""HTTP 200 should be treated as success."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -2458,7 +2461,7 @@ class TestS3UploadErrorHandling:mock_put_response = MagicMock()mock_put_response.status_code = 200- mock_put.return_value = mock_put_response+ mock_safe_request.return_value = mock_put_responseresult = _upload_bytes_to_s3(client=mock_client,@@ -2470,8 +2473,8 @@ class TestS3UploadErrorHandling:)assert result == "s3-key"- @patch("composio.core.models._files.requests.put")- def test_500_is_treated_as_error(self, mock_put):+ @patch("composio.core.models._files.safe_request")+ def test_500_is_treated_as_error(self, mock_safe_request):"""HTTP 500 should be treated as upload failure."""mock_client = MagicMock()mock_s3_response = MagicMock()@@ -2481,7 +2484,7 @@ class TestS3UploadErrorHandling:mock_put_response = MagicMock()mock_put_response.status_code = 500- mock_put.return_value = mock_put_response+ mock_safe_request.return_value = mock_put_responsewith pytest.raises(ErrorUploadingFile, match="500"):_upload_bytes_to_s3(@@ -2528,6 +2531,11 @@ class TestUrlSanitization:class TestFileDownloadablePathTraversal:"""SEC-316: server-controlled `name` must not escape the output dir."""+ @pytest.fixture(autouse=True)+ def _allow_fetch_target(self):+ with patch("composio.core.models._files.assert_safe_fetch_target"):+ yield+def _mock_response(self, content: bytes = b"data") -> MagicMock:response = MagicMock()response.status_code = 200@@ -2624,6 +2632,7 @@ class TestFileDownloadablePathTraversal:mock_get.assert_called_once_with(url="https://example.com/file",stream=True,+ allow_redirects=False,timeout=(5, 60),)@@ -3017,12 +3026,6 @@ class TestFromPathSensitiveGuard:mock_client.post.assert_not_called()def test_from_path_opt_out_disables_guard(self, mock_client):- """`sensitive_file_upload_protection=False` restores the legacy- (unguarded) behavior; the denylist no longer raises for that path."""- # A non-existent basename under `.ssh`: the `.ssh` segment still trips the- # denylist when protection is on, but the file never exists, so with- # protection off we deterministically hit the missing-file path (no real- # key read, no network) rather than the block error.p = Path.home() / ".ssh" / "composio-does-not-exist-guard-test"with pytest.raises(Exception) as exc_info:FileUploadable.from_path(@@ -3033,6 +3036,135 @@ class TestFromPathSensitiveGuard:sensitive_file_upload_protection=False,)assert not isinstance(exc_info.value, SensitiveFilePathBlockedError)- # Guard skipped, so the failure is downstream (missing file), before any- # presigned-URL request.mock_client.post.assert_not_called()+++class TestResponseDerivedUrlsAreGuarded:+ def _download_response(self) -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.iter_content = lambda chunk_size: [b"%PDF-1.4"]+ response.close = MagicMock()+ return response++ def _s3_client(self, presigned_url: str) -> MagicMock:+ client = MagicMock()+ s3meta = MagicMock()+ s3meta.key = "s3-key"+ s3meta.new_presigned_url = presigned_url+ client.post.return_value = s3meta+ return client++ def test_download_validates_s3url(self, tmp_path):+ f = FileDownloadable(+ name="report.pdf",+ mimetype="application/pdf",+ s3url="https://s3.example.com/file",+ )+ with patch(+ "composio.core.models._files.assert_safe_fetch_target"+ ) as mock_assert:+ with patch(+ "composio.core.models._files.requests.get",+ return_value=self._download_response(),+ ):+ f.download(tmp_path / "out", root=tmp_path / "out")++ mock_assert.assert_called_once_with("https://s3.example.com/file")++ def test_download_blocked_url_never_reaches_the_network(self, tmp_path):+ outdir = tmp_path / "out"+ f = FileDownloadable(+ name="report.pdf",+ mimetype="application/pdf",+ s3url="http://169.254.169.254/latest/meta-data",+ )+ with patch(+ "composio.core.models._files.assert_safe_fetch_target",+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("composio.core.models._files.requests.get") as mock_get:+ with pytest.raises(BlockedInternalUrlError):+ f.download(outdir, root=outdir)++ mock_get.assert_not_called()+ assert not outdir.exists()++ def test_download_refuses_to_follow_redirects(self, tmp_path):+ f = FileDownloadable(+ name="report.pdf",+ mimetype="application/pdf",+ s3url="https://s3.example.com/file",+ )+ with patch("composio.core.models._files.assert_safe_fetch_target"):+ with patch(+ "composio.core.models._files.requests.get",+ return_value=self._download_response(),+ ) as mock_get:+ f.download(tmp_path / "out", root=tmp_path / "out")++ assert mock_get.call_args.kwargs["allow_redirects"] is False++ def test_upload_bytes_to_s3_goes_through_safe_request(self):+ client = self._s3_client("https://s3.example.com/upload")+ with patch("composio.core.models._files.safe_request") as mock_safe_request:+ mock_safe_request.return_value.status_code = 200+ _upload_bytes_to_s3(+ client=client,+ filename="test.jpg",+ content=b"data",+ mimetype="image/jpeg",+ tool="TEST",+ toolkit="test",+ )++ assert mock_safe_request.call_args.args == (+ "PUT",+ "https://s3.example.com/upload",+ )++ def test_upload_bytes_to_s3_blocked_url_sends_nothing(self):+ client = self._s3_client("http://169.254.169.254/upload")+ with patch(+ "composio.utils.url_safety.assert_safe_fetch_target",+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("composio.utils.url_safety.requests.request") as mock_request:+ with pytest.raises(BlockedInternalUrlError):+ _upload_bytes_to_s3(+ client=client,+ filename="test.jpg",+ content=b"data",+ mimetype="image/jpeg",+ tool="TEST",+ toolkit="test",+ )++ mock_request.assert_not_called()++ def test_file_upload_goes_through_safe_request(self, tmp_path):+ source = tmp_path / "report.pdf"+ source.write_bytes(b"%PDF-1.4")++ with patch("composio.core.models._files.safe_request") as mock_safe_request:+ mock_safe_request.return_value.status_code = 200+ assert upload(url="https://s3.example.com/upload", file=source) is True++ assert mock_safe_request.call_args.args == (+ "PUT",+ "https://s3.example.com/upload",+ )++ def test_file_upload_blocked_url_sends_nothing(self, tmp_path):+ source = tmp_path / "report.pdf"+ source.write_bytes(b"%PDF-1.4")++ with patch(+ "composio.utils.url_safety.assert_safe_fetch_target",+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("composio.utils.url_safety.requests.request") as mock_request:+ with pytest.raises(BlockedInternalUrlError):+ upload(url="http://127.0.0.1:9000/upload", file=source)++ mock_request.assert_not_called()diff --git a/python/tests/test_tool_router_session_files.py b/python/tests/test_tool_router_session_files.pyindex 48ca520f0..562d0920e 100644--- a/python/tests/test_tool_router_session_files.py+++ b/python/tests/test_tool_router_session_files.py@@ -10,7 +10,32 @@ from composio.core.models.tool_router_session_files import (RemoteFile,ToolRouterSessionFilesMount,)-from composio.exceptions import RemoteFileDownloadError, ValidationError+from composio.exceptions import (+ BlockedInternalUrlError,+ RemoteFileDownloadError,+ ValidationError,+)++MODULE = "composio.core.models.tool_router_session_files"+SAFE_REQUEST = f"{MODULE}.safe_request"+ASSERT_SAFE_FETCH_TARGET = f"{MODULE}.assert_safe_fetch_target"+++def mock_stream_response(+ content: bytes = b"file content",+ *,+ status_code: int = 200,+ content_type: str = "text/plain",+) -> MagicMock:+ """A streaming `requests` response double, as `_fetch_url_bytes` reads it."""+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.reason = "OK" if response.ok else "Not Found"+ response.headers = {"content-type": content_type}+ response.iter_content = lambda chunk_size: [content]+ response.close = MagicMock()+ return response@pytest.fixture@@ -90,9 +115,9 @@ class TestToolRouterSessionFilesMount:def test_upload_from_bytes_with_remote_path(self, files_mount, mock_client):"""Test upload from bytes with remote_path."""- with patch("requests.put") as mock_put:- mock_put.return_value.status_code = 200- mock_put.return_value.ok = True+ with patch(SAFE_REQUEST) as mock_safe_request:+ mock_safe_request.return_value.status_code = 200+ mock_safe_request.return_value.ok = Trueresult = files_mount.upload(b"hello world",@@ -102,7 +127,11 @@ class TestToolRouterSessionFilesMount:assert isinstance(result, RemoteFile)assert result.mount_relative_path == "output/test.txt"- mock_put.assert_called_once_with(+ # Routed through `safe_request`, not a bare `requests.put`:+ # `upload_url` is a response field, so its target is validated+ # before the bytes are sent, and on every redirect hop after.+ mock_safe_request.assert_called_once_with(+ "PUT","https://s3.example.com/upload",data=b"hello world",headers={"Content-Type": "text/plain"},@@ -113,7 +142,7 @@ class TestToolRouterSessionFilesMount:def test_upload_raises_validation_error_on_timeout(self, files_mount):"""Test upload converts request timeouts to ValidationError."""- with patch("requests.put", side_effect=requests.exceptions.Timeout("timeout")):+ with patch(SAFE_REQUEST, side_effect=requests.exceptions.Timeout("timeout")):with pytest.raises(ValidationError, match="Failed to upload file"):files_mount.upload(b"hello world",@@ -126,9 +155,9 @@ class TestToolRouterSessionFilesMount:test_file = tmp_path / "report.pdf"test_file.write_bytes(b"pdf content")- with patch("requests.put") as mock_put:- mock_put.return_value.status_code = 200- mock_put.return_value.ok = True+ with patch(SAFE_REQUEST) as mock_safe_request:+ mock_safe_request.return_value.status_code = 200+ mock_safe_request.return_value.ok = Trueresult = files_mount.upload(str(test_file))@@ -184,15 +213,15 @@ class TestRemoteFile:sandbox_mount_prefix="/mnt/files",download_url="https://example.com/file",)- with patch("requests.get") as mock_get:- mock_get.return_value.status_code = 200- mock_get.return_value.ok = True- mock_get.return_value.content = b"file content"+ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch("requests.get", return_value=mock_stream_response()) as mock_get:+ result = rf.buffer()- result = rf.buffer()assert result == b"file content"mock_get.assert_called_once_with("https://example.com/file",+ stream=True,+ allow_redirects=False,timeout=(5, 60),)@@ -204,16 +233,15 @@ class TestRemoteFile:sandbox_mount_prefix="/mnt/files",download_url="https://example.com/file",)- with patch("requests.get") as mock_get:- mock_get.return_value.status_code = 404- mock_get.return_value.ok = False- mock_get.return_value.reason = "Not Found"-- with pytest.raises(RemoteFileDownloadError) as exc_info:- rf.buffer()+ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch(+ "requests.get", return_value=mock_stream_response(status_code=404)+ ):+ with pytest.raises(RemoteFileDownloadError) as exc_info:+ rf.buffer()- assert exc_info.value.status_code == 404- assert exc_info.value.filename == "test.txt"+ assert exc_info.value.status_code == 404+ assert exc_info.value.filename == "test.txt"def test_buffer_timeout_raises_remote_file_download_error(self):"""Test buffer() converts request timeouts to RemoteFileDownloadError."""@@ -223,12 +251,15 @@ class TestRemoteFile:sandbox_mount_prefix="/mnt/files",download_url="https://example.com/file",)- with patch("requests.get", side_effect=requests.exceptions.Timeout("timeout")):- with pytest.raises(RemoteFileDownloadError) as exc_info:- rf.buffer()+ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch(+ "requests.get", side_effect=requests.exceptions.Timeout("timeout")+ ):+ with pytest.raises(RemoteFileDownloadError) as exc_info:+ rf.buffer()- assert exc_info.value.filename == "test.txt"- assert exc_info.value.download_url == "https://example.com/file"+ assert exc_info.value.filename == "test.txt"+ assert exc_info.value.download_url == "https://example.com/file"def test_text(self):"""Test text() decodes UTF-8."""@@ -290,3 +321,103 @@ class TestRemoteFile:# The check raises before mkdir/write, so nothing was written under tmp_path.assert not (tmp_path / ".composio").exists()+++class TestResponseDerivedUrlsAreGuarded:+ """`download_url` and `upload_url` are response fields, so they are guarded.++ `RemoteFile.buffer()` previously called `requests.get` directly: no target+ validation, no redirect control, and `response.content` read the whole body+ into memory with no cap — while the sibling `_fetch_from_url`, four lines+ up, had all three. The only difference between them was which side of the+ trust boundary the URL came from.+ """++ def _remote_file(self, download_url: str) -> RemoteFile:+ return RemoteFile(+ expires_at="2026-01-01",+ mount_relative_path="test.txt",+ sandbox_mount_prefix="/mnt/files",+ download_url=download_url,+ )++ def test_buffer_validates_download_url(self):+ rf = self._remote_file("https://s3.example.com/download")++ with patch(ASSERT_SAFE_FETCH_TARGET) as mock_assert:+ with patch("requests.get", return_value=mock_stream_response()):+ rf.buffer()++ mock_assert.assert_called_once_with("https://s3.example.com/download")++ def test_buffer_blocked_url_never_reaches_the_network(self):+ rf = self._remote_file("http://169.254.169.254/latest/meta-data")++ with patch(+ ASSERT_SAFE_FETCH_TARGET,+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("requests.get") as mock_get:+ with pytest.raises(BlockedInternalUrlError):+ rf.buffer()++ mock_get.assert_not_called()++ def test_buffer_rejects_redirects(self):+ """A validated URL must not be able to bounce the fetch elsewhere."""+ rf = self._remote_file("https://s3.example.com/download")++ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch(+ "requests.get", return_value=mock_stream_response(status_code=302)+ ) as mock_get:+ with pytest.raises(RemoteFileDownloadError, match="redirect"):+ rf.buffer()++ assert mock_get.call_args.kwargs["allow_redirects"] is False++ 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")+ oversized = mock_stream_response()+ oversized.headers = {+ "content-type": "text/plain",+ "Content-Length": str(200 * 1024 * 1024),+ }++ with patch(ASSERT_SAFE_FETCH_TARGET):+ with patch("requests.get", return_value=oversized):+ with pytest.raises(RemoteFileDownloadError, match="exceeds maximum"):+ rf.buffer()++ def test_text_and_save_inherit_the_guard(self, tmp_path):+ """`text()` and `save()` read through `buffer()`, so they are covered."""+ rf = self._remote_file("http://127.0.0.1:9000/download")++ with patch(+ ASSERT_SAFE_FETCH_TARGET,+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("requests.get") as mock_get:+ with pytest.raises(BlockedInternalUrlError):+ rf.text()+ with pytest.raises(BlockedInternalUrlError):+ rf.save(str(tmp_path / "out.txt"))++ mock_get.assert_not_called()+ assert not (tmp_path / "out.txt").exists()++ def test_upload_blocked_url_sends_nothing(self, files_mount):+ with patch(+ "composio.utils.url_safety.assert_safe_fetch_target",+ side_effect=BlockedInternalUrlError("blocked"),+ ):+ with patch("composio.utils.url_safety.requests.request") as mock_request:+ with pytest.raises(BlockedInternalUrlError):+ files_mount.upload(+ b"hello world",+ remote_path="data.txt",+ mimetype="text/plain",+ )++ mock_request.assert_not_called()diff --git a/python/tests/test_url_safety.py b/python/tests/test_url_safety.pyindex 90fc88494..723ea4421 100644--- a/python/tests/test_url_safety.py+++ b/python/tests/test_url_safety.py@@ -2,13 +2,18 @@from __future__ import annotations+import ioimport socket-from unittest.mock import patch+from unittest.mock import MagicMock, call, patchimport pytestfrom composio.exceptions import BlockedInternalUrlError-from composio.utils.url_safety import assert_safe_fetch_target, is_blocked_ip+from composio.utils.url_safety import (+ assert_safe_fetch_target,+ is_blocked_ip,+ safe_request,+)@pytest.mark.parametrize(@@ -94,3 +99,100 @@ def test_allows_public_dns_answers(mock_getaddrinfo) -> None:]assert_safe_fetch_target("https://example.com/file.pdf")+++def _response(status_code: int, location: str | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.headers = {"Location": location} if location else {}+ response.close = MagicMock()+ return response+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_validates_before_sending(mock_assert, mock_request) -> None:+ mock_assert.side_effect = BlockedInternalUrlError("blocked")++ with pytest.raises(BlockedInternalUrlError):+ safe_request("PUT", "https://s3.example.com/upload", data=b"payload")++ # The point of the guard: a rejected target must never reach the network.+ mock_request.assert_not_called()+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_disables_automatic_redirects(mock_assert, mock_request) -> None:+ mock_request.return_value = _response(200)++ response = safe_request("PUT", "https://s3.example.com/upload", data=b"payload")++ assert response.status_code == 200+ mock_assert.assert_called_once_with("https://s3.example.com/upload")+ # `requests` must not follow redirects on its own, or hops after the first+ # would be fetched without ever being validated.+ assert mock_request.call_args.kwargs["allow_redirects"] is False+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_revalidates_each_redirect_hop(mock_assert, mock_request) -> None:+ """A public URL that redirects into private space must be caught at the hop."""+ mock_assert.side_effect = [None, BlockedInternalUrlError("blocked")]+ mock_request.return_value = _response(+ 307, "http://169.254.169.254/latest/meta-data"+ )++ with pytest.raises(BlockedInternalUrlError):+ safe_request("PUT", "https://s3.example.com/upload", data=b"payload")++ assert mock_assert.call_args_list == [+ call("https://s3.example.com/upload"),+ call("http://169.254.169.254/latest/meta-data"),+ ]+ # Only the first hop was sent; the redirect target never was.+ assert mock_request.call_count == 1+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_follows_validated_redirect(mock_assert, mock_request) -> None:+ """S3 can answer a PUT with a 307 region redirect; that must still work."""+ mock_request.side_effect = [+ _response(307, "https://s3.eu-west-1.example.com/upload"),+ _response(200),+ ]+ body = io.BytesIO(b"payload")++ response = safe_request("PUT", "https://s3.example.com/upload", data=body)++ assert response.status_code == 200+ assert mock_assert.call_args_list == [+ call("https://s3.example.com/upload"),+ call("https://s3.eu-west-1.example.com/upload"),+ ]+ # The body was rewound, so the retried hop sends the payload rather than+ # an already-exhausted stream.+ assert body.read() == b"payload"+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_relative_redirect_is_resolved(mock_assert, mock_request) -> None:+ mock_request.side_effect = [_response(302, "/elsewhere"), _response(200)]++ safe_request("GET", "https://files.example.com/a/b")++ assert mock_assert.call_args_list[1] == call("https://files.example.com/elsewhere")+++@patch("composio.utils.url_safety.requests.request")+@patch("composio.utils.url_safety.assert_safe_fetch_target")+def test_safe_request_rejects_endless_redirects(mock_assert, mock_request) -> None:+ mock_request.return_value = _response(302, "https://s3.example.com/upload")++ with pytest.raises(BlockedInternalUrlError, match="too many redirects"):+ safe_request("GET", "https://s3.example.com/upload", max_redirects=2)++ assert mock_request.call_count == 3diff --git a/ts/packages/core/src/models/RemoteFile.ts b/ts/packages/core/src/models/RemoteFile.tsindex f4770aa57..ec6d9d864 100644--- a/ts/packages/core/src/models/RemoteFile.ts+++ b/ts/packages/core/src/models/RemoteFile.ts@@ -1,4 +1,5 @@import { platform } from '#platform';+import { ssrfSafeFetchWhereSupported } from '#ssrf_guard';import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';function getParentDir(filePath: string): string {@@ -82,7 +83,10 @@ export class RemoteFile {* @throws RemoteFileDownloadError if the fetch fails*/async buffer(): Promise<Uint8Array> {- const response = await fetch(this.downloadUrl);+ // SSRF guard: `downloadUrl` is set from an API response, so it is untrusted+ // input like every other response field, and its bytes are handed straight+ // back to the caller. See ssrfGuard.node.ts.+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);if (!response.ok) {throw new RemoteFileDownloadError(`Failed to download file: ${response.status} ${response.statusText}`,@@ -116,7 +120,8 @@ export class RemoteFile {* @throws RemoteFileDownloadError if the fetch fails*/async blob(): Promise<Blob> {- const response = await fetch(this.downloadUrl);+ // SSRF guard: see `buffer()`.+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);if (!response.ok) {throw new RemoteFileDownloadError(`Failed to download file: ${response.status} ${response.statusText}`,diff --git a/ts/packages/core/src/models/ToolRouterSessionFileMount.ts b/ts/packages/core/src/models/ToolRouterSessionFileMount.tsindex e9834094a..7d8a814c6 100644--- a/ts/packages/core/src/models/ToolRouterSessionFileMount.ts+++ b/ts/packages/core/src/models/ToolRouterSessionFileMount.ts@@ -18,7 +18,7 @@ import {import { RemoteFile } from './RemoteFile';import { ValidationError } from '../errors';import { platform } from '#platform';-import { ssrfSafeFetch } from '#ssrf_guard';+import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from '#ssrf_guard';import { getExtensionFromMimeType } from '../utils/mime';import { readResponseBodyWithLimit } from '../utils/readResponseBody';import { getRandomShortId } from '../utils/uuid';@@ -240,13 +240,19 @@ export class ToolRouterSessionFilesMount {? (createUploadURLResponse as { body: unknown }).body: createUploadURLResponse;- const uploadResponse = await fetch((uploadURLData as { upload_url: string }).upload_url, {- method: 'PUT',- body: await fileToUpload.arrayBuffer(),- headers: {- 'Content-Type': mimetype,- },- });+ // SSRF guard: `upload_url` comes from the API response, so the target is+ // validated before the file's bytes are sent to it — the same treatment the+ // user-supplied URL above already gets. See ssrfGuard.node.ts.+ const uploadResponse = await ssrfSafeFetchWhereSupported(+ (uploadURLData as { upload_url: string }).upload_url,+ {+ method: 'PUT',+ body: await fileToUpload.arrayBuffer(),+ headers: {+ 'Content-Type': mimetype,+ },+ }+ );if (!uploadResponse.ok) {throw new Error(`Failed to upload file: ${uploadResponse.statusText}`);diff --git a/ts/packages/core/src/utils/fileUtils.node.ts b/ts/packages/core/src/utils/fileUtils.node.tsindex 219b028b5..c659d7c49 100644--- a/ts/packages/core/src/utils/fileUtils.node.ts+++ b/ts/packages/core/src/utils/fileUtils.node.ts@@ -246,7 +246,10 @@ const uploadFileToS3 = async (// `InvalidArgumentError: invalid content-length header`, which surfaces as// `TypeError: fetch failed` and breaks every `file_uploadable` connector tool// on Node 22+.- const uploadResponse = await fetch(signedURL, {+ // SSRF guard: `new_presigned_url` comes from the API response, which the SDK+ // treats as untrusted — a response naming an internal address would otherwise+ // have the file's bytes PUT to it. See ssrfGuard.node.ts.+ const uploadResponse = await ssrfSafeFetch(signedURL, {method: 'PUT',body: uploadBuffer,signal,@@ -348,7 +351,10 @@ export const downloadFileFromS3 = async ({fileDownloadDir?: string;signal?: AbortSignal;}): Promise<FileDownloadData> => {- const response = await fetch(s3Url, { signal });+ // SSRF guard: `s3Url` is a field of the tool-execution response, so it is no+ // more trusted than a user-supplied URL — and the bytes it returns are+ // written to disk. See ssrfGuard.node.ts.+ const response = await ssrfSafeFetch(s3Url, { signal });if (!response.ok) {throw new Error(`Failed to download file: ${response.statusText}`);}diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.tsindex 791cc1aec..366e737ed 100644--- a/ts/packages/core/src/utils/ssrfGuard.node.ts+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts@@ -204,3 +204,14 @@ export const ssrfSafeFetch = async ({ url: rawUrl });};++/**+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.+ *+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the+ * caller chose to upload — the alternative is fetching it unvalidated — but not+ * for Tool Router session file transfers, where refusing would remove a working+ * feature from Workers rather than close a hole reachable there. On Node this+ * is the full guard; only the edge build differs.+ */+export const ssrfSafeFetchWhereSupported = ssrfSafeFetch;diff --git a/ts/packages/core/src/utils/ssrfGuard.workerd.ts b/ts/packages/core/src/utils/ssrfGuard.workerd.tsindex ab78fc2ac..81a897baa 100644--- a/ts/packages/core/src/utils/ssrfGuard.workerd.ts+++ b/ts/packages/core/src/utils/ssrfGuard.workerd.ts@@ -17,3 +17,19 @@ export const ssrfSafeFetch = async (rawUrl: string): Promise<Response> => {});};++/**+ * Unguarded `fetch`, for the call sites that must keep working here.+ *+ * Failing closed is the right default for a URL the caller chose to upload, but+ * applying it to Tool Router session file transfers would take a working+ * feature away from Workers instead of closing a hole reachable there. The+ * guard exists to stop a URL from reaching private address space the SDK's host+ * can see; an edge worker has no such vantage point — it cannot resolve DNS to+ * check, and its `fetch` does not originate inside the caller's network. The+ * Node build applies the full guard.+ */+export const ssrfSafeFetchWhereSupported = async (+ rawUrl: string,+ init: RequestInit = {}+): Promise<Response> => fetch(rawUrl, init);diff --git a/ts/packages/core/test/models/RemoteFile.test.ts b/ts/packages/core/test/models/RemoteFile.test.tsindex 6e854617a..9d4596161 100644--- a/ts/packages/core/test/models/RemoteFile.test.ts+++ b/ts/packages/core/test/models/RemoteFile.test.ts@@ -1,6 +1,22 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { RemoteFile } from '../../src/models/RemoteFile';-import { RemoteFileDownloadError, ValidationError } from '../../src/errors';+import {+ ComposioBlockedInternalUrlError,+ RemoteFileDownloadError,+ ValidationError,+} from '../../src/errors';++// `downloadUrl` comes from an API response, so downloads run through the SSRF+// guard, which resolves the host before connecting. Resolve as public by+// default; the guard's own tests cover the blocking behavior.+vi.mock('node:dns/promises', () => ({+ lookup: vi.fn(),+}));++// eslint-disable-next-line no-restricted-imports+import { lookup } from 'node:dns/promises';++const mockLookup = vi.mocked(lookup);describe('RemoteFile', () => {const validCamelCaseData = {@@ -21,6 +37,8 @@ describe('RemoteFile', () => {beforeEach(() => {originalFetch = globalThis.fetch;+ mockLookup.mockReset();+ mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);});afterEach(() => {@@ -79,7 +97,11 @@ describe('RemoteFile', () => {const file = new RemoteFile(validCamelCaseData);const result = await file.buffer();- expect(globalThis.fetch).toHaveBeenCalledWith(validCamelCaseData.downloadUrl);+ // `redirect: 'manual'` is the guard following redirects itself so it can+ // re-validate each hop, rather than letting fetch follow them unchecked.+ expect(globalThis.fetch).toHaveBeenCalledWith(validCamelCaseData.downloadUrl, {+ redirect: 'manual',+ });expect(result).toBeInstanceOf(Uint8Array);expect(result).toEqual(content);});@@ -143,6 +165,45 @@ describe('RemoteFile', () => {});});+ describe('SSRF guard', () => {+ // `downloadUrl` is set from an API response. Under the SDK's trust boundary+ // that is untrusted input, so a response naming an internal address must+ // not be fetched — the bytes go straight back to the caller, typically into+ // an LLM context.+ it.each([+ ['loopback', 'http://127.0.0.1/secret', '127.0.0.1'],+ ['cloud metadata', 'http://169.254.169.254/latest/meta-data/', '169.254.169.254'],+ ])('should block a %s downloadUrl before fetching', async (_label, downloadUrl, address) => {+ mockLookup.mockResolvedValue([{ address, family: 4 }] as never);+ globalThis.fetch = vi.fn();++ const file = new RemoteFile({ ...validCamelCaseData, downloadUrl });++ await expect(file.buffer()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);+ await expect(file.blob()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);+ await expect(file.text()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('should block a downloadUrl that redirects into private space', async () => {+ mockLookup+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)+ .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { location: 'http://169.254.169.254/latest/meta-data/' },+ })+ );++ const file = new RemoteFile(validCamelCaseData);++ await expect(file.buffer()).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);+ // The first hop was fetched; the redirect target never was.+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ });+ });+describe('save', () => {it('should save file to specified path when platform supports file system', async () => {const content = new Uint8Array([1, 2, 3]);diff --git a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.tsindex 1ded7dcf9..8506e511f 100644--- a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts+++ b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts@@ -35,6 +35,10 @@ describe('ToolRouterSessionFilesMount', () => {beforeEach(() => {vi.clearAllMocks();mockLookup.mockReset();+ // Uploads PUT to a response-supplied `upload_url`, which is now validated+ // like any other fetch target; resolve test hosts as public by default so+ // only the tests that care about the guard have to say anything about DNS.+ mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);mockClient = createMockClient();filesMount = new ToolRouterSessionFilesMount(mockClient, sessionId);});@@ -366,6 +370,24 @@ describe('ToolRouterSessionFilesMount', () => {expect(result.downloadUrl).toBe('https://s3.example.com/presigned');});+ it('should block a response-supplied upload_url that resolves internally', async () => {+ // The user-supplied URL branch above was already guarded; `upload_url`+ // comes back from the API and was not. Both are untrusted here, and this+ // one receives the file's bytes.+ mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({+ ...createUploadURLResponse,+ upload_url: 'http://metadata.example/upload',+ });+ mockLookup.mockResolvedValue([{ address: '169.254.169.254', family: 4 }] as never);++ await expect(+ filesMount.upload(new File(['data'], 'report.txt', { type: 'text/plain' }))+ ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);++ expect(fetch).not.toHaveBeenCalled();+ expect(mockClient.toolRouter.session.files.createDownloadURL).not.toHaveBeenCalled();+ });+it('should handle upload response body wrapper', async () => {const { platform } = await import('../../src/platform/node');const { join } = await import('node:path');diff --git a/ts/packages/core/test/utils/fileUtils.test.ts b/ts/packages/core/test/utils/fileUtils.test.tsindex b00ec1b57..f89e0a07a 100644--- a/ts/packages/core/test/utils/fileUtils.test.ts+++ b/ts/packages/core/test/utils/fileUtils.test.ts@@ -49,6 +49,12 @@ vi.mock('node:dns/promises', () => ({lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),}));+// eslint-disable-next-line no-restricted-imports+import { lookup } from 'node:dns/promises';+import { ComposioBlockedInternalUrlError } from '../../src/errors';++const mockLookup = vi.mocked(lookup);+// Mock global fetchconst mockFetch = vi.fn();global.fetch = mockFetch;@@ -515,4 +521,43 @@ describe('fileUtils', () => {).rejects.toThrow('Invalid file type');});});+ describe('SSRF guard on response-supplied URLs', () => {+ // The S3 URLs below are API response fields, not caller input. The SDK+ // treats a response as untrusted, so both directions are validated: a+ // download would otherwise fetch an internal address and write the bytes+ // to disk, and an upload would PUT the user's file to one.+ it('should block a download whose s3Url resolves internally', async () => {+ mockLookup.mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);++ await expect(+ downloadFileFromS3({+ toolSlug: 'github',+ s3Url: 'http://metadata.example/latest/meta-data/',+ mimeType: 'text/plain',+ })+ ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);++ expect(mockFetch).not.toHaveBeenCalled();+ });++ it('should block an upload whose presigned URL resolves internally', async () => {+ vi.mocked(mockClient.files.createPresignedURL).mockResolvedValue({+ key: 'test-key',+ type: 'new',+ new_presigned_url: 'http://127.0.0.1:9000/upload',+ } as never);+ // The file content is read first, then the presigned URL is validated.+ mockLookup.mockResolvedValueOnce([{ address: '127.0.0.1', family: 4 }] as never);++ await expect(+ getFileDataAfterUploadingToS3(new File(['data'], 'report.txt', { type: 'text/plain' }), {+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ client: mockClient,+ })+ ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError);++ expect(mockFetch).not.toHaveBeenCalled();+ });+ });});diff --git a/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts b/ts/packages/core/test/utils/ssrfGuard.workerd.test.tsindex ce0d760db..8b54cb2e8 100644--- a/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts+++ b/ts/packages/core/test/utils/ssrfGuard.workerd.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';import { ComposioBlockedInternalUrlError } from '../../src/errors/SsrfErrors';-import { ssrfSafeFetch } from '../../src/utils/ssrfGuard.workerd';+import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from '../../src/utils/ssrfGuard.workerd';describe('ssrfSafeFetch (workerd)', () => {afterEach(() => vi.unstubAllGlobals());@@ -14,4 +14,20 @@ describe('ssrfSafeFetch (workerd)', () => {);expect(fetchMock).not.toHaveBeenCalled();});++ it('lets session file transfers through, since the guard cannot run here', async () => {+ // Failing closed would remove a working feature from Workers rather than+ // close a hole reachable there: an edge worker has no DNS API to validate+ // with, and its fetch does not originate inside the caller's network.+ const response = new Response('ok');+ const fetchMock = vi.fn().mockResolvedValue(response);+ vi.stubGlobal('fetch', fetchMock);++ await expect(+ ssrfSafeFetchWhereSupported('https://s3.example.com/presigned', { method: 'PUT' })+ ).resolves.toBe(response);+ expect(fetchMock).toHaveBeenCalledWith('https://s3.example.com/presigned', {+ method: 'PUT',+ });+ });});