Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(sdk): harden pusher auth and cross-origin redirect headers (#4406)

Alberto Schiabel85996c4a1d7c
diff --git a/.changeset/strip-credentials-cross-origin-redirect.md b/.changeset/strip-credentials-cross-origin-redirect.md
new file mode 100644
index 000000000..15a827e24
--- /dev/null
+++ b/.changeset/strip-credentials-cross-origin-redirect.md
@@ -0,0 +1,6 @@
+---
+'@composio/core': patch
+'@composio/slim': patch
+---
+
+Drop `Authorization`, `Proxy-Authorization`, and `Cookie` from the request headers when the SSRF guard follows a redirect to a different origin, as the Fetch standard does for automatic redirects. Same-origin redirects keep them.
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index 125334aeb..b2b0f3adf 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -5,6 +5,8 @@ import functools
import hashlib
import hmac
import json
+import logging
+import re
import threading
import time
import traceback
@@ -12,8 +14,8 @@ import typing as t
import uuid
from concurrent.futures import ThreadPoolExecutor
from enum import Enum
-from unittest import mock
+import requests
import typing_extensions as te
from composio_client import APIStatusError, Omit, omit
from composio_client.types import TriggersTypeRetrieveResponse
@@ -33,6 +35,22 @@ from composio.utils.pydantic import none_to_omit
PUSHER_AUTH_URL = "{base_url}/api/v3/internal/sdk/realtime/auth?source=python"
+# `(connect, read)` seconds for the channel-auth POST pysher makes on the
+# websocket thread. pysher itself sends it with no timeout, so an auth endpoint
+# that accepts the connection and never answers would hang every (re)subscribe
+# for the life of the process.
+PUSHER_AUTH_TIMEOUT: t.Tuple[float, float] = (5.0, 15.0)
+
+# Pusher cluster names are short lowercase labels such as ``mt1`` or
+# ``ap-southeast-1``. pysher formats the value straight into the websocket
+# host (``ws-{cluster}.pusher.com``), and it arrives in an API response, which
+# `python/AGENTS.md` treats as untrusted: anything outside this shape could
+# steer the socket to a host of the response author's choosing.
+_PUSHER_CLUSTER_PATTERN = re.compile(r"^[a-z0-9-]+$")
+_PUSHER_CLUSTER_MAX_LENGTH = 64
+
+_PYSHER_LOGGER_NAME = "composio.core.models.triggers.pysher"
+
"""
export type _TriggerData = {
appName: string;
@@ -836,6 +854,109 @@ class TriggerSubscription(Resource):
self._connection._connect() # pylint: disable=protected-access
+def _silent_pysher_logger() -> logging.Logger:
+ """A logger that swallows pysher's connection chatter.
+
+ pysher logs every raw websocket frame at ``INFO``, trigger payloads
+ included. Handing its connection a logger that neither emits nor propagates
+ keeps those frames out of the user's log output; the SDK logs what it needs
+ itself from ``TriggerSubscription``.
+ """
+ logger = logging.getLogger(_PYSHER_LOGGER_NAME)
+ if not any(isinstance(handler, logging.NullHandler) for handler in logger.handlers):
+ logger.addHandler(logging.NullHandler())
+ logger.propagate = False
+ logger.setLevel(logging.CRITICAL)
+ logger.disabled = True
+ return logger
+
+
+def _validate_pusher_cluster(cluster: object) -> str:
+ """Return ``cluster`` once it is known to be a plain cluster label.
+
+ :raises InvalidPusherClusterError: naming the shape violation, never the
+ value itself, since the response that carried it is untrusted.
+ """
+ if not isinstance(cluster, str) or not cluster:
+ raise exceptions.InvalidPusherClusterError(
+ "Realtime credentials did not include a pusher cluster"
+ )
+ if len(cluster) > _PUSHER_CLUSTER_MAX_LENGTH:
+ raise exceptions.InvalidPusherClusterError(
+ "Realtime credentials returned a pusher cluster longer than "
+ f"{_PUSHER_CLUSTER_MAX_LENGTH} characters"
+ )
+ if _PUSHER_CLUSTER_PATTERN.match(cluster) is None:
+ raise exceptions.InvalidPusherClusterError(
+ "Realtime credentials returned a pusher cluster with characters "
+ "outside [a-z0-9-]"
+ )
+ return cluster
+
+
+class _ComposioPusher(Pusher):
+ """``pysher.Pusher`` with a bounded, typed channel-auth request.
+
+ pysher's own ``_generate_auth_token``/``_generate_presence_token`` POST to
+ the auth endpoint with no timeout and turn a non-200 into a bare
+ ``AssertionError``, on the websocket thread, on every (re)subscribe. Both
+ are replaced here: the request carries :data:`PUSHER_AUTH_TIMEOUT`, and any
+ failure surfaces as :class:`~composio.exceptions.TriggerSubscriptionAuthError`.
+
+ The endpoint is the Composio API base URL the client was configured with,
+ a fixed trusted host rather than a value from a response, so the request
+ is a plain ``requests.post`` instead of going through the SSRF guard.
+ """
+
+ def _generate_auth_token(self, channel_name: str) -> str:
+ if self.secret or not self.auth_endpoint:
+ return t.cast(str, super()._generate_auth_token(channel_name))
+ return self._request_channel_auth(
+ {"channel_name": channel_name, "socket_id": self.connection.socket_id}
+ )
+
+ def _generate_presence_token(self, channel_name: str) -> str:
+ if self.secret or not self.auth_endpoint:
+ return t.cast(str, super()._generate_presence_token(channel_name))
+ return self._request_channel_auth(
+ {
+ "channel_name": channel_name,
+ "socket_id": self.connection.socket_id,
+ "user_data": self.user_data,
+ }
+ )
+
+ def _request_channel_auth(self, request_data: t.Dict[str, t.Any]) -> str:
+ try:
+ response = requests.post(
+ self.auth_endpoint,
+ data=request_data,
+ headers=self.auth_endpoint_headers,
+ timeout=PUSHER_AUTH_TIMEOUT,
+ )
+ except requests.RequestException as error:
+ raise exceptions.TriggerSubscriptionAuthError(
+ f"Could not reach the realtime auth endpoint: {type(error).__name__}"
+ ) from error
+
+ if response.status_code != 200:
+ raise exceptions.TriggerSubscriptionAuthError(
+ f"Realtime channel auth failed with HTTP {response.status_code}"
+ )
+
+ try:
+ auth = response.json()["auth"]
+ except (ValueError, KeyError, TypeError) as error:
+ raise exceptions.TriggerSubscriptionAuthError(
+ "Realtime channel auth response did not carry an `auth` token"
+ ) from error
+ if not isinstance(auth, str) or not auth:
+ raise exceptions.TriggerSubscriptionAuthError(
+ "Realtime channel auth response did not carry an `auth` token"
+ )
+ return auth
+
+
class _SubcriptionBuilder(WithLogger):
"""Pusher client for Composio SDK."""
@@ -879,9 +1000,9 @@ class _SubcriptionBuilder(WithLogger):
def _get_pusher_instance(self, key: str, cluster: str) -> Pusher:
"""Get a pusher instance."""
- return Pusher(
+ return _ComposioPusher(
key=key,
- cluster=cluster,
+ cluster=_validate_pusher_cluster(cluster),
auth_endpoint=PUSHER_AUTH_URL.format(base_url=self._client.base_url),
auth_endpoint_headers={
"x-api-key": self._client.api_key,
@@ -899,8 +1020,8 @@ class _SubcriptionBuilder(WithLogger):
cluster=project_info.pusher_cluster,
)
- # Patch pusher logger
- pusher.connection.logger = mock.MagicMock() # type: ignore
+ # pysher logs every raw frame at INFO; keep them out of user logs.
+ pusher.connection.logger = _silent_pysher_logger()
pusher.connection.bind(
"pusher:connection_established",
self._get_connection_handler(
diff --git a/python/composio/exceptions.py b/python/composio/exceptions.py
index 16eab8930..daf9c2606 100644
--- a/python/composio/exceptions.py
+++ b/python/composio/exceptions.py
@@ -292,6 +292,22 @@ class InvalidTriggerFilters(TriggerSubscriptionError):
pass
+class TriggerSubscriptionAuthError(TriggerSubscriptionError):
+ """Raised when the realtime channel-auth request fails.
+
+ Covers a transport error, a timeout, a non-200 response, and a response
+ without an ``auth`` token.
+ """
+
+ pass
+
+
+class InvalidPusherClusterError(TriggerSubscriptionError, ValidationError):
+ """Raised when the realtime credentials carry a malformed pusher cluster."""
+
+ pass
+
+
class ApiKeyError(ComposioClientError):
pass
diff --git a/python/composio/utils/url_safety.py b/python/composio/utils/url_safety.py
index 89608d21e..a45cc3ef1 100644
--- a/python/composio/utils/url_safety.py
+++ b/python/composio/utils/url_safety.py
@@ -72,9 +72,44 @@ _BODY_HEADERS = frozenset(
"transfer-encoding",
}
)
+# Headers that carry a credential for the origin the request was addressed
+# to, so they must not follow a redirect to a different origin. The Fetch
+# standard strips ``Authorization`` on a cross-origin redirect; ``Cookie`` and
+# ``Proxy-Authorization`` go with it the way ``requests``' own ``rebuild_auth``
+# and curl drop them on a host change. Following redirects by hand bypasses
+# ``rebuild_auth``, so the rule is applied here. The TypeScript guard drops the
+# same three (``CREDENTIAL_HEADERS``).
+_CREDENTIAL_HEADERS = frozenset({"authorization", "cookie", "proxy-authorization"})
_MAX_REDIRECTS = 5
+def _origin(url: str) -> t.Optional[t.Tuple[str, str, int]]:
+ """The ``(scheme, host, port)`` triple two URLs must share to be same-origin.
+
+ ``None`` when the URL cannot be parsed: ``urlparse`` raises ``ValueError``
+ for a broken IPv6 literal, and ``.port`` for an out-of-range port. A
+ redirect ``Location`` is remote input, so that is not an error here: the
+ hop is treated as leaving the origin, and :func:`assert_safe_fetch_target`
+ rejects the URL before anything is sent.
+ """
+ try:
+ parsed = urlparse(url)
+ scheme = parsed.scheme.lower()
+ host = (parsed.hostname or "").lower()
+ port = parsed.port
+ except ValueError:
+ return None
+ if port is None:
+ port = 443 if scheme == "https" else 80
+ return scheme, host, port
+
+
+def _same_origin(previous_url: str, next_url: str) -> bool:
+ """Whether a redirect hop stays on the origin the caller addressed."""
+ previous_origin = _origin(previous_url)
+ return previous_origin is not None and previous_origin == _origin(next_url)
+
+
def is_blocked_ip(value: str) -> bool:
"""Return whether an address is non-publicly-routable."""
try:
@@ -233,7 +268,15 @@ def safe_request(
return response
response.close()
- current_url = urljoin(current_url, location)
+ previous_url = current_url
+ try:
+ current_url = urljoin(current_url, location)
+ except ValueError:
+ # `urljoin` refuses a broken IPv6 literal. `Location` is remote
+ # input, so this is a rejected hop, not a crash.
+ raise BlockedInternalUrlError(
+ "Refusing to follow a malformed redirect Location"
+ ) from None
# The next hop is whatever `Location` says, query string included, so
# `params` must not be appended to it a second time — that is how
@@ -241,6 +284,16 @@ def safe_request(
# credential from being handed to a target that never asked for one.
kwargs.pop("params", None)
+ # A credential header was addressed to the origin the caller named, so
+ # a hop that leaves that origin must not carry it along.
+ if not _same_origin(previous_url, current_url):
+ if headers := kwargs.get("headers"):
+ kwargs["headers"] = {
+ name: value
+ for name, value in headers.items()
+ if name.lower() not in _CREDENTIAL_HEADERS
+ }
+
rewritten_method = _redirect_rewrite(response.status_code, method)
if rewritten_method is not None:
method = rewritten_method
diff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.py
index 29b5873f7..56d487ee5 100644
--- a/python/tests/test_triggers.py
+++ b/python/tests/test_triggers.py
@@ -4,6 +4,8 @@ import base64
import hashlib
import hmac
import json
+import logging
+import pathlib
import threading
import time
from datetime import datetime, timezone
@@ -11,9 +13,11 @@ from unittest.mock import Mock, patch
import httpx
import pytest
+import requests
from composio_client import NotFoundError, omit
from composio import exceptions
+from composio.core.models import triggers as triggers_module
from composio.core.models.triggers import (
_MAX_LOGGED_FRAME_CHARS,
ComposioSDKTimeoutError,
@@ -1789,3 +1793,186 @@ class TestSubscriptionBuilderConnectTimeout:
assert result is builder.subscription
pusher.disconnect.assert_not_called()
+
+
+class TestPusherChannelAuth:
+ """Tests for the hardened pysher channel-auth request."""
+
+ @staticmethod
+ def _pusher() -> triggers_module._ComposioPusher:
+ return triggers_module._ComposioPusher(
+ key="app-key",
+ cluster="mt1",
+ auth_endpoint="https://api.example.com/api/v3/internal/sdk/realtime/auth",
+ auth_endpoint_headers={"x-api-key": "sk-secret-value"},
+ )
+
+ def test_auth_request_carries_a_timeout(self):
+ """pysher sends the auth POST with no timeout; the subclass bounds it."""
+ pusher = self._pusher()
+ pusher.connection.socket_id = "123.456"
+ response = Mock(status_code=200)
+ response.json.return_value = {"auth": "app-key:signature"}
+
+ with patch.object(
+ triggers_module.requests, "post", return_value=response
+ ) as post:
+ token = pusher._generate_auth_token("private-project_triggers")
+
+ assert token == "app-key:signature"
+ post.assert_called_once_with(
+ "https://api.example.com/api/v3/internal/sdk/realtime/auth",
+ data={"channel_name": "private-project_triggers", "socket_id": "123.456"},
+ headers={"x-api-key": "sk-secret-value"},
+ timeout=triggers_module.PUSHER_AUTH_TIMEOUT,
+ )
+ assert triggers_module.PUSHER_AUTH_TIMEOUT == (5.0, 15.0)
+
+ def test_presence_request_carries_a_timeout(self):
+ pusher = self._pusher()
+ pusher.connection.socket_id = "123.456"
+ response = Mock(status_code=200)
+ response.json.return_value = {"auth": "app-key:signature"}
+
+ with patch.object(
+ triggers_module.requests, "post", return_value=response
+ ) as post:
+ pusher._generate_presence_token("presence-room")
+
+ assert post.call_args.kwargs["timeout"] == triggers_module.PUSHER_AUTH_TIMEOUT
+ assert post.call_args.kwargs["data"]["user_data"] == {}
+
+ @pytest.mark.parametrize("status_code", [401, 403, 500])
+ def test_non_200_raises_typed_error_without_the_api_key(self, status_code):
+ """A non-200 used to trip a bare ``assert`` on the websocket thread."""
+ pusher = self._pusher()
+ response = Mock(status_code=status_code)
+
+ with (
+ patch.object(triggers_module.requests, "post", return_value=response),
+ pytest.raises(exceptions.TriggerSubscriptionAuthError) as info,
+ ):
+ pusher._generate_auth_token("private-project_triggers")
+
+ assert isinstance(info.value, exceptions.TriggerSubscriptionError)
+ assert f"HTTP {status_code}" in str(info.value)
+ assert "sk-secret-value" not in str(info.value)
+
+ def test_transport_failure_raises_typed_error(self):
+ with (
+ patch.object(
+ triggers_module.requests,
+ "post",
+ side_effect=requests.ConnectTimeout("slow"),
+ ),
+ pytest.raises(
+ exceptions.TriggerSubscriptionAuthError, match="ConnectTimeout"
+ ),
+ ):
+ self._pusher()._generate_auth_token("private-project_triggers")
+
+ @pytest.mark.parametrize("body", [{}, {"auth": ""}, {"auth": 1}, []])
+ def test_missing_auth_token_raises_typed_error(self, body):
+ response = Mock(status_code=200)
+ response.json.return_value = body
+
+ with (
+ patch.object(triggers_module.requests, "post", return_value=response),
+ pytest.raises(
+ exceptions.TriggerSubscriptionAuthError, match="`auth` token"
+ ),
+ ):
+ self._pusher()._generate_auth_token("private-project_triggers")
+
+
+class TestPusherClusterValidation:
+ """The cluster comes from an API response and lands in the websocket host."""
+
+ @staticmethod
+ def _builder() -> _SubcriptionBuilder:
+ client = Mock()
+ client.base_url = "https://api.example.com"
+ client.api_key = "sk-secret-value"
+ return _SubcriptionBuilder(client=client)
+
+ @pytest.mark.parametrize("cluster", ["mt1", "eu", "ap-southeast-1", "us3"])
+ def test_valid_cluster_builds_the_expected_host(self, cluster):
+ pusher = self._builder()._get_pusher_instance(key="app-key", cluster=cluster)
+
+ assert isinstance(pusher, triggers_module._ComposioPusher)
+ assert pusher.host == f"ws-{cluster}.pusher.com"
+ assert pusher.auth_endpoint_headers["x-api-key"] == "sk-secret-value"
+
+ @pytest.mark.parametrize(
+ ("cluster", "reason"),
+ [
+ ("", "did not include"),
+ (None, "did not include"),
+ ("MT1", "outside"),
+ ("mt1.evil.example", "outside"),
+ ("mt1/../evil", "outside"),
+ ("mt1 ", "outside"),
+ ("mt1:8080", "outside"),
+ ("a" * 65, "longer than 64"),
+ ],
+ )
+ def test_invalid_cluster_is_rejected_before_building_pusher(self, cluster, reason):
+ with (
+ patch.object(triggers_module, "_ComposioPusher") as pusher_cls,
+ pytest.raises(exceptions.InvalidPusherClusterError, match=reason) as info,
+ ):
+ self._builder()._get_pusher_instance(key="app-key", cluster=cluster)
+
+ pusher_cls.assert_not_called()
+ assert isinstance(info.value, exceptions.TriggerSubscriptionError)
+ assert isinstance(info.value, exceptions.ValidationError)
+ # The offending value is never echoed; the response is untrusted.
+ if cluster:
+ assert cluster not in str(info.value)
+
+
+class TestPysherLogger:
+ def test_module_does_not_import_unittest(self):
+ """``unittest.mock`` used to stand in for a logger at runtime."""
+ source = pathlib.Path(triggers_module.__file__).read_text()
+
+ assert "unittest" not in source
+ assert not hasattr(triggers_module, "mock")
+
+ def test_silent_logger_emits_nothing(self, caplog):
+ logger = triggers_module._silent_pysher_logger()
+
+ assert isinstance(logger, logging.Logger)
+ assert logger.propagate is False
+ assert any(isinstance(h, logging.NullHandler) for h in logger.handlers)
+ with caplog.at_level(logging.DEBUG):
+ logger.info("Connection: Message - %s", '{"data": "raw frame"}')
+ logger.error("Connection: Error")
+ assert caplog.records == []
+
+ def test_silent_logger_is_idempotent(self):
+ first = triggers_module._silent_pysher_logger()
+ second = triggers_module._silent_pysher_logger()
+
+ assert first is second
+ assert sum(isinstance(h, logging.NullHandler) for h in first.handlers) == 1
+
+ def test_connect_installs_the_silent_logger(self):
+ client = Mock()
+ client.base_url = "https://api.example.com"
+ pusher = Mock()
+ builder = _SubcriptionBuilder(client=client)
+ builder.subscription = Mock()
+ builder.subscription.is_alive.return_value = True
+ builder.internal = Mock()
+ builder.internal.get_sdk_realtime_credentials.return_value = Mock(
+ project_id="p", pusher_key="k", pusher_cluster="mt1"
+ )
+
+ with patch.object(
+ _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
+ ):
+ builder.connect(timeout=2.0)
+
+ assert isinstance(pusher.connection.logger, logging.Logger)
+ assert pusher.connection.logger.name == triggers_module._PYSHER_LOGGER_NAME
diff --git a/python/tests/test_url_safety.py b/python/tests/test_url_safety.py
index 73e5eb9d5..73c27b8ed 100644
--- a/python/tests/test_url_safety.py
+++ b/python/tests/test_url_safety.py
@@ -292,6 +292,122 @@ def test_safe_request_does_not_reapply_params_to_the_redirect_target(
)
+_CREDENTIALED: t.Dict[str, str] = {
+ "Authorization": "Bearer token",
+ "Proxy-Authorization": "Basic cHJveHk=",
+ "Cookie": "session=abc",
+ "X-Test": "kept",
+}
+
+
+ "location",
+ [
+ "https://other.example.com/elsewhere", # different host
+ "http://example.com/elsewhere", # different scheme
+ "https://example.com:8443/elsewhere", # different port
+ ],
+)
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_drops_credentials_on_cross_origin_redirect(
+ mock_assert, mock_request, location: str
+) -> None:
+ """Manual redirects bypass `requests`' `rebuild_auth`, so strip here.
+
+ A credential header is addressed to the origin the caller named; replaying
+ it to another origin hands the bearer token to whoever answered the
+ redirect. Mirrors the Fetch rule `ssrfSafeFetch` applies.
+ """
+ mock_request.side_effect = [_response(307, location), _response(200)]
+
+ safe_request("GET", "https://example.com/download", headers=dict(_CREDENTIALED))
+
+ assert mock_request.call_args_list[1] == call(
+ "GET",
+ location,
+ allow_redirects=False,
+ headers={"X-Test": "kept"},
+ )
+
+
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_keeps_credentials_on_same_origin_redirect(
+ mock_assert, mock_request
+) -> None:
+ mock_request.side_effect = [
+ _response(307, "https://example.com:443/moved"),
+ _response(200),
+ ]
+
+ safe_request("GET", "https://example.com/download", headers=dict(_CREDENTIALED))
+
+ assert mock_request.call_args_list[1] == call(
+ "GET",
+ "https://example.com:443/moved",
+ allow_redirects=False,
+ headers=_CREDENTIALED,
+ )
+
+
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_strips_credentials_case_insensitively(
+ mock_assert, mock_request
+) -> None:
+ mock_request.side_effect = [
+ _response(302, "https://other.example.com/elsewhere"),
+ _response(200),
+ ]
+
+ safe_request(
+ "GET",
+ "https://example.com/download",
+ headers={"AUTHORIZATION": "Bearer token", "cookie": "a=b", "X-Test": "kept"},
+ )
+
+ assert mock_request.call_args_list[1].kwargs["headers"] == {"X-Test": "kept"}
+
+
+ "location",
+ [
+ "https://example.com:99999/elsewhere", # port out of range
+ "https://[::1/elsewhere", # broken IPv6 literal
+ ],
+)
+@patch("composio.utils.url_safety.requests.Session.request")
+@patch("composio.utils.url_safety.assert_safe_fetch_target")
+def test_safe_request_unparseable_redirect_is_blocked_not_a_crash(
+ mock_assert, mock_request, location: str
+) -> None:
+ """`urljoin` / `urlparse(...).port` raise `ValueError` on these.
+
+ Both run on the `Location` before the target is validated, so they must
+ not turn remote input into a stray `ValueError` that call sites catching
+ only `RequestException` would let escape. The hop is rejected the way any
+ malformed URL is, and never sent.
+ """
+ mock_assert.side_effect = [["93.184.216.34"], BlockedInternalUrlError("blocked")]
+ mock_request.return_value = _response(307, location)
+
+ with pytest.raises(BlockedInternalUrlError):
+ safe_request("GET", "https://example.com/download", headers=dict(_CREDENTIALED))
+
+ assert mock_request.call_count == 1
+
+
+def test_origin_is_none_for_unparseable_urls() -> None:
+ from composio.utils.url_safety import _origin, _same_origin
+
+ assert _origin("https://example.com:99999/x") is None
+ assert _origin("https://[::1/x") is None
+ assert _origin("https://example.com/x") == ("https", "example.com", 443)
+ assert not _same_origin("https://example.com/a", "https://example.com:99999/b")
+ assert _same_origin("https://example.com/a", "https://example.com:443/b")
+
+
@patch("composio.utils.url_safety.requests.Session.request")
@patch("composio.utils.url_safety.assert_safe_fetch_target")
def test_safe_request_relative_redirect_is_resolved(mock_assert, mock_request) -> None:
diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.ts
index 24c53073e..361b1a096 100644
--- a/ts/packages/core/src/utils/ssrfGuard.node.ts
+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts
@@ -81,12 +81,30 @@ const redirectRewrite = (status: number, method: string): string | null => {
return null;
};
-const applyRedirectSemantics = (init: RequestInit, status: number): RequestInit => {
+/**
+ * Headers that carry a credential for the origin the request was addressed
+ * to, so they must not follow a redirect to a different origin. The Fetch
+ * standard strips `Authorization` on a cross-origin redirect; `Cookie` and
+ * `Proxy-Authorization` go with it the way `requests` and curl drop them on a
+ * host change. `redirect: 'manual'` means `fetch` never applies that rule for
+ * us either. The Python guard drops the same three (`_CREDENTIAL_HEADERS`).
+ */
+const CREDENTIAL_HEADERS = ['authorization', 'cookie', 'proxy-authorization'];
+
+const applyRedirectSemantics = (
+ init: RequestInit,
+ status: number,
+ fromUrl: string,
+ toUrl: string
+): RequestInit => {
const method = redirectRewrite(status, (init.method ?? 'GET').toUpperCase());
- if (method === null) return init;
+ const crossOrigin = new URL(fromUrl).origin !== new URL(toUrl).origin;
+ if (method === null && !crossOrigin) return init;
const headers = new Headers(init.headers);
- for (const name of BODY_HEADERS) headers.delete(name);
+ if (method !== null) for (const name of BODY_HEADERS) headers.delete(name);
+ if (crossOrigin) for (const name of CREDENTIAL_HEADERS) headers.delete(name);
+ if (method === null) return { ...init, headers };
return { ...init, method, body: undefined, headers };
};
@@ -284,8 +302,8 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> =
* connects to the address it validated, and re-validates and re-pins every
* redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
* Intermediate redirect bodies are cancelled; non-redirect responses are
- * returned unchanged. Each hop carries the method and body the Fetch standard
- * says it should — see {@link applyRedirectSemantics}.
+ * returned unchanged. Each hop carries the method, body, and credential headers
+ * the Fetch standard says it should — see {@link applyRedirectSemantics}.
*
* A hop whose effective dispatcher is a configured route (caller-supplied
* `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
@@ -357,8 +375,9 @@ export const ssrfSafeFetch = async (
// than leaving it to the garbage collector (mirrors `readResponseBodyWithLimit`).
await response.body?.cancel().catch(() => undefined);
- currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
- currentInit = applyRedirectSemantics(currentInit, response.status);
+ const nextUrl = new URL(response.headers.get('location')!, currentUrl).toString();
+ currentInit = applyRedirectSemantics(currentInit, response.status, currentUrl, nextUrl);
+ currentUrl = nextUrl;
}
throw new ComposioBlockedInternalUrlError(
diff --git a/ts/packages/core/test/utils/ssrfGuard.test.ts b/ts/packages/core/test/utils/ssrfGuard.test.ts
index f4e4ec642..c35dc0c01 100644
--- a/ts/packages/core/test/utils/ssrfGuard.test.ts
+++ b/ts/packages/core/test/utils/ssrfGuard.test.ts
@@ -437,6 +437,80 @@ describe('ssrfSafeFetch', () => {
expect(mockFetch.mock.calls[2][1].body).toBeUndefined();
});
+ // A credential header is addressed to the origin the caller named, so a hop
+ // that leaves that origin must not carry it: `redirect: 'manual'` means
+ // `fetch` never strips it for us. The Python guard applies the same rule.
+ const credentialed = {
+ Authorization: 'Bearer token',
+ 'Proxy-Authorization': 'Basic cHJveHk=',
+ Cookie: 'session=abc',
+ 'X-Test': 'kept',
+ };
+
+ it.each([
+ { location: 'https://other.example.com/elsewhere', differs: 'host' },
+ { location: 'http://example.com/elsewhere', differs: 'scheme' },
+ { location: 'https://example.com:8443/elsewhere', differs: 'port' },
+ ])('drops credential headers on a redirect to a different $differs', async ({ location }) => {
+ resolvesTo('93.184.216.34');
+ mockFetch
+ .mockResolvedValueOnce(new Response(null, { status: 307, headers: { location } }))
+ .mockResolvedValueOnce(new Response('data', { status: 200 }));
+
+ await ssrfSafeFetch('https://example.com/download', { headers: credentialed });
+
+ const [url, init] = mockFetch.mock.calls[1];
+ expect(url).toBe(location);
+ const headers = new Headers(init.headers);
+ expect(headers.get('authorization')).toBeNull();
+ expect(headers.get('proxy-authorization')).toBeNull();
+ expect(headers.get('cookie')).toBeNull();
+ expect(headers.get('x-test')).toBe('kept');
+ });
+
+ it('keeps credential headers on a same-origin redirect', async () => {
+ resolvesTo('93.184.216.34');
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(null, { status: 307, headers: { location: 'https://example.com:443/moved' } })
+ )
+ .mockResolvedValueOnce(new Response('data', { status: 200 }));
+
+ await ssrfSafeFetch('https://example.com/download', { headers: credentialed });
+
+ const headers = new Headers(mockFetch.mock.calls[1][1].headers);
+ expect(headers.get('authorization')).toBe('Bearer token');
+ expect(headers.get('proxy-authorization')).toBe('Basic cHJveHk=');
+ expect(headers.get('cookie')).toBe('session=abc');
+ expect(headers.get('x-test')).toBe('kept');
+ });
+
+ it('drops credential headers together with the body on a cross-origin 303', async () => {
+ resolvesTo('93.184.216.34');
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response(null, {
+ status: 303,
+ headers: { location: 'https://other.example.com/result' },
+ })
+ )
+ .mockResolvedValueOnce(new Response('data', { status: 200 }));
+
+ await ssrfSafeFetch('https://example.com/create', {
+ method: 'POST',
+ body: 'payload',
+ headers: { ...credentialed, 'Content-Type': 'application/octet-stream' },
+ });
+
+ const init = mockFetch.mock.calls[1][1];
+ expect(init.method).toBe('GET');
+ expect(init.body).toBeUndefined();
+ const headers = new Headers(init.headers);
+ expect(headers.get('content-type')).toBeNull();
+ expect(headers.get('authorization')).toBeNull();
+ expect(headers.get('x-test')).toBe('kept');
+ });
+
it.each([300, 304, 305, 306])(
'returns a %i without following its location',
async (status: number) => {