4
import hashlib
5
import hmac
6
import json
7
+import logging
8
+import pathlib
9
import threading
10
import time
11
from datetime import datetime, timezone
13
14
import httpx
15
import pytest
16
+import requests
17
from composio_client import NotFoundError, omit
18
19
from composio import exceptions
20
+from composio.core.models import triggers as triggers_module
21
from composio.core.models.triggers import (
22
_MAX_LOGGED_FRAME_CHARS,
23
ComposioSDKTimeoutError,
1793
1794
assert result is builder.subscription
1795
pusher.disconnect.assert_not_called()
1796
+
1797
+
1798
+class TestPusherChannelAuth:
1799
+ """Tests for the hardened pysher channel-auth request."""
1800
+
1801
+ @staticmethod
1802
+ def _pusher() -> triggers_module._ComposioPusher:
1803
+ return triggers_module._ComposioPusher(
1804
+ key="app-key",
1805
+ cluster="mt1",
1806
+ auth_endpoint="https://api.example.com/api/v3/internal/sdk/realtime/auth",
1807
+ auth_endpoint_headers={"x-api-key": "sk-secret-value"},
1808
+ )
1809
+
1810
+ def test_auth_request_carries_a_timeout(self):
1811
+ """pysher sends the auth POST with no timeout; the subclass bounds it."""
1812
+ pusher = self._pusher()
1813
+ pusher.connection.socket_id = "123.456"
1814
+ response = Mock(status_code=200)
1815
+ response.json.return_value = {"auth": "app-key:signature"}
1816
+
1817
+ with patch.object(
1818
+ triggers_module.requests, "post", return_value=response
1819
+ ) as post:
1820
+ token = pusher._generate_auth_token("private-project_triggers")
1821
+
1822
+ assert token == "app-key:signature"
1823
+ post.assert_called_once_with(
1824
+ "https://api.example.com/api/v3/internal/sdk/realtime/auth",
1825
+ data={"channel_name": "private-project_triggers", "socket_id": "123.456"},
1826
+ headers={"x-api-key": "sk-secret-value"},
1827
+ timeout=triggers_module.PUSHER_AUTH_TIMEOUT,
1828
+ )
1829
+ assert triggers_module.PUSHER_AUTH_TIMEOUT == (5.0, 15.0)
1830
+
1831
+ def test_presence_request_carries_a_timeout(self):
1832
+ pusher = self._pusher()
1833
+ pusher.connection.socket_id = "123.456"
1834
+ response = Mock(status_code=200)
1835
+ response.json.return_value = {"auth": "app-key:signature"}
1836
+
1837
+ with patch.object(
1838
+ triggers_module.requests, "post", return_value=response
1839
+ ) as post:
1840
+ pusher._generate_presence_token("presence-room")
1841
+
1842
+ assert post.call_args.kwargs["timeout"] == triggers_module.PUSHER_AUTH_TIMEOUT
1843
+ assert post.call_args.kwargs["data"]["user_data"] == {}
1844
+
1845
+ @pytest.mark.parametrize("status_code", [401, 403, 500])
1846
+ def test_non_200_raises_typed_error_without_the_api_key(self, status_code):
1847
+ """A non-200 used to trip a bare ``assert`` on the websocket thread."""
1848
+ pusher = self._pusher()
1849
+ response = Mock(status_code=status_code)
1850
+
1851
+ with (
1852
+ patch.object(triggers_module.requests, "post", return_value=response),
1853
+ pytest.raises(exceptions.TriggerSubscriptionAuthError) as info,
1854
+ ):
1855
+ pusher._generate_auth_token("private-project_triggers")
1856
+
1857
+ assert isinstance(info.value, exceptions.TriggerSubscriptionError)
1858
+ assert f"HTTP {status_code}" in str(info.value)
1859
+ assert "sk-secret-value" not in str(info.value)
1860
+
1861
+ def test_transport_failure_raises_typed_error(self):
1862
+ with (
1863
+ patch.object(
1864
+ triggers_module.requests,
1865
+ "post",
1866
+ side_effect=requests.ConnectTimeout("slow"),
1867
+ ),
1868
+ pytest.raises(
1869
+ exceptions.TriggerSubscriptionAuthError, match="ConnectTimeout"
1870
+ ),
1871
+ ):
1872
+ self._pusher()._generate_auth_token("private-project_triggers")
1873
+
1874
+ @pytest.mark.parametrize("body", [{}, {"auth": ""}, {"auth": 1}, []])
1875
+ def test_missing_auth_token_raises_typed_error(self, body):
1876
+ response = Mock(status_code=200)
1877
+ response.json.return_value = body
1878
+
1879
+ with (
1880
+ patch.object(triggers_module.requests, "post", return_value=response),
1881
+ pytest.raises(
1882
+ exceptions.TriggerSubscriptionAuthError, match="`auth` token"
1883
+ ),
1884
+ ):
1885
+ self._pusher()._generate_auth_token("private-project_triggers")
1886
+
1887
+
1888
+class TestPusherClusterValidation:
1889
+ """The cluster comes from an API response and lands in the websocket host."""
1890
+
1891
+ @staticmethod
1892
+ def _builder() -> _SubcriptionBuilder:
1893
+ client = Mock()
1894
+ client.base_url = "https://api.example.com"
1895
+ client.api_key = "sk-secret-value"
1896
+ return _SubcriptionBuilder(client=client)
1897
+
1898
+ @pytest.mark.parametrize("cluster", ["mt1", "eu", "ap-southeast-1", "us3"])
1899
+ def test_valid_cluster_builds_the_expected_host(self, cluster):
1900
+ pusher = self._builder()._get_pusher_instance(key="app-key", cluster=cluster)
1901
+
1902
+ assert isinstance(pusher, triggers_module._ComposioPusher)
1903
+ assert pusher.host == f"ws-{cluster}.pusher.com"
1904
+ assert pusher.auth_endpoint_headers["x-api-key"] == "sk-secret-value"
1905
+
1906
+ @pytest.mark.parametrize(
1907
+ ("cluster", "reason"),
1908
+ [
1909
+ ("", "did not include"),
1910
+ (None, "did not include"),
1911
+ ("MT1", "outside"),
1912
+ ("mt1.evil.example", "outside"),
1913
+ ("mt1/../evil", "outside"),
1914
+ ("mt1 ", "outside"),
1915
+ ("mt1:8080", "outside"),
1916
+ ("a" * 65, "longer than 64"),
1917
+ ],
1918
+ )
1919
+ def test_invalid_cluster_is_rejected_before_building_pusher(self, cluster, reason):
1920
+ with (
1921
+ patch.object(triggers_module, "_ComposioPusher") as pusher_cls,
1922
+ pytest.raises(exceptions.InvalidPusherClusterError, match=reason) as info,
1923
+ ):
1924
+ self._builder()._get_pusher_instance(key="app-key", cluster=cluster)
1925
+
1926
+ pusher_cls.assert_not_called()
1927
+ assert isinstance(info.value, exceptions.TriggerSubscriptionError)
1928
+ assert isinstance(info.value, exceptions.ValidationError)
1929
+ # The offending value is never echoed; the response is untrusted.
1930
+ if cluster:
1931
+ assert cluster not in str(info.value)
1932
+
1933
+
1934
+class TestPysherLogger:
1935
+ def test_module_does_not_import_unittest(self):
1936
+ """``unittest.mock`` used to stand in for a logger at runtime."""
1937
+ source = pathlib.Path(triggers_module.__file__).read_text()
1938
+
1939
+ assert "unittest" not in source
1940
+ assert not hasattr(triggers_module, "mock")
1941
+
1942
+ def test_silent_logger_emits_nothing(self, caplog):
1943
+ logger = triggers_module._silent_pysher_logger()
1944
+
1945
+ assert isinstance(logger, logging.Logger)
1946
+ assert logger.propagate is False
1947
+ assert any(isinstance(h, logging.NullHandler) for h in logger.handlers)
1948
+ with caplog.at_level(logging.DEBUG):
1949
+ logger.info("Connection: Message - %s", '{"data": "raw frame"}')
1950
+ logger.error("Connection: Error")
1951
+ assert caplog.records == []
1952
+
1953
+ def test_silent_logger_is_idempotent(self):
1954
+ first = triggers_module._silent_pysher_logger()
1955
+ second = triggers_module._silent_pysher_logger()
1956
+
1957
+ assert first is second
1958
+ assert sum(isinstance(h, logging.NullHandler) for h in first.handlers) == 1
1959
+
1960
+ def test_connect_installs_the_silent_logger(self):
1961
+ client = Mock()
1962
+ client.base_url = "https://api.example.com"
1963
+ pusher = Mock()
1964
+ builder = _SubcriptionBuilder(client=client)
1965
+ builder.subscription = Mock()
1966
+ builder.subscription.is_alive.return_value = True
1967
+ builder.internal = Mock()
1968
+ builder.internal.get_sdk_realtime_credentials.return_value = Mock(
1969
+ project_id="p", pusher_key="k", pusher_cluster="mt1"
1970
+ )
1971
+
1972
+ with patch.object(
1973
+ _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1974
+ ):
1975
+ builder.connect(timeout=2.0)
1976
+
1977
+ assert isinstance(pusher.connection.logger, logging.Logger)
1978
+ assert pusher.connection.logger.name == triggers_module._PYSHER_LOGGER_NAME