Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 03:37 UTC
| 1 | """Tests for Triggers class.""" |
| 2 | |
| 3 | import base64 |
| 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 |
| 12 | from unittest.mock import Mock, patch |
| 13 | |
| 14 | import httpx |
| 15 | import pytest |
| 16 | import requests |
| 17 | from composio_client import NoAuth, NotFoundError, ProjectAuth, UserAuth, 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, |
| 24 | Triggers, |
| 25 | TriggerSubscription, |
| 26 | WebhookVersion, |
| 27 | _SubcriptionBuilder, |
| 28 | _truncate_frame, |
| 29 | ) |
| 30 | |
| 31 | |
| 32 | class TestTriggers: |
| 33 | """Test cases for Triggers class.""" |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def mock_client(self): |
| 37 | """Create a mock HTTP client.""" |
| 38 | client = Mock() |
| 39 | client.triggers_types = Mock() |
| 40 | client.trigger_instances = Mock() |
| 41 | client.trigger_instances.manage = Mock() |
| 42 | client.connected_accounts = Mock() |
| 43 | return client |
| 44 | |
| 45 | @pytest.fixture |
| 46 | def triggers(self, mock_client): |
| 47 | """Create a Triggers instance with default toolkit versions.""" |
| 48 | return Triggers(client=mock_client) |
| 49 | |
| 50 | @pytest.fixture |
| 51 | def triggers_with_versions(self, mock_client): |
| 52 | """Create a Triggers instance with custom toolkit versions.""" |
| 53 | return Triggers( |
| 54 | client=mock_client, |
| 55 | toolkit_versions={"github": "12082025_00", "slack": "10082025_01"}, |
| 56 | ) |
| 57 | |
| 58 | @pytest.fixture |
| 59 | def mock_trigger_type(self): |
| 60 | """Mock trigger type response.""" |
| 61 | mock_type = Mock() |
| 62 | mock_type.slug = "GITHUB_COMMIT_EVENT" |
| 63 | mock_type.name = "GitHub Commit Event" |
| 64 | mock_type.description = "Triggered when a commit is pushed" |
| 65 | mock_type.toolkit = Mock() |
| 66 | mock_type.toolkit.slug = "github" |
| 67 | mock_type.toolkit.name = "GitHub" |
| 68 | return mock_type |
| 69 | |
| 70 | @pytest.fixture |
| 71 | def mock_trigger_instances(self): |
| 72 | """Mock trigger instances list response.""" |
| 73 | mock_response = Mock() |
| 74 | mock_response.items = [ |
| 75 | Mock( |
| 76 | id="trigger-1", |
| 77 | connected_account_id="conn-123", |
| 78 | disabled_at=None, |
| 79 | state={"lastRun": "2024-01-01T00:00:00Z"}, |
| 80 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 81 | trigger_name="GITHUB_COMMIT_EVENT", |
| 82 | updated_at="2024-01-01T00:00:00Z", |
| 83 | trigger_data='{"event":"push"}', |
| 84 | ), |
| 85 | ] |
| 86 | mock_response.next_cursor = None |
| 87 | mock_response.total_pages = 1 |
| 88 | return mock_response |
| 89 | |
| 90 | def test_init_with_default_versions(self, mock_client): |
| 91 | """Test Triggers initialization with default toolkit versions.""" |
| 92 | triggers = Triggers(client=mock_client) |
| 93 | |
| 94 | assert triggers._client == mock_client |
| 95 | assert triggers._toolkit_versions is None |
| 96 | assert callable(triggers.list_enum) |
| 97 | assert callable(triggers.delete) |
| 98 | assert callable(triggers.enable) |
| 99 | assert callable(triggers.disable) |
| 100 | |
| 101 | def test_init_with_custom_versions(self, mock_client): |
| 102 | """Test Triggers initialization with custom toolkit versions.""" |
| 103 | custom_versions = {"github": "12082025_00", "slack": "10082025_01"} |
| 104 | triggers = Triggers(client=mock_client, toolkit_versions=custom_versions) |
| 105 | |
| 106 | assert triggers._toolkit_versions == custom_versions |
| 107 | |
| 108 | def test_set_webhook_subscription_creates_when_none_exists( |
| 109 | self, triggers, mock_client |
| 110 | ): |
| 111 | """Test set_webhook_subscription creates a subscription when none exists.""" |
| 112 | webhook_url = "https://example.com/webhooks/composio" |
| 113 | raw_subscription = { |
| 114 | "id": "sub_123", |
| 115 | "webhook_url": webhook_url, |
| 116 | "version": "V3", |
| 117 | "enabled_events": ["composio.trigger.message"], |
| 118 | } |
| 119 | mock_client.webhook_subscriptions.list.return_value = Mock(items=[]) |
| 120 | mock_client.webhook_subscriptions.create.return_value = raw_subscription |
| 121 | |
| 122 | result = triggers.set_webhook_subscription(webhook_url=webhook_url) |
| 123 | |
| 124 | mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1) |
| 125 | mock_client.webhook_subscriptions.create.assert_called_once_with( |
| 126 | webhook_url=webhook_url, |
| 127 | enabled_events=["composio.trigger.message"], |
| 128 | version="V3", |
| 129 | ) |
| 130 | mock_client.webhook_subscriptions.update.assert_not_called() |
| 131 | assert result == raw_subscription |
| 132 | |
| 133 | def test_set_webhook_subscription_updates_first_existing( |
| 134 | self, triggers, mock_client |
| 135 | ): |
| 136 | """Test set_webhook_subscription updates the first subscription when one exists.""" |
| 137 | webhook_url = "https://example.com/webhooks/composio" |
| 138 | raw_subscription = { |
| 139 | "id": "sub_123", |
| 140 | "webhook_url": webhook_url, |
| 141 | "version": "V3", |
| 142 | "enabled_events": [ |
| 143 | "composio.trigger.message", |
| 144 | "composio.connected_account.expired", |
| 145 | ], |
| 146 | } |
| 147 | mock_client.webhook_subscriptions.list.return_value = Mock( |
| 148 | items=[Mock(id="sub_123")] |
| 149 | ) |
| 150 | mock_client.webhook_subscriptions.update.return_value = raw_subscription |
| 151 | |
| 152 | result = triggers.set_webhook_subscription( |
| 153 | webhook_url=webhook_url, |
| 154 | enabled_events=[ |
| 155 | "composio.trigger.message", |
| 156 | "composio.connected_account.expired", |
| 157 | ], |
| 158 | version="V3", |
| 159 | ) |
| 160 | |
| 161 | mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1) |
| 162 | mock_client.webhook_subscriptions.update.assert_called_once_with( |
| 163 | "sub_123", |
| 164 | webhook_url=webhook_url, |
| 165 | enabled_events=[ |
| 166 | "composio.trigger.message", |
| 167 | "composio.connected_account.expired", |
| 168 | ], |
| 169 | version="V3", |
| 170 | ) |
| 171 | mock_client.webhook_subscriptions.create.assert_not_called() |
| 172 | assert result == raw_subscription |
| 173 | |
| 174 | def test_set_webhook_subscription_rejects_empty_events(self, triggers): |
| 175 | """Test set_webhook_subscription rejects empty enabled_events.""" |
| 176 | with pytest.raises(exceptions.ValidationError): |
| 177 | triggers.set_webhook_subscription( |
| 178 | webhook_url="https://example.com/webhooks/composio", |
| 179 | enabled_events=[], |
| 180 | ) |
| 181 | |
| 182 | def test_get_type_with_default_versions( |
| 183 | self, triggers, mock_client, mock_trigger_type |
| 184 | ): |
| 185 | """Test get_type with default toolkit versions.""" |
| 186 | mock_client.triggers_types.retrieve.return_value = mock_trigger_type |
| 187 | |
| 188 | result = triggers.get_type("GITHUB_COMMIT_EVENT") |
| 189 | |
| 190 | # When toolkit_versions is None, it should be converted to omit |
| 191 | call_kwargs = mock_client.triggers_types.retrieve.call_args.kwargs |
| 192 | assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT" |
| 193 | assert call_kwargs["toolkit_versions"] is omit |
| 194 | assert result == mock_trigger_type |
| 195 | |
| 196 | def test_get_type_with_custom_versions( |
| 197 | self, triggers_with_versions, mock_client, mock_trigger_type |
| 198 | ): |
| 199 | """Test get_type with custom toolkit versions.""" |
| 200 | mock_client.triggers_types.retrieve.return_value = mock_trigger_type |
| 201 | custom_versions = {"github": "12082025_00", "slack": "10082025_01"} |
| 202 | |
| 203 | result = triggers_with_versions.get_type("GITHUB_COMMIT_EVENT") |
| 204 | |
| 205 | mock_client.triggers_types.retrieve.assert_called_once_with( |
| 206 | slug="GITHUB_COMMIT_EVENT", |
| 207 | toolkit_versions=custom_versions, |
| 208 | ) |
| 209 | assert result == mock_trigger_type |
| 210 | |
| 211 | def test_list_active_without_filters( |
| 212 | self, triggers, mock_client, mock_trigger_instances |
| 213 | ): |
| 214 | """Test list_active without any filters.""" |
| 215 | mock_client.trigger_instances.list_active.return_value = mock_trigger_instances |
| 216 | |
| 217 | result = triggers.list_active() |
| 218 | |
| 219 | mock_client.trigger_instances.list_active.assert_called_once() |
| 220 | assert result == mock_trigger_instances |
| 221 | |
| 222 | def test_list_active_with_filters( |
| 223 | self, triggers, mock_client, mock_trigger_instances |
| 224 | ): |
| 225 | """Test list_active with filters.""" |
| 226 | mock_client.trigger_instances.list_active.return_value = mock_trigger_instances |
| 227 | |
| 228 | result = triggers.list_active( |
| 229 | trigger_ids=["trigger-1"], |
| 230 | trigger_names=["GITHUB_COMMIT_EVENT"], |
| 231 | auth_config_ids=["auth-123"], |
| 232 | connected_account_ids=["conn-123"], |
| 233 | show_disabled=False, |
| 234 | limit=10, |
| 235 | cursor="cursor-abc", |
| 236 | ) |
| 237 | |
| 238 | mock_client.trigger_instances.list_active.assert_called_once() |
| 239 | call_kwargs = mock_client.trigger_instances.list_active.call_args.kwargs |
| 240 | assert call_kwargs["query_trigger_ids_1"] == ["trigger-1"] |
| 241 | assert call_kwargs["query_trigger_names_1"] == ["GITHUB_COMMIT_EVENT"] |
| 242 | assert call_kwargs["query_auth_config_ids_1"] == ["auth-123"] |
| 243 | assert call_kwargs["query_connected_account_ids_1"] == ["conn-123"] |
| 244 | assert call_kwargs["query_show_disabled_1"] is False |
| 245 | assert call_kwargs["limit"] == 10 |
| 246 | assert call_kwargs["cursor"] == "cursor-abc" |
| 247 | assert result == mock_trigger_instances |
| 248 | |
| 249 | def test_list_trigger_types_without_filters(self, triggers, mock_client): |
| 250 | """Test list trigger types without filters.""" |
| 251 | mock_response = Mock() |
| 252 | mock_client.triggers_types.list.return_value = mock_response |
| 253 | |
| 254 | result = triggers.list() |
| 255 | |
| 256 | mock_client.triggers_types.list.assert_called_once() |
| 257 | assert result == mock_response |
| 258 | |
| 259 | def test_list_trigger_types_with_filters(self, triggers_with_versions, mock_client): |
| 260 | """Test list trigger types with filters and custom versions.""" |
| 261 | mock_response = Mock() |
| 262 | mock_client.triggers_types.list.return_value = mock_response |
| 263 | custom_versions = {"github": "12082025_00", "slack": "10082025_01"} |
| 264 | |
| 265 | result = triggers_with_versions.list( |
| 266 | cursor="cursor-123", |
| 267 | limit=10, |
| 268 | toolkit_slugs=["github", "slack"], |
| 269 | ) |
| 270 | |
| 271 | mock_client.triggers_types.list.assert_called_once() |
| 272 | call_kwargs = mock_client.triggers_types.list.call_args.kwargs |
| 273 | assert call_kwargs["cursor"] == "cursor-123" |
| 274 | assert call_kwargs["limit"] == 10 |
| 275 | assert call_kwargs["toolkit_slugs"] == ["github", "slack"] |
| 276 | assert call_kwargs["toolkit_versions"] == custom_versions |
| 277 | assert result == mock_response |
| 278 | |
| 279 | def test_create_with_connected_account_id(self, triggers, mock_client): |
| 280 | """Test create trigger with connected_account_id.""" |
| 281 | mock_response = Mock() |
| 282 | mock_response.trigger_id = "trigger-123" |
| 283 | mock_client.trigger_instances.upsert.return_value = mock_response |
| 284 | |
| 285 | result = triggers.create( |
| 286 | slug="GITHUB_COMMIT_EVENT", |
| 287 | connected_account_id="conn-123", |
| 288 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 289 | ) |
| 290 | |
| 291 | # No extra lookup when an explicit connection is pinned. |
| 292 | mock_client.connected_accounts.list.assert_not_called() |
| 293 | mock_client.trigger_instances.upsert.assert_called_once() |
| 294 | call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs |
| 295 | assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT" |
| 296 | assert call_kwargs["connected_account_id"] == "conn-123" |
| 297 | assert call_kwargs["body_trigger_config_1"] == { |
| 298 | "webhook_url": "https://example.com/webhook" |
| 299 | } |
| 300 | assert call_kwargs["toolkit_versions"] is None |
| 301 | # No user_id supplied → omitted from the request (native kwarg, not extra_body). |
| 302 | assert call_kwargs["user_id"] is omit |
| 303 | assert result == mock_response |
| 304 | |
| 305 | def test_create_passes_type_and_polling_interval(self, triggers, mock_client): |
| 306 | """type and polling_interval reach the upsert; unset ones are omitted.""" |
| 307 | triggers.create( |
| 308 | slug="GMAIL_NEW_GMAIL_MESSAGE", |
| 309 | user_id="user-123", |
| 310 | type="poll", |
| 311 | polling_interval=15, |
| 312 | ) |
| 313 | triggers.create(slug="GMAIL_NEW_GMAIL_MESSAGE", user_id="user-123") |
| 314 | |
| 315 | with_fields, without_fields = ( |
| 316 | mock_client.trigger_instances.upsert.call_args_list |
| 317 | ) |
| 318 | assert with_fields.kwargs["type"] == "poll" |
| 319 | assert with_fields.kwargs["polling_interval"] == 15 |
| 320 | assert without_fields.kwargs["type"] is omit |
| 321 | assert without_fields.kwargs["polling_interval"] is omit |
| 322 | |
| 323 | def test_create_with_user_id(self, triggers, mock_client): |
| 324 | """Test create trigger with user_id only. |
| 325 | |
| 326 | The backend resolves the connection from ``user_id``, so the SDK passes |
| 327 | it straight through and no longer lists connected accounts. |
| 328 | """ |
| 329 | mock_response = Mock() |
| 330 | mock_response.trigger_id = "trigger-123" |
| 331 | mock_client.trigger_instances.upsert.return_value = mock_response |
| 332 | |
| 333 | result = triggers.create( |
| 334 | slug="GITHUB_COMMIT_EVENT", |
| 335 | user_id="user-123", |
| 336 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 337 | ) |
| 338 | |
| 339 | # The SDK no longer lists connected accounts to resolve the connection, |
| 340 | # but it still validates the slug up-front (parity with the TS SDK). |
| 341 | mock_client.connected_accounts.list.assert_not_called() |
| 342 | mock_client.triggers_types.retrieve.assert_called_once() |
| 343 | |
| 344 | mock_client.trigger_instances.upsert.assert_called_once() |
| 345 | call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs |
| 346 | assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT" |
| 347 | # No explicit connection pinned → omitted; user_id is sent as a native kwarg. |
| 348 | assert call_kwargs["connected_account_id"] is omit |
| 349 | assert call_kwargs["user_id"] == "user-123" |
| 350 | assert call_kwargs["body_trigger_config_1"] == { |
| 351 | "webhook_url": "https://example.com/webhook" |
| 352 | } |
| 353 | assert call_kwargs["toolkit_versions"] is None |
| 354 | assert result == mock_response |
| 355 | |
| 356 | def test_create_with_user_id_and_connected_account_id(self, triggers, mock_client): |
| 357 | """Test create trigger with both user_id and a pinned connected_account_id. |
| 358 | |
| 359 | When a connection is pinned and 2FA is enabled, the backend validates the |
| 360 | connection is owned by ``user_id``. Both values are forwarded natively |
| 361 | (no ``extra_body``). Mirrors the TS ``create`` test. |
| 362 | """ |
| 363 | mock_response = Mock() |
| 364 | mock_response.trigger_id = "trigger-123" |
| 365 | mock_client.trigger_instances.upsert.return_value = mock_response |
| 366 | |
| 367 | result = triggers.create( |
| 368 | slug="GITHUB_COMMIT_EVENT", |
| 369 | user_id="user-123", |
| 370 | connected_account_id="conn-123", |
| 371 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 372 | ) |
| 373 | |
| 374 | mock_client.connected_accounts.list.assert_not_called() |
| 375 | mock_client.trigger_instances.upsert.assert_called_once() |
| 376 | call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs |
| 377 | assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT" |
| 378 | assert call_kwargs["connected_account_id"] == "conn-123" |
| 379 | assert call_kwargs["user_id"] == "user-123" |
| 380 | assert call_kwargs["body_trigger_config_1"] == { |
| 381 | "webhook_url": "https://example.com/webhook" |
| 382 | } |
| 383 | assert result == mock_response |
| 384 | |
| 385 | def test_create_raises_trigger_type_not_found_for_unknown_slug( |
| 386 | self, triggers, mock_client |
| 387 | ): |
| 388 | """An unknown slug surfaces as TriggerTypeNotFound (parity with the TS SDK).""" |
| 389 | request = httpx.Request("GET", "https://backend.composio.dev") |
| 390 | response = httpx.Response(404, request=request) |
| 391 | mock_client.triggers_types.retrieve.side_effect = NotFoundError( |
| 392 | "not found", response=response, body=None |
| 393 | ) |
| 394 | |
| 395 | with pytest.raises(exceptions.TriggerTypeNotFound): |
| 396 | triggers.create(slug="UNKNOWN_TRIGGER", user_id="user-123") |
| 397 | |
| 398 | mock_client.trigger_instances.upsert.assert_not_called() |
| 399 | |
| 400 | def test_create_treats_blank_user_id_as_missing(self, triggers, mock_client): |
| 401 | """A blank user_id is rejected like a missing one, before any request.""" |
| 402 | with pytest.raises(exceptions.InvalidParams): |
| 403 | triggers.create(slug="GITHUB_COMMIT_EVENT", user_id=" ") |
| 404 | |
| 405 | mock_client.triggers_types.retrieve.assert_not_called() |
| 406 | mock_client.trigger_instances.upsert.assert_not_called() |
| 407 | |
| 408 | def test_create_with_custom_toolkit_versions( |
| 409 | self, triggers_with_versions, mock_client |
| 410 | ): |
| 411 | """Test create trigger with custom toolkit versions.""" |
| 412 | mock_response = Mock() |
| 413 | mock_response.trigger_id = "trigger-123" |
| 414 | mock_client.trigger_instances.upsert.return_value = mock_response |
| 415 | custom_versions = {"github": "12082025_00", "slack": "10082025_01"} |
| 416 | |
| 417 | result = triggers_with_versions.create( |
| 418 | slug="GITHUB_COMMIT_EVENT", |
| 419 | connected_account_id="conn-123", |
| 420 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 421 | ) |
| 422 | |
| 423 | mock_client.trigger_instances.upsert.assert_called_once() |
| 424 | call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs |
| 425 | assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT" |
| 426 | assert call_kwargs["connected_account_id"] == "conn-123" |
| 427 | assert call_kwargs["body_trigger_config_1"] == { |
| 428 | "webhook_url": "https://example.com/webhook" |
| 429 | } |
| 430 | assert call_kwargs["toolkit_versions"] == custom_versions |
| 431 | assert result == mock_response |
| 432 | |
| 433 | def test_create_without_user_id_or_connected_account_raises_error( |
| 434 | self, triggers, mock_client |
| 435 | ): |
| 436 | """Test create trigger without user_id or connected_account_id raises error.""" |
| 437 | with pytest.raises(exceptions.InvalidParams) as exc_info: |
| 438 | triggers.create( |
| 439 | slug="GITHUB_COMMIT_EVENT", |
| 440 | trigger_config={"webhook_url": "https://example.com/webhook"}, |
| 441 | ) |
| 442 | |
| 443 | assert "please provide valid `connected_account_id` or `user_id`" in str( |
| 444 | exc_info.value |
| 445 | ) |
| 446 | |
| 447 | def test_enable_trigger(self, triggers, mock_client): |
| 448 | """Test enable trigger.""" |
| 449 | mock_response = Mock() |
| 450 | mock_client.trigger_instances.manage.update.return_value = mock_response |
| 451 | |
| 452 | result = triggers.enable(trigger_id="trigger-123") |
| 453 | |
| 454 | mock_client.trigger_instances.manage.update.assert_called_once_with( |
| 455 | trigger_id="trigger-123", |
| 456 | status="enable", |
| 457 | ) |
| 458 | assert result == mock_response |
| 459 | |
| 460 | def test_disable_trigger(self, triggers, mock_client): |
| 461 | """Test disable trigger.""" |
| 462 | mock_response = Mock() |
| 463 | mock_client.trigger_instances.manage.update.return_value = mock_response |
| 464 | |
| 465 | result = triggers.disable(trigger_id="trigger-123") |
| 466 | |
| 467 | mock_client.trigger_instances.manage.update.assert_called_once_with( |
| 468 | trigger_id="trigger-123", |
| 469 | status="disable", |
| 470 | ) |
| 471 | assert result == mock_response |
| 472 | |
| 473 | def test_delete_trigger(self, triggers, mock_client): |
| 474 | """Test delete trigger.""" |
| 475 | mock_response = Mock() |
| 476 | mock_client.trigger_instances.manage.delete.return_value = mock_response |
| 477 | |
| 478 | result = triggers.delete(trigger_id="trigger-123") |
| 479 | |
| 480 | mock_client.trigger_instances.manage.delete.assert_called_once_with( |
| 481 | trigger_id="trigger-123" |
| 482 | ) |
| 483 | assert result == mock_response |
| 484 | |
| 485 | def test_list_enum(self, triggers, mock_client): |
| 486 | """Test list_enum method.""" |
| 487 | mock_response = Mock() |
| 488 | mock_response.enum = ["GITHUB_COMMIT_EVENT", "SLACK_MESSAGE_RECEIVED"] |
| 489 | mock_client.triggers_types.retrieve_enum.return_value = mock_response |
| 490 | |
| 491 | result = triggers.list_enum() |
| 492 | |
| 493 | mock_client.triggers_types.retrieve_enum.assert_called_once() |
| 494 | assert result == mock_response |
| 495 | |
| 496 | def test_subscribe(self, triggers, mock_client): |
| 497 | """Test subscribe method.""" |
| 498 | with patch( |
| 499 | "composio.core.models.triggers._SubcriptionBuilder" |
| 500 | ) as mock_builder_class: |
| 501 | mock_builder = Mock() |
| 502 | mock_subscription = Mock() |
| 503 | mock_builder.connect.return_value = mock_subscription |
| 504 | mock_builder_class.return_value = mock_builder |
| 505 | |
| 506 | result = triggers.subscribe(timeout=20.0) |
| 507 | |
| 508 | mock_builder_class.assert_called_once_with(client=mock_client) |
| 509 | mock_builder.connect.assert_called_once_with( |
| 510 | timeout=20.0, on_subscription_error=None |
| 511 | ) |
| 512 | assert result == mock_subscription |
| 513 | |
| 514 | def test_subscribe_with_default_timeout(self, triggers, mock_client): |
| 515 | """Test subscribe method with default timeout.""" |
| 516 | with patch( |
| 517 | "composio.core.models.triggers._SubcriptionBuilder" |
| 518 | ) as mock_builder_class: |
| 519 | mock_builder = Mock() |
| 520 | mock_subscription = Mock() |
| 521 | mock_builder.connect.return_value = mock_subscription |
| 522 | mock_builder_class.return_value = mock_builder |
| 523 | |
| 524 | result = triggers.subscribe() |
| 525 | |
| 526 | mock_builder.connect.assert_called_once_with( |
| 527 | timeout=15.0, on_subscription_error=None |
| 528 | ) |
| 529 | assert result == mock_subscription |
| 530 | |
| 531 | def test_subscribe_passes_subscription_error_callback(self, triggers, mock_client): |
| 532 | """The optional on_subscription_error callback reaches the builder.""" |
| 533 | with patch( |
| 534 | "composio.core.models.triggers._SubcriptionBuilder" |
| 535 | ) as mock_builder_class: |
| 536 | mock_builder = Mock() |
| 537 | mock_subscription = Mock() |
| 538 | mock_builder.connect.return_value = mock_subscription |
| 539 | mock_builder_class.return_value = mock_builder |
| 540 | on_subscription_error = Mock() |
| 541 | |
| 542 | result = triggers.subscribe( |
| 543 | timeout=5.0, on_subscription_error=on_subscription_error |
| 544 | ) |
| 545 | |
| 546 | mock_builder.connect.assert_called_once_with( |
| 547 | timeout=5.0, on_subscription_error=on_subscription_error |
| 548 | ) |
| 549 | assert result == mock_subscription |
| 550 | |
| 551 | |
| 552 | class TestVerifyWebhook: |
| 553 | """Test cases for verify_webhook method.""" |
| 554 | |
| 555 | @pytest.fixture |
| 556 | def mock_client(self): |
| 557 | """Create a mock HTTP client.""" |
| 558 | client = Mock() |
| 559 | client.triggers_types = Mock() |
| 560 | client.trigger_instances = Mock() |
| 561 | client.trigger_instances.manage = Mock() |
| 562 | client.connected_accounts = Mock() |
| 563 | return client |
| 564 | |
| 565 | @pytest.fixture |
| 566 | def triggers(self, mock_client): |
| 567 | """Create a Triggers instance.""" |
| 568 | return Triggers(client=mock_client) |
| 569 | |
| 570 | @pytest.fixture |
| 571 | def test_secret(self): |
| 572 | """Test webhook secret.""" |
| 573 | return "test-webhook-secret-12345" |
| 574 | |
| 575 | @pytest.fixture |
| 576 | def test_webhook_id(self): |
| 577 | """Test webhook ID.""" |
| 578 | return "msg_test123" |
| 579 | |
| 580 | @pytest.fixture |
| 581 | def test_timestamp(self): |
| 582 | """Test webhook timestamp (current time in Unix seconds).""" |
| 583 | return str(int(time.time())) |
| 584 | |
| 585 | @pytest.fixture |
| 586 | def mock_v1_payload(self): |
| 587 | """Create mock V1 webhook payload.""" |
| 588 | return { |
| 589 | "trigger_name": "GITHUB_PUSH_EVENT", |
| 590 | "connection_id": "conn-123", |
| 591 | "trigger_id": "trigger-123", |
| 592 | "payload": {"action": "push", "repository": "test-repo"}, |
| 593 | "log_id": "log-123", |
| 594 | } |
| 595 | |
| 596 | @pytest.fixture |
| 597 | def mock_v2_payload(self): |
| 598 | """Create mock V2 webhook payload.""" |
| 599 | return { |
| 600 | "type": "github_push_event", |
| 601 | "timestamp": datetime.now(timezone.utc).isoformat(), |
| 602 | "log_id": "log-123", |
| 603 | "data": { |
| 604 | "connection_id": "conn-123", |
| 605 | "connection_nano_id": "conn-nano-123", |
| 606 | "trigger_nano_id": "trigger-nano-123", |
| 607 | "trigger_id": "trigger-123", |
| 608 | "user_id": "user-456", |
| 609 | "action": "push", |
| 610 | "repository": "test-repo", |
| 611 | }, |
| 612 | } |
| 613 | |
| 614 | @pytest.fixture |
| 615 | def mock_v3_payload(self): |
| 616 | """Create mock V3 webhook payload.""" |
| 617 | return { |
| 618 | "id": "evt-123", |
| 619 | "timestamp": datetime.now(timezone.utc).isoformat(), |
| 620 | "type": "composio.trigger.message", |
| 621 | "metadata": { |
| 622 | "log_id": "log-123", |
| 623 | "trigger_slug": "GITHUB_PUSH_EVENT", |
| 624 | "trigger_id": "trigger-nano-123", |
| 625 | "connected_account_id": "conn-nano-123", |
| 626 | "auth_config_id": "auth-nano-123", |
| 627 | "user_id": "user-456", |
| 628 | }, |
| 629 | "data": {"action": "push", "repository": "test-repo"}, |
| 630 | } |
| 631 | |
| 632 | def create_signature( |
| 633 | self, webhook_id: str, timestamp: str, payload: str, secret: str |
| 634 | ) -> str: |
| 635 | """Helper to create a valid v1,base64 signature.""" |
| 636 | to_sign = f"{webhook_id}.{timestamp}.{payload}" |
| 637 | signature_bytes = hmac.new( |
| 638 | key=secret.encode("utf-8"), |
| 639 | msg=to_sign.encode("utf-8"), |
| 640 | digestmod=hashlib.sha256, |
| 641 | ).digest() |
| 642 | return f"v1,{base64.b64encode(signature_bytes).decode('utf-8')}" |
| 643 | |
| 644 | # Successful verification tests with V3 payload |
| 645 | |
| 646 | def test_verify_webhook_v3_payload( |
| 647 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 648 | ): |
| 649 | """Test successful V3 webhook verification.""" |
| 650 | payload = json.dumps(mock_v3_payload) |
| 651 | signature = self.create_signature( |
| 652 | test_webhook_id, test_timestamp, payload, test_secret |
| 653 | ) |
| 654 | |
| 655 | result = triggers.verify_webhook( |
| 656 | id=test_webhook_id, |
| 657 | payload=payload, |
| 658 | signature=signature, |
| 659 | timestamp=test_timestamp, |
| 660 | secret=test_secret, |
| 661 | ) |
| 662 | |
| 663 | assert result["version"] == WebhookVersion.V3 |
| 664 | assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT" |
| 665 | assert result["payload"]["user_id"] == "user-456" |
| 666 | assert result["raw_payload"] == mock_v3_payload |
| 667 | |
| 668 | def test_verify_webhook_v3_normalizes_payload( |
| 669 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 670 | ): |
| 671 | """Test V3 payload normalization.""" |
| 672 | payload = json.dumps(mock_v3_payload) |
| 673 | signature = self.create_signature( |
| 674 | test_webhook_id, test_timestamp, payload, test_secret |
| 675 | ) |
| 676 | |
| 677 | result = triggers.verify_webhook( |
| 678 | id=test_webhook_id, |
| 679 | payload=payload, |
| 680 | signature=signature, |
| 681 | timestamp=test_timestamp, |
| 682 | secret=test_secret, |
| 683 | ) |
| 684 | |
| 685 | assert ( |
| 686 | result["payload"]["metadata"]["connected_account"]["id"] == "conn-nano-123" |
| 687 | ) |
| 688 | assert ( |
| 689 | result["payload"]["metadata"]["connected_account"]["auth_config_id"] |
| 690 | == "auth-nano-123" |
| 691 | ) |
| 692 | assert ( |
| 693 | result["payload"]["metadata"]["connected_account"]["user_id"] == "user-456" |
| 694 | ) |
| 695 | |
| 696 | def test_verify_webhook_v3_non_trigger_event_type( |
| 697 | self, triggers, test_secret, test_webhook_id, test_timestamp |
| 698 | ): |
| 699 | """Test V3 payload with non-trigger event type is detected as V3, not V2. |
| 700 | |
| 701 | Uses realistic connection metadata (project_id, org_id) instead of |
| 702 | fabricated trigger metadata, verifying V3 detection works for events |
| 703 | with different metadata shapes. |
| 704 | """ |
| 705 | payload_dict = { |
| 706 | "id": "msg_abc123", |
| 707 | "timestamp": "2024-01-01T00:00:00Z", |
| 708 | "type": "composio.connected_account.expired", |
| 709 | "metadata": { |
| 710 | "project_id": "pr_koucdrMIwRsf", |
| 711 | "org_id": "4a4ded8f-d3ae-4dea-a229-c30234298b05", |
| 712 | }, |
| 713 | "data": { |
| 714 | "toolkit": {"slug": "gmail"}, |
| 715 | "id": "ca__IvSeEzEBjVt", |
| 716 | "user_id": "test-user", |
| 717 | "status": "EXPIRED", |
| 718 | }, |
| 719 | } |
| 720 | payload = json.dumps(payload_dict) |
| 721 | signature = self.create_signature( |
| 722 | test_webhook_id, test_timestamp, payload, test_secret |
| 723 | ) |
| 724 | |
| 725 | result = triggers.verify_webhook( |
| 726 | id=test_webhook_id, |
| 727 | payload=payload, |
| 728 | signature=signature, |
| 729 | timestamp=test_timestamp, |
| 730 | secret=test_secret, |
| 731 | ) |
| 732 | |
| 733 | # Should be detected as V3, not fall back to V2 |
| 734 | assert result["version"] == WebhookVersion.V3 |
| 735 | assert result["raw_payload"] == payload_dict |
| 736 | |
| 737 | # Successful verification with V2 payload |
| 738 | |
| 739 | def test_verify_webhook_v2_payload( |
| 740 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v2_payload |
| 741 | ): |
| 742 | """Test successful V2 webhook verification.""" |
| 743 | payload = json.dumps(mock_v2_payload) |
| 744 | signature = self.create_signature( |
| 745 | test_webhook_id, test_timestamp, payload, test_secret |
| 746 | ) |
| 747 | |
| 748 | result = triggers.verify_webhook( |
| 749 | id=test_webhook_id, |
| 750 | payload=payload, |
| 751 | signature=signature, |
| 752 | timestamp=test_timestamp, |
| 753 | secret=test_secret, |
| 754 | ) |
| 755 | |
| 756 | assert result["version"] == WebhookVersion.V2 |
| 757 | assert result["payload"]["user_id"] == "user-456" |
| 758 | |
| 759 | # Successful verification with V1 payload |
| 760 | |
| 761 | def test_verify_webhook_v1_payload( |
| 762 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v1_payload |
| 763 | ): |
| 764 | """Test successful V1 webhook verification.""" |
| 765 | payload = json.dumps(mock_v1_payload) |
| 766 | signature = self.create_signature( |
| 767 | test_webhook_id, test_timestamp, payload, test_secret |
| 768 | ) |
| 769 | |
| 770 | result = triggers.verify_webhook( |
| 771 | id=test_webhook_id, |
| 772 | payload=payload, |
| 773 | signature=signature, |
| 774 | timestamp=test_timestamp, |
| 775 | secret=test_secret, |
| 776 | ) |
| 777 | |
| 778 | assert result["version"] == WebhookVersion.V1 |
| 779 | assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT" |
| 780 | assert result["payload"]["id"] == "trigger-123" |
| 781 | |
| 782 | # Tolerance tests |
| 783 | |
| 784 | def test_verify_webhook_with_tolerance_zero( |
| 785 | self, triggers, test_secret, test_webhook_id, mock_v3_payload |
| 786 | ): |
| 787 | """Test webhook verification with tolerance set to 0 (skip timestamp validation).""" |
| 788 | # Use an old timestamp (1 hour ago) |
| 789 | old_timestamp = str(int(time.time()) - 3600) |
| 790 | payload = json.dumps(mock_v3_payload) |
| 791 | signature = self.create_signature( |
| 792 | test_webhook_id, old_timestamp, payload, test_secret |
| 793 | ) |
| 794 | |
| 795 | result = triggers.verify_webhook( |
| 796 | id=test_webhook_id, |
| 797 | payload=payload, |
| 798 | signature=signature, |
| 799 | timestamp=old_timestamp, |
| 800 | secret=test_secret, |
| 801 | tolerance=0, |
| 802 | ) |
| 803 | |
| 804 | assert result["version"] == WebhookVersion.V3 |
| 805 | |
| 806 | def test_verify_webhook_with_custom_tolerance( |
| 807 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 808 | ): |
| 809 | """Test webhook verification with custom tolerance.""" |
| 810 | payload = json.dumps(mock_v3_payload) |
| 811 | signature = self.create_signature( |
| 812 | test_webhook_id, test_timestamp, payload, test_secret |
| 813 | ) |
| 814 | |
| 815 | result = triggers.verify_webhook( |
| 816 | id=test_webhook_id, |
| 817 | payload=payload, |
| 818 | signature=signature, |
| 819 | timestamp=test_timestamp, |
| 820 | secret=test_secret, |
| 821 | tolerance=600, # 10 minutes |
| 822 | ) |
| 823 | |
| 824 | assert result is not None |
| 825 | |
| 826 | # Signature verification error tests |
| 827 | |
| 828 | def test_verify_webhook_empty_payload_raises_error( |
| 829 | self, triggers, test_secret, test_webhook_id, test_timestamp |
| 830 | ): |
| 831 | """Test that empty payload raises WebhookSignatureVerificationError.""" |
| 832 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 833 | triggers.verify_webhook( |
| 834 | id=test_webhook_id, |
| 835 | payload="", |
| 836 | signature="v1,somesignature", |
| 837 | timestamp=test_timestamp, |
| 838 | secret=test_secret, |
| 839 | ) |
| 840 | |
| 841 | assert "No webhook payload was provided" in str(exc_info.value) |
| 842 | |
| 843 | def test_verify_webhook_empty_signature_raises_error( |
| 844 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 845 | ): |
| 846 | """Test that empty signature raises WebhookSignatureVerificationError.""" |
| 847 | payload = json.dumps(mock_v3_payload) |
| 848 | |
| 849 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 850 | triggers.verify_webhook( |
| 851 | id=test_webhook_id, |
| 852 | payload=payload, |
| 853 | signature="", |
| 854 | timestamp=test_timestamp, |
| 855 | secret=test_secret, |
| 856 | ) |
| 857 | |
| 858 | assert "No signature header value was provided" in str(exc_info.value) |
| 859 | |
| 860 | def test_verify_webhook_empty_secret_raises_error( |
| 861 | self, triggers, test_webhook_id, test_timestamp, mock_v3_payload |
| 862 | ): |
| 863 | """Test that empty secret raises WebhookSignatureVerificationError.""" |
| 864 | payload = json.dumps(mock_v3_payload) |
| 865 | |
| 866 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 867 | triggers.verify_webhook( |
| 868 | id=test_webhook_id, |
| 869 | payload=payload, |
| 870 | signature="v1,somesignature", |
| 871 | timestamp=test_timestamp, |
| 872 | secret="", |
| 873 | ) |
| 874 | |
| 875 | assert "No webhook secret was provided" in str(exc_info.value) |
| 876 | |
| 877 | def test_verify_webhook_empty_webhook_id_raises_error( |
| 878 | self, triggers, test_secret, test_timestamp, mock_v3_payload |
| 879 | ): |
| 880 | """Test that empty webhook ID raises WebhookSignatureVerificationError.""" |
| 881 | payload = json.dumps(mock_v3_payload) |
| 882 | |
| 883 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 884 | triggers.verify_webhook( |
| 885 | id="", |
| 886 | payload=payload, |
| 887 | signature="v1,somesignature", |
| 888 | timestamp=test_timestamp, |
| 889 | secret=test_secret, |
| 890 | ) |
| 891 | |
| 892 | assert "No webhook ID was provided" in str(exc_info.value) |
| 893 | |
| 894 | def test_verify_webhook_empty_timestamp_raises_error( |
| 895 | self, triggers, test_secret, test_webhook_id, mock_v3_payload |
| 896 | ): |
| 897 | """Test that empty timestamp raises WebhookPayloadError.""" |
| 898 | payload = json.dumps(mock_v3_payload) |
| 899 | |
| 900 | with pytest.raises(exceptions.WebhookPayloadError) as exc_info: |
| 901 | triggers.verify_webhook( |
| 902 | id=test_webhook_id, |
| 903 | payload=payload, |
| 904 | signature="v1,somesignature", |
| 905 | timestamp="", |
| 906 | secret=test_secret, |
| 907 | ) |
| 908 | |
| 909 | assert "Invalid webhook timestamp" in str(exc_info.value) |
| 910 | |
| 911 | def test_verify_webhook_invalid_signature_format_raises_error( |
| 912 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 913 | ): |
| 914 | """Test that signature without v1 prefix raises error.""" |
| 915 | payload = json.dumps(mock_v3_payload) |
| 916 | |
| 917 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 918 | triggers.verify_webhook( |
| 919 | id=test_webhook_id, |
| 920 | payload=payload, |
| 921 | signature="invalid-signature-no-prefix", |
| 922 | timestamp=test_timestamp, |
| 923 | secret=test_secret, |
| 924 | ) |
| 925 | |
| 926 | assert "No valid v1 signature found" in str(exc_info.value) |
| 927 | |
| 928 | def test_verify_webhook_invalid_signature_raises_error( |
| 929 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 930 | ): |
| 931 | """Test that invalid signature raises WebhookSignatureVerificationError.""" |
| 932 | payload = json.dumps(mock_v3_payload) |
| 933 | |
| 934 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 935 | triggers.verify_webhook( |
| 936 | id=test_webhook_id, |
| 937 | payload=payload, |
| 938 | signature="v1,invalidbase64signature==", |
| 939 | timestamp=test_timestamp, |
| 940 | secret=test_secret, |
| 941 | ) |
| 942 | |
| 943 | assert "The signature provided is invalid" in str(exc_info.value) |
| 944 | |
| 945 | def test_verify_webhook_wrong_secret_raises_error( |
| 946 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 947 | ): |
| 948 | """Test that signature created with different secret raises error.""" |
| 949 | payload = json.dumps(mock_v3_payload) |
| 950 | signature = self.create_signature( |
| 951 | test_webhook_id, test_timestamp, payload, "different-secret" |
| 952 | ) |
| 953 | |
| 954 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 955 | triggers.verify_webhook( |
| 956 | id=test_webhook_id, |
| 957 | payload=payload, |
| 958 | signature=signature, |
| 959 | timestamp=test_timestamp, |
| 960 | secret=test_secret, |
| 961 | ) |
| 962 | |
| 963 | assert "The signature provided is invalid" in str(exc_info.value) |
| 964 | |
| 965 | def test_verify_webhook_modified_payload_raises_error( |
| 966 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 967 | ): |
| 968 | """Test that modified payload after signing raises error.""" |
| 969 | original_payload = json.dumps(mock_v3_payload) |
| 970 | signature = self.create_signature( |
| 971 | test_webhook_id, test_timestamp, original_payload, test_secret |
| 972 | ) |
| 973 | |
| 974 | # Modify the payload |
| 975 | mock_v3_payload["data"] = {"modified": True} |
| 976 | modified_payload = json.dumps(mock_v3_payload) |
| 977 | |
| 978 | with pytest.raises(exceptions.WebhookSignatureVerificationError): |
| 979 | triggers.verify_webhook( |
| 980 | id=test_webhook_id, |
| 981 | payload=modified_payload, |
| 982 | signature=signature, |
| 983 | timestamp=test_timestamp, |
| 984 | secret=test_secret, |
| 985 | ) |
| 986 | |
| 987 | # Payload parsing error tests |
| 988 | |
| 989 | def test_verify_webhook_invalid_json_raises_error( |
| 990 | self, triggers, test_secret, test_webhook_id, test_timestamp |
| 991 | ): |
| 992 | """Test that invalid JSON payload raises WebhookPayloadError.""" |
| 993 | invalid_json = "not-valid-json{" |
| 994 | signature = self.create_signature( |
| 995 | test_webhook_id, test_timestamp, invalid_json, test_secret |
| 996 | ) |
| 997 | |
| 998 | with pytest.raises(exceptions.WebhookPayloadError) as exc_info: |
| 999 | triggers.verify_webhook( |
| 1000 | id=test_webhook_id, |
| 1001 | payload=invalid_json, |
| 1002 | signature=signature, |
| 1003 | timestamp=test_timestamp, |
| 1004 | secret=test_secret, |
| 1005 | ) |
| 1006 | |
| 1007 | assert "Failed to parse webhook payload as JSON" in str(exc_info.value) |
| 1008 | |
| 1009 | def test_verify_webhook_unrecognized_payload_raises_error( |
| 1010 | self, triggers, test_secret, test_webhook_id, test_timestamp |
| 1011 | ): |
| 1012 | """Test that unrecognized payload format raises WebhookPayloadError.""" |
| 1013 | unknown_payload = json.dumps({"unknown": "format"}) |
| 1014 | signature = self.create_signature( |
| 1015 | test_webhook_id, test_timestamp, unknown_payload, test_secret |
| 1016 | ) |
| 1017 | |
| 1018 | with pytest.raises(exceptions.WebhookPayloadError) as exc_info: |
| 1019 | triggers.verify_webhook( |
| 1020 | id=test_webhook_id, |
| 1021 | payload=unknown_payload, |
| 1022 | signature=signature, |
| 1023 | timestamp=test_timestamp, |
| 1024 | secret=test_secret, |
| 1025 | ) |
| 1026 | |
| 1027 | assert "does not match any known version" in str(exc_info.value) |
| 1028 | |
| 1029 | def test_verify_webhook_v3_missing_data_field_raises_error( |
| 1030 | self, triggers, test_secret, test_webhook_id, test_timestamp |
| 1031 | ): |
| 1032 | """Test that V3-like payload missing 'data' field raises WebhookPayloadError. |
| 1033 | |
| 1034 | This tests the fix for a potential KeyError crash when a malformed payload |
| 1035 | has valid V3 markers (type, id, metadata) but is missing the required 'data' field. |
| 1036 | """ |
| 1037 | # Payload with V3 markers but missing 'data' field |
| 1038 | v3_like_payload_missing_data = { |
| 1039 | "id": "evt-123", |
| 1040 | "timestamp": datetime.now(timezone.utc).isoformat(), |
| 1041 | "type": "composio.trigger.message", |
| 1042 | "metadata": { |
| 1043 | "log_id": "log-123", |
| 1044 | "trigger_slug": "GITHUB_PUSH_EVENT", |
| 1045 | "trigger_id": "trigger-nano-123", |
| 1046 | "connected_account_id": "conn-nano-123", |
| 1047 | "auth_config_id": "auth-nano-123", |
| 1048 | "user_id": "user-456", |
| 1049 | }, |
| 1050 | # Note: 'data' field is intentionally missing |
| 1051 | } |
| 1052 | payload = json.dumps(v3_like_payload_missing_data) |
| 1053 | signature = self.create_signature( |
| 1054 | test_webhook_id, test_timestamp, payload, test_secret |
| 1055 | ) |
| 1056 | |
| 1057 | with pytest.raises(exceptions.WebhookPayloadError) as exc_info: |
| 1058 | triggers.verify_webhook( |
| 1059 | id=test_webhook_id, |
| 1060 | payload=payload, |
| 1061 | signature=signature, |
| 1062 | timestamp=test_timestamp, |
| 1063 | secret=test_secret, |
| 1064 | ) |
| 1065 | |
| 1066 | # Should be rejected as unrecognized format, not crash with KeyError |
| 1067 | assert "does not match any known version" in str(exc_info.value) |
| 1068 | |
| 1069 | # Timestamp validation tests |
| 1070 | |
| 1071 | def test_verify_webhook_timestamp_within_tolerance( |
| 1072 | self, triggers, test_secret, test_webhook_id, mock_v3_payload |
| 1073 | ): |
| 1074 | """Test that timestamp within tolerance passes validation.""" |
| 1075 | recent_timestamp = str(int(time.time())) |
| 1076 | payload = json.dumps(mock_v3_payload) |
| 1077 | signature = self.create_signature( |
| 1078 | test_webhook_id, recent_timestamp, payload, test_secret |
| 1079 | ) |
| 1080 | |
| 1081 | result = triggers.verify_webhook( |
| 1082 | id=test_webhook_id, |
| 1083 | payload=payload, |
| 1084 | signature=signature, |
| 1085 | timestamp=recent_timestamp, |
| 1086 | secret=test_secret, |
| 1087 | tolerance=300, |
| 1088 | ) |
| 1089 | |
| 1090 | assert result is not None |
| 1091 | |
| 1092 | def test_verify_webhook_timestamp_outside_tolerance_raises_error( |
| 1093 | self, triggers, test_secret, test_webhook_id, mock_v3_payload |
| 1094 | ): |
| 1095 | """Test that timestamp outside tolerance raises error.""" |
| 1096 | # 10 minutes ago |
| 1097 | old_timestamp = str(int(time.time()) - 600) |
| 1098 | payload = json.dumps(mock_v3_payload) |
| 1099 | signature = self.create_signature( |
| 1100 | test_webhook_id, old_timestamp, payload, test_secret |
| 1101 | ) |
| 1102 | |
| 1103 | with pytest.raises(exceptions.WebhookSignatureVerificationError) as exc_info: |
| 1104 | triggers.verify_webhook( |
| 1105 | id=test_webhook_id, |
| 1106 | payload=payload, |
| 1107 | signature=signature, |
| 1108 | timestamp=old_timestamp, |
| 1109 | secret=test_secret, |
| 1110 | tolerance=300, # 5 minutes |
| 1111 | ) |
| 1112 | |
| 1113 | assert "outside the allowed tolerance" in str(exc_info.value) |
| 1114 | |
| 1115 | def test_verify_webhook_invalid_timestamp_format_raises_error( |
| 1116 | self, triggers, test_secret, test_webhook_id, mock_v3_payload |
| 1117 | ): |
| 1118 | """Test that invalid timestamp format raises WebhookPayloadError.""" |
| 1119 | invalid_timestamp = "not-a-timestamp" |
| 1120 | payload = json.dumps(mock_v3_payload) |
| 1121 | signature = self.create_signature( |
| 1122 | test_webhook_id, invalid_timestamp, payload, test_secret |
| 1123 | ) |
| 1124 | |
| 1125 | with pytest.raises(exceptions.WebhookPayloadError) as exc_info: |
| 1126 | triggers.verify_webhook( |
| 1127 | id=test_webhook_id, |
| 1128 | payload=payload, |
| 1129 | signature=signature, |
| 1130 | timestamp=invalid_timestamp, |
| 1131 | secret=test_secret, |
| 1132 | tolerance=300, |
| 1133 | ) |
| 1134 | |
| 1135 | assert "Invalid webhook timestamp" in str(exc_info.value) |
| 1136 | |
| 1137 | # Security tests |
| 1138 | |
| 1139 | def test_verify_webhook_uses_timing_safe_comparison( |
| 1140 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 1141 | ): |
| 1142 | """Test that signature comparison is timing-safe.""" |
| 1143 | payload = json.dumps(mock_v3_payload) |
| 1144 | valid_signature = self.create_signature( |
| 1145 | test_webhook_id, test_timestamp, payload, test_secret |
| 1146 | ) |
| 1147 | |
| 1148 | # Valid signature should work |
| 1149 | result = triggers.verify_webhook( |
| 1150 | id=test_webhook_id, |
| 1151 | payload=payload, |
| 1152 | signature=valid_signature, |
| 1153 | timestamp=test_timestamp, |
| 1154 | secret=test_secret, |
| 1155 | ) |
| 1156 | assert result is not None |
| 1157 | |
| 1158 | # Invalid signature with same format should fail |
| 1159 | invalid_signature = "v1," + "a" * 44 # base64 SHA256 is 44 chars |
| 1160 | with pytest.raises(exceptions.WebhookSignatureVerificationError): |
| 1161 | triggers.verify_webhook( |
| 1162 | id=test_webhook_id, |
| 1163 | payload=payload, |
| 1164 | signature=invalid_signature, |
| 1165 | timestamp=test_timestamp, |
| 1166 | secret=test_secret, |
| 1167 | ) |
| 1168 | |
| 1169 | def test_verify_webhook_handles_unicode_payload( |
| 1170 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 1171 | ): |
| 1172 | """Test that unicode in payload is handled correctly.""" |
| 1173 | mock_v3_payload["data"] = {"message": "你好世界 🌍 مرحبا"} |
| 1174 | payload = json.dumps(mock_v3_payload, ensure_ascii=False) |
| 1175 | signature = self.create_signature( |
| 1176 | test_webhook_id, test_timestamp, payload, test_secret |
| 1177 | ) |
| 1178 | |
| 1179 | result = triggers.verify_webhook( |
| 1180 | id=test_webhook_id, |
| 1181 | payload=payload, |
| 1182 | signature=signature, |
| 1183 | timestamp=test_timestamp, |
| 1184 | secret=test_secret, |
| 1185 | ) |
| 1186 | |
| 1187 | assert result["payload"]["payload"]["message"] == "你好世界 🌍 مرحبا" |
| 1188 | |
| 1189 | def test_verify_webhook_handles_special_characters_in_secret( |
| 1190 | self, triggers, test_webhook_id, test_timestamp, mock_v3_payload |
| 1191 | ): |
| 1192 | """Test that special characters in secret are handled correctly.""" |
| 1193 | special_secret = "secret!@#$%^&*()_+-=[]{}|;:,.<>?" |
| 1194 | payload = json.dumps(mock_v3_payload) |
| 1195 | signature = self.create_signature( |
| 1196 | test_webhook_id, test_timestamp, payload, special_secret |
| 1197 | ) |
| 1198 | |
| 1199 | result = triggers.verify_webhook( |
| 1200 | id=test_webhook_id, |
| 1201 | payload=payload, |
| 1202 | signature=signature, |
| 1203 | timestamp=test_timestamp, |
| 1204 | secret=special_secret, |
| 1205 | ) |
| 1206 | |
| 1207 | assert result is not None |
| 1208 | |
| 1209 | def test_verify_webhook_supports_multiple_signatures( |
| 1210 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 1211 | ): |
| 1212 | """Test that multiple signatures in header are supported.""" |
| 1213 | payload = json.dumps(mock_v3_payload) |
| 1214 | valid_signature = self.create_signature( |
| 1215 | test_webhook_id, test_timestamp, payload, test_secret |
| 1216 | ) |
| 1217 | # Multiple signatures space-separated |
| 1218 | multiple_signatures = f"v1,invalidsig== {valid_signature}" |
| 1219 | |
| 1220 | result = triggers.verify_webhook( |
| 1221 | id=test_webhook_id, |
| 1222 | payload=payload, |
| 1223 | signature=multiple_signatures, |
| 1224 | timestamp=test_timestamp, |
| 1225 | secret=test_secret, |
| 1226 | ) |
| 1227 | |
| 1228 | assert result is not None |
| 1229 | |
| 1230 | # Error class tests |
| 1231 | |
| 1232 | def test_webhook_signature_verification_error_is_trigger_error(self): |
| 1233 | """Test that WebhookSignatureVerificationError inherits from TriggerError.""" |
| 1234 | error = exceptions.WebhookSignatureVerificationError("test") |
| 1235 | assert isinstance(error, exceptions.TriggerError) |
| 1236 | |
| 1237 | def test_webhook_payload_error_is_trigger_error(self): |
| 1238 | """Test that WebhookPayloadError inherits from TriggerError.""" |
| 1239 | error = exceptions.WebhookPayloadError("test") |
| 1240 | assert isinstance(error, exceptions.TriggerError) |
| 1241 | |
| 1242 | |
| 1243 | class TestParseWebhook: |
| 1244 | """Test cases for the parse() webhook helper.""" |
| 1245 | |
| 1246 | @pytest.fixture |
| 1247 | def mock_client(self): |
| 1248 | """Create a mock HTTP client.""" |
| 1249 | client = Mock() |
| 1250 | client.triggers_types = Mock() |
| 1251 | client.trigger_instances = Mock() |
| 1252 | client.trigger_instances.manage = Mock() |
| 1253 | client.connected_accounts = Mock() |
| 1254 | return client |
| 1255 | |
| 1256 | @pytest.fixture |
| 1257 | def triggers(self, mock_client): |
| 1258 | """Create a Triggers instance.""" |
| 1259 | return Triggers(client=mock_client) |
| 1260 | |
| 1261 | @pytest.fixture |
| 1262 | def test_secret(self): |
| 1263 | """Test webhook secret.""" |
| 1264 | return "test-webhook-secret-12345" |
| 1265 | |
| 1266 | @pytest.fixture |
| 1267 | def test_webhook_id(self): |
| 1268 | """Test webhook ID.""" |
| 1269 | return "msg_test123" |
| 1270 | |
| 1271 | @pytest.fixture |
| 1272 | def test_timestamp(self): |
| 1273 | """Test webhook timestamp (current time in Unix seconds).""" |
| 1274 | return str(int(time.time())) |
| 1275 | |
| 1276 | @pytest.fixture |
| 1277 | def mock_v3_payload(self): |
| 1278 | """Create mock V3 webhook payload.""" |
| 1279 | return { |
| 1280 | "id": "evt-123", |
| 1281 | "timestamp": datetime.now(timezone.utc).isoformat(), |
| 1282 | "type": "composio.trigger.message", |
| 1283 | "metadata": { |
| 1284 | "log_id": "log-123", |
| 1285 | "trigger_slug": "GITHUB_PUSH_EVENT", |
| 1286 | "trigger_id": "trigger-nano-123", |
| 1287 | "connected_account_id": "conn-nano-123", |
| 1288 | "auth_config_id": "auth-nano-123", |
| 1289 | "user_id": "user-456", |
| 1290 | }, |
| 1291 | "data": {"action": "push", "repository": "test-repo"}, |
| 1292 | } |
| 1293 | |
| 1294 | def create_signature( |
| 1295 | self, webhook_id: str, timestamp: str, payload: str, secret: str |
| 1296 | ) -> str: |
| 1297 | """Helper to create a valid v1,base64 signature.""" |
| 1298 | to_sign = f"{webhook_id}.{timestamp}.{payload}" |
| 1299 | signature_bytes = hmac.new( |
| 1300 | key=secret.encode("utf-8"), |
| 1301 | msg=to_sign.encode("utf-8"), |
| 1302 | digestmod=hashlib.sha256, |
| 1303 | ).digest() |
| 1304 | return f"v1,{base64.b64encode(signature_bytes).decode('utf-8')}" |
| 1305 | |
| 1306 | def test_parse_with_request_object_and_verify( |
| 1307 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 1308 | ): |
| 1309 | """Parse and verify from a framework-style request object.""" |
| 1310 | payload = json.dumps(mock_v3_payload) |
| 1311 | signature = self.create_signature( |
| 1312 | test_webhook_id, test_timestamp, payload, test_secret |
| 1313 | ) |
| 1314 | |
| 1315 | request = Mock() |
| 1316 | request.body = payload.encode("utf-8") |
| 1317 | request.headers = { |
| 1318 | "webhook-id": test_webhook_id, |
| 1319 | "webhook-timestamp": test_timestamp, |
| 1320 | "webhook-signature": signature, |
| 1321 | } |
| 1322 | # Avoid Mock auto-creating a callable get_data attribute. |
| 1323 | del request.get_data |
| 1324 | |
| 1325 | result = triggers.parse(request, verify_secret=test_secret) |
| 1326 | |
| 1327 | assert result["version"] == WebhookVersion.V3 |
| 1328 | assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT" |
| 1329 | assert result["payload"]["payload"] == { |
| 1330 | "action": "push", |
| 1331 | "repository": "test-repo", |
| 1332 | } |
| 1333 | |
| 1334 | def test_parse_with_explicit_body_and_headers_no_verify( |
| 1335 | self, triggers, mock_v3_payload |
| 1336 | ): |
| 1337 | """Parse without verifying using explicit body/headers kwargs.""" |
| 1338 | payload = json.dumps(mock_v3_payload) |
| 1339 | |
| 1340 | result = triggers.parse(body=payload, headers={}) |
| 1341 | |
| 1342 | assert result["version"] == WebhookVersion.V3 |
| 1343 | assert result["payload"]["trigger_slug"] == "GITHUB_PUSH_EVENT" |
| 1344 | assert result["payload"]["payload"] == { |
| 1345 | "action": "push", |
| 1346 | "repository": "test-repo", |
| 1347 | } |
| 1348 | |
| 1349 | def test_parse_bad_signature_raises( |
| 1350 | self, triggers, test_secret, test_webhook_id, test_timestamp, mock_v3_payload |
| 1351 | ): |
| 1352 | """A bad signature with verify_secret raises a verification error.""" |
| 1353 | payload = json.dumps(mock_v3_payload) |
| 1354 | |
| 1355 | with pytest.raises(exceptions.WebhookSignatureVerificationError): |
| 1356 | triggers.parse( |
| 1357 | body=payload, |
| 1358 | headers={ |
| 1359 | "webhook-id": test_webhook_id, |
| 1360 | "webhook-timestamp": test_timestamp, |
| 1361 | "webhook-signature": "v1,not-a-valid-signature", |
| 1362 | }, |
| 1363 | verify_secret=test_secret, |
| 1364 | ) |
| 1365 | |
| 1366 | def test_parse_missing_headers_with_verify_raises( |
| 1367 | self, triggers, test_secret, mock_v3_payload |
| 1368 | ): |
| 1369 | """verify_secret set but missing signature headers raises ValidationError.""" |
| 1370 | payload = json.dumps(mock_v3_payload) |
| 1371 | |
| 1372 | with pytest.raises(exceptions.ValidationError) as exc_info: |
| 1373 | triggers.parse(body=payload, headers={}, verify_secret=test_secret) |
| 1374 | |
| 1375 | assert "missing signature header" in str(exc_info.value) |
| 1376 | |
| 1377 | |
| 1378 | class TestTriggerSubscriptionParsing: |
| 1379 | """Tests for realtime (Pusher) payload parsing in TriggerSubscription.""" |
| 1380 | |
| 1381 | @pytest.fixture |
| 1382 | def subscription(self): |
| 1383 | """Create a TriggerSubscription with a mock client.""" |
| 1384 | return TriggerSubscription(client=Mock()) |
| 1385 | |
| 1386 | def test_parse_payload_v3_realtime_envelope(self, subscription): |
| 1387 | """A V3 realtime envelope is parsed (no KeyError: 'nanoId').""" |
| 1388 | event = json.dumps( |
| 1389 | { |
| 1390 | "id": "evt-1", |
| 1391 | "type": "composio.trigger.message", |
| 1392 | "metadata": { |
| 1393 | "log_id": "log-1", |
| 1394 | "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE", |
| 1395 | "trigger_id": "ti_abc", |
| 1396 | "connected_account_id": "ca_abc", |
| 1397 | "auth_config_id": "ac_abc", |
| 1398 | "user_id": "user-1", |
| 1399 | }, |
| 1400 | "data": {"subject": "hello"}, |
| 1401 | } |
| 1402 | ) |
| 1403 | |
| 1404 | result = subscription._parse_payload(event) |
| 1405 | |
| 1406 | assert result is not None |
| 1407 | assert result["id"] == "ti_abc" |
| 1408 | assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE" |
| 1409 | assert result["toolkit_slug"] == "GMAIL" |
| 1410 | assert result["user_id"] == "user-1" |
| 1411 | assert result["payload"] == {"subject": "hello"} |
| 1412 | assert result["metadata"]["connected_account"]["id"] == "ca_abc" |
| 1413 | assert result["metadata"]["connected_account"]["auth_config_id"] == "ac_abc" |
| 1414 | |
| 1415 | def test_parse_payload_legacy_envelope(self, subscription): |
| 1416 | """A legacy (V1/V2) realtime envelope still parses correctly.""" |
| 1417 | event = json.dumps( |
| 1418 | { |
| 1419 | "appName": "gmail", |
| 1420 | "payload": {"subject": "hello"}, |
| 1421 | "originalPayload": {"raw": 1}, |
| 1422 | "metadata": { |
| 1423 | "id": "uuid-1", |
| 1424 | "nanoId": "ti_abc", |
| 1425 | "triggerName": "GMAIL_NEW_GMAIL_MESSAGE", |
| 1426 | "triggerData": "", |
| 1427 | "triggerConfig": {}, |
| 1428 | "connection": { |
| 1429 | "id": "conn-uuid", |
| 1430 | "connectedAccountNanoId": "ca_abc", |
| 1431 | "authConfigNanoId": "ac_abc", |
| 1432 | "integrationId": "int-uuid", |
| 1433 | "clientUniqueUserId": "user-1", |
| 1434 | "status": "ACTIVE", |
| 1435 | }, |
| 1436 | }, |
| 1437 | } |
| 1438 | ) |
| 1439 | |
| 1440 | result = subscription._parse_payload(event) |
| 1441 | |
| 1442 | assert result is not None |
| 1443 | assert result["id"] == "ti_abc" |
| 1444 | assert result["toolkit_slug"] == "gmail" |
| 1445 | assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE" |
| 1446 | assert result["metadata"]["connected_account"]["id"] == "ca_abc" |
| 1447 | assert result["original_payload"] == {"raw": 1} |
| 1448 | |
| 1449 | def test_parse_payload_malformed_returns_none(self, subscription): |
| 1450 | """Truly undecodable or unrecognized frames are skipped, not raised.""" |
| 1451 | assert subscription._parse_payload("not-json") is None |
| 1452 | assert subscription._parse_payload(json.dumps({"unexpected": True})) is None |
| 1453 | |
| 1454 | def test_parse_payload_legacy_non_dict_metadata_does_not_raise(self, subscription): |
| 1455 | """A legacy frame with a non-dict metadata is skipped, not raised. |
| 1456 | |
| 1457 | Guards the broadened `except Exception` in _parse_payload: such a frame |
| 1458 | must return None rather than propagate into pysher's dispatch loop. |
| 1459 | """ |
| 1460 | event = json.dumps({"appName": "gmail", "metadata": "not-a-dict"}) |
| 1461 | assert subscription._parse_payload(event) is None |
| 1462 | |
| 1463 | def test_parse_payload_non_trigger_v3_event(self, subscription): |
| 1464 | """A non-trigger composio.* event is normalized as a COMPOSIO event.""" |
| 1465 | event = json.dumps( |
| 1466 | { |
| 1467 | "id": "evt-1", |
| 1468 | "type": "composio.connected_account.expired", |
| 1469 | "metadata": {"project_id": "pr_1"}, |
| 1470 | "data": {"status": "EXPIRED"}, |
| 1471 | } |
| 1472 | ) |
| 1473 | |
| 1474 | result = subscription._parse_payload(event) |
| 1475 | |
| 1476 | assert result is not None |
| 1477 | assert result["toolkit_slug"] == "COMPOSIO" |
| 1478 | assert result["trigger_slug"] == "composio.connected_account.expired" |
| 1479 | assert result["original_payload"] == json.loads(event) |
| 1480 | |
| 1481 | def test_parse_payload_trigger_empty_metadata_does_not_raise(self, subscription): |
| 1482 | """A trigger frame with empty metadata is delivered with empty identity.""" |
| 1483 | event = json.dumps( |
| 1484 | { |
| 1485 | "id": "evt-1", |
| 1486 | "type": "composio.trigger.message", |
| 1487 | "metadata": {}, |
| 1488 | "data": {}, |
| 1489 | } |
| 1490 | ) |
| 1491 | |
| 1492 | result = subscription._parse_payload(event) |
| 1493 | |
| 1494 | assert result is not None |
| 1495 | assert result["trigger_slug"] == "" |
| 1496 | assert result["toolkit_slug"] == "UNKNOWN" |
| 1497 | |
| 1498 | def test_parse_payload_legacy_missing_optional_fields(self, subscription): |
| 1499 | """A legacy frame missing optional fields is delivered, not dropped.""" |
| 1500 | event = json.dumps( |
| 1501 | { |
| 1502 | "appName": "gmail", |
| 1503 | "payload": {"subject": "hello"}, |
| 1504 | # originalPayload + triggerData intentionally omitted |
| 1505 | "metadata": { |
| 1506 | "id": "uuid-1", |
| 1507 | "nanoId": "ti_abc", |
| 1508 | "triggerName": "GMAIL_NEW_GMAIL_MESSAGE", |
| 1509 | "triggerConfig": {}, |
| 1510 | "connection": { |
| 1511 | "id": "conn-uuid", |
| 1512 | "connectedAccountNanoId": "ca_abc", |
| 1513 | "authConfigNanoId": "ac_abc", |
| 1514 | "integrationId": "int-uuid", |
| 1515 | "clientUniqueUserId": "user-1", |
| 1516 | "status": "ACTIVE", |
| 1517 | }, |
| 1518 | }, |
| 1519 | } |
| 1520 | ) |
| 1521 | |
| 1522 | result = subscription._parse_payload(event) |
| 1523 | |
| 1524 | assert result is not None |
| 1525 | assert result["original_payload"] is None |
| 1526 | assert result["metadata"]["trigger_data"] is None |
| 1527 | |
| 1528 | def test_parse_payload_trigger_keyed_off_type_not_all_metadata(self, subscription): |
| 1529 | """A trigger frame missing one metadata field is still a trigger event. |
| 1530 | |
| 1531 | Detection keys off ``type == "composio.trigger.message"`` rather than |
| 1532 | requiring all six metadata fields, so the event is delivered (not |
| 1533 | silently demoted to a non-trigger COMPOSIO event). |
| 1534 | """ |
| 1535 | event = json.dumps( |
| 1536 | { |
| 1537 | "id": "evt-1", |
| 1538 | "type": "composio.trigger.message", |
| 1539 | "metadata": { |
| 1540 | # ``log_id`` intentionally omitted |
| 1541 | "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE", |
| 1542 | "trigger_id": "ti_abc", |
| 1543 | "connected_account_id": "ca_abc", |
| 1544 | "auth_config_id": "ac_abc", |
| 1545 | "user_id": "user-1", |
| 1546 | }, |
| 1547 | "data": {"subject": "hello"}, |
| 1548 | } |
| 1549 | ) |
| 1550 | |
| 1551 | result = subscription._parse_payload(event) |
| 1552 | |
| 1553 | assert result is not None |
| 1554 | assert result["trigger_slug"] == "GMAIL_NEW_GMAIL_MESSAGE" |
| 1555 | assert result["toolkit_slug"] == "GMAIL" |
| 1556 | assert result["user_id"] == "user-1" |
| 1557 | |
| 1558 | def test_parse_payload_non_string_trigger_slug_does_not_raise(self, subscription): |
| 1559 | """A null/non-string trigger_slug must not raise AttributeError (Vector A).""" |
| 1560 | event = json.dumps( |
| 1561 | { |
| 1562 | "id": "evt-1", |
| 1563 | "type": "composio.trigger.message", |
| 1564 | "metadata": { |
| 1565 | "trigger_slug": None, |
| 1566 | "trigger_id": "ti_abc", |
| 1567 | "connected_account_id": "ca_abc", |
| 1568 | "auth_config_id": "ac_abc", |
| 1569 | "user_id": 123, |
| 1570 | "log_id": "log-1", |
| 1571 | }, |
| 1572 | "data": {"subject": "hello"}, |
| 1573 | } |
| 1574 | ) |
| 1575 | |
| 1576 | result = subscription._parse_payload(event) |
| 1577 | |
| 1578 | assert result is not None |
| 1579 | assert result["trigger_slug"] == "" |
| 1580 | assert result["toolkit_slug"] == "UNKNOWN" |
| 1581 | assert result["user_id"] == "123" |
| 1582 | |
| 1583 | @staticmethod |
| 1584 | def _make_event(**overrides): |
| 1585 | """Build a minimal TriggerEvent dict for filter-matching tests.""" |
| 1586 | event = { |
| 1587 | "id": "ti_1", |
| 1588 | "uuid": "ti_1", |
| 1589 | "user_id": "user-1", |
| 1590 | "toolkit_slug": "GMAIL", |
| 1591 | "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE", |
| 1592 | "metadata": { |
| 1593 | "id": "ti_1", |
| 1594 | "connected_account": { |
| 1595 | "id": "ca_1", |
| 1596 | "auth_config_id": "ac_1", |
| 1597 | }, |
| 1598 | }, |
| 1599 | } |
| 1600 | event.update(overrides) |
| 1601 | return event |
| 1602 | |
| 1603 | def test_filters_match_no_filters_matches(self, subscription): |
| 1604 | """An empty filterset matches any event.""" |
| 1605 | assert subscription._filters_match(self._make_event(), {}, "cb") is True |
| 1606 | |
| 1607 | def test_filters_match_does_not_crash_on_non_string_event_value(self, subscription): |
| 1608 | """A non-string identity field must not raise AttributeError (Vector B).""" |
| 1609 | event = self._make_event(user_id=123) |
| 1610 | assert subscription._filters_match(event, {"user_id": "123"}, "cb") is True |
| 1611 | assert subscription._filters_match(event, {"user_id": "999"}, "cb") is False |
| 1612 | |
| 1613 | def test_filters_match_empty_event_value_does_not_fail_open(self, subscription): |
| 1614 | """A synthesized empty identity field must not match a "" filter.""" |
| 1615 | event = self._make_event(user_id="") |
| 1616 | assert subscription._filters_match(event, {"user_id": ""}, "cb") is False |
| 1617 | |
| 1618 | # Toolkit slugs such as `one_drive`, `launch_darkly` and `agent_mail` contain |
| 1619 | # an underscore, so the toolkit derived from the trigger slug's first segment |
| 1620 | # is `ONE`, not `ONE_DRIVE`. |
| 1621 | @staticmethod |
| 1622 | def _v3_frame(trigger_slug): |
| 1623 | return json.dumps( |
| 1624 | { |
| 1625 | "id": "evt-1", |
| 1626 | "type": "composio.trigger.message", |
| 1627 | "metadata": { |
| 1628 | "trigger_slug": trigger_slug, |
| 1629 | "trigger_id": "ti_abc", |
| 1630 | "connected_account_id": "ca_abc", |
| 1631 | "auth_config_id": "ac_abc", |
| 1632 | "user_id": "user-1", |
| 1633 | "log_id": "log-1", |
| 1634 | }, |
| 1635 | "data": {}, |
| 1636 | } |
| 1637 | ) |
| 1638 | |
| 1639 | @pytest.mark.parametrize("toolkit", ["one_drive", "ONE_DRIVE"]) |
| 1640 | def test_filters_match_toolkit_slug_with_underscore(self, subscription, toolkit): |
| 1641 | """A `toolkit` filter matches events of a toolkit whose slug has an underscore.""" |
| 1642 | event = subscription._parse_payload( |
| 1643 | self._v3_frame("ONE_DRIVE_FILE_CREATED_TRIGGER") |
| 1644 | ) |
| 1645 | assert event is not None |
| 1646 | assert subscription._filters_match(event, {"toolkit": toolkit}, "cb") is True |
| 1647 | |
| 1648 | def test_filters_match_toolkit_prefix_needs_full_segment(self, subscription): |
| 1649 | """A `toolkit` filter that only shares a prefix with the trigger slug does not match.""" |
| 1650 | event = subscription._parse_payload(self._v3_frame("ONE_DRIVEX_FILE_CREATED")) |
| 1651 | assert event is not None |
| 1652 | assert ( |
| 1653 | subscription._filters_match(event, {"toolkit": "one_drive"}, "cb") is False |
| 1654 | ) |
| 1655 | |
| 1656 | def test_truncate_frame_bounds_long_frames(self): |
| 1657 | """A long raw frame is truncated so PII-bearing frames aren't dumped.""" |
| 1658 | short = "x" * 10 |
| 1659 | assert _truncate_frame(short) == short |
| 1660 | |
| 1661 | long = "y" * (_MAX_LOGGED_FRAME_CHARS + 100) |
| 1662 | truncated = _truncate_frame(long) |
| 1663 | assert len(truncated) < len(long) |
| 1664 | assert truncated.startswith("y" * _MAX_LOGGED_FRAME_CHARS) |
| 1665 | assert str(len(long)) in truncated |
| 1666 | |
| 1667 | |
| 1668 | class TestChunkedEventResilience: |
| 1669 | """A malformed chunked frame must never tear down the subscription. |
| 1670 | |
| 1671 | ``_handle_chunked_events`` is bound directly as a pysher channel callback, |
| 1672 | and pysher invokes bound callbacks without a try/except. Before the fix, |
| 1673 | any malformed frame (bad JSON, missing key, wrong type) propagated up and |
| 1674 | killed the subscription — the same failure mode already guarded against in |
| 1675 | ``_parse_payload``. |
| 1676 | """ |
| 1677 | |
| 1678 | @pytest.fixture |
| 1679 | def subscription(self): |
| 1680 | """Create a TriggerSubscription with a mock client.""" |
| 1681 | return TriggerSubscription(client=Mock()) |
| 1682 | |
| 1683 | def test_malformed_json_does_not_raise(self, subscription): |
| 1684 | """A non-JSON frame is logged and skipped, not raised.""" |
| 1685 | # Must not raise — pysher's dispatch loop has no try/except. |
| 1686 | subscription._handle_chunked_events("not valid json {") |
| 1687 | # No chunks were buffered for the bad frame. |
| 1688 | assert subscription._chunks == {} |
| 1689 | |
| 1690 | @pytest.mark.parametrize( |
| 1691 | "event", |
| 1692 | [ |
| 1693 | [], |
| 1694 | {"id": "evt-1", "index": 0}, |
| 1695 | {"id": [], "index": 0, "chunk": "x", "final": True}, |
| 1696 | {"id": "evt-1", "index": "zero", "chunk": "x", "final": True}, |
| 1697 | {"id": "evt-1", "index": True, "chunk": "x", "final": True}, |
| 1698 | {"id": "evt-1", "index": 0, "chunk": 1, "final": True}, |
| 1699 | {"id": "evt-1", "index": 0, "chunk": "x", "final": "true"}, |
| 1700 | ], |
| 1701 | ) |
| 1702 | def test_invalid_frame_is_skipped(self, subscription, event): |
| 1703 | """Missing or wrongly typed fields are skipped without dispatching.""" |
| 1704 | with patch.object(subscription, "_handle_event") as mock_handle: |
| 1705 | subscription._handle_chunked_events(json.dumps(event)) |
| 1706 | |
| 1707 | mock_handle.assert_not_called() |
| 1708 | assert subscription._chunks == {} |
| 1709 | |
| 1710 | def test_decoder_failure_does_not_raise(self, subscription): |
| 1711 | """Unexpected decoder failures are contained at the callback boundary.""" |
| 1712 | with patch( |
| 1713 | "composio.core.models.triggers.json.loads", side_effect=RecursionError |
| 1714 | ): |
| 1715 | subscription._handle_chunked_events("[]") |
| 1716 | |
| 1717 | assert subscription._chunks == {} |
| 1718 | |
| 1719 | def test_valid_chunks_reassemble_after_bad_frame_for_same_id(self, subscription): |
| 1720 | """A bad frame clears partial state so the same id can be reused.""" |
| 1721 | with patch.object(subscription, "_handle_event") as mock_handle: |
| 1722 | subscription._handle_chunked_events( |
| 1723 | json.dumps( |
| 1724 | {"id": "evt-1", "index": 0, "chunk": "stale", "final": False} |
| 1725 | ) |
| 1726 | ) |
| 1727 | subscription._handle_chunked_events( |
| 1728 | json.dumps( |
| 1729 | {"id": "evt-1", "index": "bad", "chunk": "x", "final": False} |
| 1730 | ) |
| 1731 | ) |
| 1732 | subscription._handle_chunked_events( |
| 1733 | json.dumps({"id": "evt-1", "index": 0, "chunk": "hel", "final": False}) |
| 1734 | ) |
| 1735 | subscription._handle_chunked_events( |
| 1736 | json.dumps({"id": "evt-1", "index": 1, "chunk": "lo", "final": True}) |
| 1737 | ) |
| 1738 | |
| 1739 | mock_handle.assert_called_once_with(event="hello") |
| 1740 | assert subscription._chunks == {} |
| 1741 | |
| 1742 | |
| 1743 | class TestTriggerSubscriptionStop: |
| 1744 | """Tests for TriggerSubscription.stop lifecycle handling.""" |
| 1745 | |
| 1746 | @pytest.fixture |
| 1747 | def subscription(self): |
| 1748 | """Create a TriggerSubscription with a mock client.""" |
| 1749 | sub = TriggerSubscription(client=Mock()) |
| 1750 | sub._alive = True |
| 1751 | return sub |
| 1752 | |
| 1753 | def test_stop_clears_alive_synchronously(self, subscription): |
| 1754 | """``_alive`` is cleared before ``stop`` returns, not after disconnect. |
| 1755 | |
| 1756 | A main thread parked in ``wait_forever`` checks ``_alive`` every |
| 1757 | second; clearing it synchronously (rather than after a potentially |
| 1758 | blocking ``disconnect``) lets that loop exit promptly. |
| 1759 | """ |
| 1760 | disconnect_started = threading.Event() |
| 1761 | |
| 1762 | def blocking_disconnect(): |
| 1763 | disconnect_started.set() |
| 1764 | # Block so we can prove _alive was cleared without waiting on |
| 1765 | # the disconnect. |
| 1766 | threading.Event().wait(timeout=5) |
| 1767 | |
| 1768 | subscription._connection = Mock() |
| 1769 | subscription._connection.disconnect = blocking_disconnect |
| 1770 | |
| 1771 | subscription.stop() |
| 1772 | |
| 1773 | # _alive is False the moment stop() returns, even though disconnect |
| 1774 | # is still running in the background. |
| 1775 | assert subscription.is_alive() is False |
| 1776 | assert disconnect_started.wait(timeout=2) |
| 1777 | |
| 1778 | def test_stop_does_not_block_on_slow_disconnect(self, subscription): |
| 1779 | """``stop()`` returns even if ``disconnect`` would block forever. |
| 1780 | |
| 1781 | pysher's ``Connection.disconnect`` joins the websocket thread. When |
| 1782 | ``stop()`` is called from a callback that pysher dispatches on that |
| 1783 | same thread, the join deadlocks. Running the disconnect on a daemon |
| 1784 | thread breaks the reentrancy: ``stop`` returns immediately even when |
| 1785 | ``disconnect`` never completes. |
| 1786 | """ |
| 1787 | started = threading.Event() |
| 1788 | never_set = threading.Event() |
| 1789 | |
| 1790 | def blocking_disconnect(): |
| 1791 | started.set() |
| 1792 | # Simulate pysher joining a thread that never finishes (the |
| 1793 | # deadlock state from the bug report). |
| 1794 | never_set.wait(timeout=5) |
| 1795 | |
| 1796 | subscription._connection = Mock() |
| 1797 | subscription._connection.disconnect = blocking_disconnect |
| 1798 | |
| 1799 | # If stop() were to call disconnect() inline it would block here. |
| 1800 | subscription.stop() |
| 1801 | |
| 1802 | # stop() returned control and the disconnect is running in the |
| 1803 | # background. |
| 1804 | assert subscription.is_alive() is False |
| 1805 | assert started.wait(timeout=2) |
| 1806 | |
| 1807 | def test_has_errored_ignores_socket_flag_while_pysher_retries(self, subscription): |
| 1808 | """A recoverable drop is not an error while pysher keeps retrying. |
| 1809 | |
| 1810 | websocket-client's ``has_errored`` stays set through pysher's |
| 1811 | reconnect backoff, so ``has_errored()`` must not consult it: only |
| 1812 | the pysher connection thread (alive across reconnects) decides. |
| 1813 | """ |
| 1814 | connection = Mock() |
| 1815 | connection.is_alive.return_value = True |
| 1816 | connection.socket = Mock() |
| 1817 | connection.socket.has_errored = True |
| 1818 | subscription._connection = connection |
| 1819 | |
| 1820 | assert subscription.has_errored() is False |
| 1821 | |
| 1822 | def test_has_errored_when_pysher_thread_died(self, subscription): |
| 1823 | """Once pysher gives up for good, the connection counts as errored. |
| 1824 | |
| 1825 | After an unrecoverable ``pusher:error`` (4000-4099) pysher |
| 1826 | disconnects and its connection thread exits; websocket-client's |
| 1827 | flag may never have been set, but ``has_errored()`` must still |
| 1828 | report the dead connection. |
| 1829 | """ |
| 1830 | connection = Mock() |
| 1831 | connection.is_alive.return_value = False |
| 1832 | connection.socket = Mock() |
| 1833 | connection.socket.has_errored = False |
| 1834 | subscription._connection = connection |
| 1835 | |
| 1836 | assert subscription.has_errored() is True |
| 1837 | |
| 1838 | def test_wait_forever_returns_when_pysher_gives_up(self, subscription): |
| 1839 | """``wait_forever`` unblocks once the pysher thread is gone.""" |
| 1840 | connection = Mock() |
| 1841 | connection.is_alive.return_value = False |
| 1842 | subscription._connection = connection |
| 1843 | |
| 1844 | waiter = threading.Thread(target=subscription.wait_forever, daemon=True) |
| 1845 | waiter.start() |
| 1846 | try: |
| 1847 | waiter.join(timeout=2) |
| 1848 | assert not waiter.is_alive() |
| 1849 | finally: |
| 1850 | subscription._alive = False |
| 1851 | waiter.join(timeout=2) |
| 1852 | |
| 1853 | def test_restart_preserves_pysher_worker(self, subscription): |
| 1854 | """Manual reconnect keeps the real worker and subscription wait alive.""" |
| 1855 | connected = threading.Event() |
| 1856 | reconnected = threading.Event() |
| 1857 | closed = threading.Event() |
| 1858 | done = threading.Event() |
| 1859 | attempts = [] |
| 1860 | |
| 1861 | class Socket: |
| 1862 | has_errored = False |
| 1863 | |
| 1864 | def run_forever(self, **kwargs): |
| 1865 | closed.clear() |
| 1866 | attempts.append(threading.current_thread()) |
| 1867 | (connected if len(attempts) == 1 else reconnected).set() |
| 1868 | closed.wait(timeout=5) |
| 1869 | |
| 1870 | def close(self): |
| 1871 | closed.set() |
| 1872 | |
| 1873 | connection = triggers_module.PusherConnection( |
| 1874 | event_handler=Mock(), url="ws://localhost", reconnect_interval=0 |
| 1875 | ) |
| 1876 | subscription._connection = connection |
| 1877 | waiter = threading.Thread( |
| 1878 | target=lambda: (subscription.wait_forever(), done.set()), daemon=True |
| 1879 | ) |
| 1880 | restarter = threading.Thread(target=subscription.restart, daemon=True) |
| 1881 | with patch("pysher.connection.websocket.WebSocketApp", return_value=Socket()): |
| 1882 | connection.start() |
| 1883 | try: |
| 1884 | assert connected.wait(timeout=2) |
| 1885 | waiter.start() |
| 1886 | restarter.start() |
| 1887 | assert reconnected.wait(timeout=2) |
| 1888 | assert subscription.has_errored() is False |
| 1889 | assert attempts[:2] == [connection, connection] |
| 1890 | restarter.join(timeout=2) |
| 1891 | assert not restarter.is_alive() |
| 1892 | assert not done.wait(timeout=1.1) |
| 1893 | # Terminal worker death must end a wait already in progress. |
| 1894 | connection.disconnect(timeout=2) |
| 1895 | assert done.wait(timeout=2) |
| 1896 | finally: |
| 1897 | subscription._alive = False |
| 1898 | connection.disconnect(timeout=2) |
| 1899 | restarter.join(timeout=2) |
| 1900 | if waiter.ident is not None: |
| 1901 | waiter.join(timeout=2) |
| 1902 | |
| 1903 | def test_wait_forever_survives_reconnect_backoff(self, subscription): |
| 1904 | """``wait_forever`` does not return early on a recoverable drop. |
| 1905 | |
| 1906 | The pysher thread stays alive through its reconnect backoff even |
| 1907 | though the socket flagged an error; the wait must survive until |
| 1908 | ``stop()`` clears ``_alive``. |
| 1909 | """ |
| 1910 | connection = Mock() |
| 1911 | connection.is_alive.return_value = True |
| 1912 | connection.socket = Mock() |
| 1913 | connection.socket.has_errored = True |
| 1914 | subscription._connection = connection |
| 1915 | |
| 1916 | done = threading.Event() |
| 1917 | waiter = threading.Thread( |
| 1918 | target=lambda: (subscription.wait_forever(), done.set()), |
| 1919 | daemon=True, |
| 1920 | ) |
| 1921 | waiter.start() |
| 1922 | |
| 1923 | assert not done.wait(timeout=2.5) |
| 1924 | subscription.stop() |
| 1925 | assert done.wait(timeout=5) |
| 1926 | |
| 1927 | |
| 1928 | class TestSubscriptionBuilderConnectTimeout: |
| 1929 | """Tests for _SubcriptionBuilder.connect timeout teardown.""" |
| 1930 | |
| 1931 | def _make_builder(self, pusher: Mock) -> _SubcriptionBuilder: |
| 1932 | """Build a _SubcriptionBuilder with a patched pusher factory.""" |
| 1933 | client = Mock() |
| 1934 | client.base_url = "https://api.example.com" |
| 1935 | with patch.object( |
| 1936 | _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher |
| 1937 | ): |
| 1938 | b = _SubcriptionBuilder(client=client) |
| 1939 | b.subscription = Mock() |
| 1940 | b.subscription.is_alive.return_value = False |
| 1941 | b.internal = Mock() |
| 1942 | b.internal.get_sdk_realtime_credentials.return_value = Mock( |
| 1943 | project_id="p", pusher_key="k", pusher_cluster="c" |
| 1944 | ) |
| 1945 | b._get_connection_handler = Mock( # type: ignore[method-assign] |
| 1946 | return_value=lambda *a, **k: None |
| 1947 | ) |
| 1948 | return b |
| 1949 | |
| 1950 | def test_connect_disconnects_pusher_on_timeout(self): |
| 1951 | """On timeout, the partially-connected pusher is torn down. |
| 1952 | |
| 1953 | pysher's connection loop redials every ``reconnect_interval`` until |
| 1954 | ``disconnect`` is called. If ``connect`` raises without disconnecting, |
| 1955 | each timed-out attempt leaks a websocket thread for the life of the |
| 1956 | process. The fix wraps the wait loop in try/except so the timeout |
| 1957 | path disconnects before re-raising. |
| 1958 | """ |
| 1959 | pusher = Mock() |
| 1960 | builder = self._make_builder(pusher) |
| 1961 | # subscription.is_alive() returns False, so the wait loop never |
| 1962 | # returns early -> the deadline elapses -> timeout path runs. |
| 1963 | builder.subscription.is_alive.return_value = False |
| 1964 | |
| 1965 | with ( |
| 1966 | patch.object( |
| 1967 | _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher |
| 1968 | ), |
| 1969 | pytest.raises(ComposioSDKTimeoutError), |
| 1970 | ): |
| 1971 | builder.connect(timeout=0.1) |
| 1972 | |
| 1973 | pusher.disconnect.assert_called_once() |
| 1974 | |
| 1975 | def test_connect_returns_subscription_without_disconnecting(self): |
| 1976 | """On success, the pusher stays connected and is attached to the sub.""" |
| 1977 | pusher = Mock() |
| 1978 | builder = self._make_builder(pusher) |
| 1979 | builder.subscription.is_alive.return_value = True |
| 1980 | |
| 1981 | with patch.object( |
| 1982 | _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher |
| 1983 | ): |
| 1984 | result = builder.connect(timeout=2.0) |
| 1985 | |
| 1986 | assert result is builder.subscription |
| 1987 | pusher.disconnect.assert_not_called() |
| 1988 | |
| 1989 | def test_connect_raises_recorded_failure_fast(self): |
| 1990 | """An establish-time failure raises promptly instead of timing out. |
| 1991 | |
| 1992 | The connection handler records the failure (for example a channel-auth |
| 1993 | rejection raised inside ``pusher.subscribe()``); the wait loop must |
| 1994 | surface it on its next poll and tear down the pusher, not spin until |
| 1995 | the deadline and report a generic timeout. |
| 1996 | """ |
| 1997 | pusher = Mock() |
| 1998 | builder = self._make_builder(pusher) |
| 1999 | failure = RuntimeError("auth rejected") |
| 2000 | # The connection handler records the failure; on the mocked |
| 2001 | # subscription this is the wait loop's re-raise hook. |
| 2002 | builder.subscription._raise_on_connection_error.side_effect = failure |
| 2003 | builder._get_connection_handler = Mock( # type: ignore[method-assign] |
| 2004 | return_value=lambda *a, **k: None |
| 2005 | ) |
| 2006 | |
| 2007 | started = time.monotonic() |
| 2008 | with ( |
| 2009 | patch.object( |
| 2010 | _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher |
| 2011 | ), |
| 2012 | pytest.raises(RuntimeError, match="auth rejected"), |
| 2013 | ): |
| 2014 | builder.connect(timeout=15.0) |
| 2015 | |
| 2016 | assert time.monotonic() - started < 5.0 |
| 2017 | pusher.disconnect.assert_called_once() |
| 2018 | |
| 2019 | |
| 2020 | class TestSubscriptionErrorHandler: |
| 2021 | """Tests for TriggerSubscription._handle_subscription_error.""" |
| 2022 | |
| 2023 | @pytest.fixture |
| 2024 | def subscription(self): |
| 2025 | """Create a TriggerSubscription with a mock client.""" |
| 2026 | return TriggerSubscription(client=Mock()) |
| 2027 | |
| 2028 | def test_invokes_callback_with_parsed_payload(self, subscription): |
| 2029 | """The callback receives the subscription error payload as a dict.""" |
| 2030 | callback = Mock() |
| 2031 | subscription._on_subscription_error = callback |
| 2032 | |
| 2033 | subscription._handle_subscription_error('{"type": "AuthError", "status": 401}') |
| 2034 | |
| 2035 | callback.assert_called_once_with({"type": "AuthError", "status": 401}) |
| 2036 | |
| 2037 | def test_malformed_frame_reaches_callback_as_raw(self, subscription): |
| 2038 | """A non-JSON frame is logged, not raised, and passed as ``{'raw': ...}``.""" |
| 2039 | callback = Mock() |
| 2040 | subscription._on_subscription_error = callback |
| 2041 | |
| 2042 | subscription._handle_subscription_error("not valid json {") |
| 2043 | |
| 2044 | callback.assert_called_once_with({"raw": "not valid json {"}) |
| 2045 | |
| 2046 | def test_callback_exception_is_contained(self, subscription): |
| 2047 | """A faulty handler is logged, never rethrown into pysher's thread.""" |
| 2048 | subscription._on_subscription_error = Mock(side_effect=RuntimeError("boom")) |
| 2049 | |
| 2050 | subscription._handle_subscription_error('{"error": "auth failed"}') |
| 2051 | |
| 2052 | def test_no_callback_is_a_no_op(self, subscription): |
| 2053 | """Without a registered callback the frame is only logged.""" |
| 2054 | subscription._handle_subscription_error('{"error": "auth failed"}') |
| 2055 | |
| 2056 | def test_fail_subscription_invokes_callback_and_records_error(self, subscription): |
| 2057 | """Establish-time failures reach the callback as ``{'error': ...}``.""" |
| 2058 | callback = Mock() |
| 2059 | subscription._on_subscription_error = callback |
| 2060 | |
| 2061 | subscription._fail_subscription(RuntimeError("auth rejected")) |
| 2062 | |
| 2063 | callback.assert_called_once_with({"error": "auth rejected"}) |
| 2064 | assert subscription._connection_error is not None |
| 2065 | |
| 2066 | def test_fail_subscription_without_callback_only_records(self, subscription): |
| 2067 | """The failure is recorded even when no callback is registered.""" |
| 2068 | subscription._fail_subscription(RuntimeError("auth rejected")) |
| 2069 | |
| 2070 | assert subscription._connection_error is not None |
| 2071 | |
| 2072 | def test_fail_subscription_contains_callback_exception(self, subscription): |
| 2073 | """A faulty callback cannot break the failure path.""" |
| 2074 | subscription._on_subscription_error = Mock(side_effect=RuntimeError("boom")) |
| 2075 | |
| 2076 | subscription._fail_subscription(RuntimeError("auth rejected")) |
| 2077 | |
| 2078 | assert subscription._connection_error is not None |
| 2079 | |
| 2080 | def test_raise_on_connection_error_raises_recorded_error(self, subscription): |
| 2081 | """The wait loop re-raises the recorded failure.""" |
| 2082 | subscription._fail_subscription(RuntimeError("auth rejected")) |
| 2083 | |
| 2084 | with pytest.raises(RuntimeError, match="auth rejected"): |
| 2085 | subscription._raise_on_connection_error() |
| 2086 | |
| 2087 | def test_raise_on_connection_error_is_noop_when_healthy(self, subscription): |
| 2088 | """No recorded failure means the wait loop proceeds normally.""" |
| 2089 | subscription._raise_on_connection_error() |
| 2090 | |
| 2091 | def test_connection_handler_binds_subscription_error(self): |
| 2092 | """The builder binds ``pusher:subscription_error`` to the handler.""" |
| 2093 | client = Mock() |
| 2094 | client.base_url = "https://api.example.com" |
| 2095 | builder = _SubcriptionBuilder(client=client) |
| 2096 | channel = Mock() |
| 2097 | pusher = Mock() |
| 2098 | pusher.subscribe.return_value = channel |
| 2099 | |
| 2100 | handler = builder._get_connection_handler( |
| 2101 | project_id="p", pusher=pusher, subscription=builder.subscription |
| 2102 | ) |
| 2103 | handler("connection-payload") |
| 2104 | |
| 2105 | bound = { |
| 2106 | call.kwargs["event_name"]: call.kwargs["callback"] |
| 2107 | for call in channel.bind.call_args_list |
| 2108 | } |
| 2109 | assert ( |
| 2110 | bound["pusher:subscription_error"] |
| 2111 | == builder.subscription._handle_subscription_error |
| 2112 | ) |
| 2113 | assert bound["trigger_to_client"] == builder.subscription._handle_event |
| 2114 | assert ( |
| 2115 | bound["chunked-trigger_to_client"] |
| 2116 | == builder.subscription._handle_chunked_events |
| 2117 | ) |
| 2118 | |
| 2119 | def test_connection_handler_routes_subscribe_failure_to_error_path(self): |
| 2120 | """Auth failures inside ``pusher.subscribe()`` reach the error path. |
| 2121 | |
| 2122 | pysher performs the channel-auth request synchronously inside |
| 2123 | ``subscribe()``; without this routing the callback is skipped and the |
| 2124 | caller waits out the connect timeout for a generic error. |
| 2125 | """ |
| 2126 | client = Mock() |
| 2127 | client.base_url = "https://api.example.com" |
| 2128 | builder = _SubcriptionBuilder(client=client) |
| 2129 | callback = Mock() |
| 2130 | builder.subscription._on_subscription_error = callback |
| 2131 | pusher = Mock() |
| 2132 | pusher.subscribe.side_effect = exceptions.TriggerSubscriptionAuthError( |
| 2133 | "auth failed" |
| 2134 | ) |
| 2135 | |
| 2136 | handler = builder._get_connection_handler( |
| 2137 | project_id="p", pusher=pusher, subscription=builder.subscription |
| 2138 | ) |
| 2139 | handler("connection-payload") # must not raise |
| 2140 | |
| 2141 | callback.assert_called_once_with({"error": "auth failed"}) |
| 2142 | assert builder.subscription.is_alive() is False |
| 2143 | |
| 2144 | |
| 2145 | class TestPusherChannelAuth: |
| 2146 | """Tests for the hardened pysher channel-auth request.""" |
| 2147 | |
| 2148 | @staticmethod |
| 2149 | def _pusher() -> triggers_module._ComposioPusher: |
| 2150 | return triggers_module._ComposioPusher( |
| 2151 | key="app-key", |
| 2152 | cluster="mt1", |
| 2153 | auth_endpoint="https://api.example.com/api/v3/internal/sdk/realtime/auth", |
| 2154 | auth_endpoint_headers={"x-api-key": "sk-secret-value"}, |
| 2155 | ) |
| 2156 | |
| 2157 | def test_auth_request_carries_a_timeout(self): |
| 2158 | """pysher sends the auth POST with no timeout; the subclass bounds it.""" |
| 2159 | pusher = self._pusher() |
| 2160 | pusher.connection.socket_id = "123.456" |
| 2161 | response = Mock(status_code=200) |
| 2162 | response.json.return_value = {"auth": "app-key:signature"} |
| 2163 | |
| 2164 | with patch.object( |
| 2165 | triggers_module.requests, "post", return_value=response |
| 2166 | ) as post: |
| 2167 | token = pusher._generate_auth_token("private-project_triggers") |
| 2168 | |
| 2169 | assert token == "app-key:signature" |
| 2170 | post.assert_called_once_with( |
| 2171 | "https://api.example.com/api/v3/internal/sdk/realtime/auth", |
| 2172 | data={"channel_name": "private-project_triggers", "socket_id": "123.456"}, |
| 2173 | headers={"x-api-key": "sk-secret-value"}, |
| 2174 | timeout=triggers_module.PUSHER_AUTH_TIMEOUT, |
| 2175 | ) |
| 2176 | assert triggers_module.PUSHER_AUTH_TIMEOUT == (5.0, 15.0) |
| 2177 | |
| 2178 | def test_presence_request_carries_a_timeout(self): |
| 2179 | pusher = self._pusher() |
| 2180 | pusher.connection.socket_id = "123.456" |
| 2181 | response = Mock(status_code=200) |
| 2182 | response.json.return_value = {"auth": "app-key:signature"} |
| 2183 | |
| 2184 | with patch.object( |
| 2185 | triggers_module.requests, "post", return_value=response |
| 2186 | ) as post: |
| 2187 | pusher._generate_presence_token("presence-room") |
| 2188 | |
| 2189 | assert post.call_args.kwargs["timeout"] == triggers_module.PUSHER_AUTH_TIMEOUT |
| 2190 | assert post.call_args.kwargs["data"]["user_data"] == {} |
| 2191 | |
| 2192 | @pytest.mark.parametrize("status_code", [401, 403, 500]) |
| 2193 | def test_non_200_raises_typed_error_without_the_api_key(self, status_code): |
| 2194 | """A non-200 used to trip a bare ``assert`` on the websocket thread.""" |
| 2195 | pusher = self._pusher() |
| 2196 | response = Mock(status_code=status_code) |
| 2197 | |
| 2198 | with ( |
| 2199 | patch.object(triggers_module.requests, "post", return_value=response), |
| 2200 | pytest.raises(exceptions.TriggerSubscriptionAuthError) as info, |
| 2201 | ): |
| 2202 | pusher._generate_auth_token("private-project_triggers") |
| 2203 | |
| 2204 | assert isinstance(info.value, exceptions.TriggerSubscriptionError) |
| 2205 | assert f"HTTP {status_code}" in str(info.value) |
| 2206 | assert "sk-secret-value" not in str(info.value) |
| 2207 | |
| 2208 | def test_transport_failure_raises_typed_error(self): |
| 2209 | with ( |
| 2210 | patch.object( |
| 2211 | triggers_module.requests, |
| 2212 | "post", |
| 2213 | side_effect=requests.ConnectTimeout("slow"), |
| 2214 | ), |
| 2215 | pytest.raises( |
| 2216 | exceptions.TriggerSubscriptionAuthError, match="ConnectTimeout" |
| 2217 | ), |
| 2218 | ): |
| 2219 | self._pusher()._generate_auth_token("private-project_triggers") |
| 2220 | |
| 2221 | @pytest.mark.parametrize("body", [{}, {"auth": ""}, {"auth": 1}, []]) |
| 2222 | def test_missing_auth_token_raises_typed_error(self, body): |
| 2223 | response = Mock(status_code=200) |
| 2224 | response.json.return_value = body |
| 2225 | |
| 2226 | with ( |
| 2227 | patch.object(triggers_module.requests, "post", return_value=response), |
| 2228 | pytest.raises( |
| 2229 | exceptions.TriggerSubscriptionAuthError, match="`auth` token" |
| 2230 | ), |
| 2231 | ): |
| 2232 | self._pusher()._generate_auth_token("private-project_triggers") |
| 2233 | |
| 2234 | |
| 2235 | class TestPusherClusterValidation: |
| 2236 | """The cluster comes from an API response and lands in the websocket host.""" |
| 2237 | |
| 2238 | @staticmethod |
| 2239 | def _builder() -> _SubcriptionBuilder: |
| 2240 | client = Mock() |
| 2241 | client.base_url = "https://api.example.com" |
| 2242 | client.sdk_auth = ProjectAuth("sk-secret-value") |
| 2243 | return _SubcriptionBuilder(client=client) |
| 2244 | |
| 2245 | @pytest.mark.parametrize("cluster", ["mt1", "eu", "ap-southeast-1", "us3"]) |
| 2246 | def test_valid_cluster_builds_the_expected_host(self, cluster): |
| 2247 | pusher = self._builder()._get_pusher_instance(key="app-key", cluster=cluster) |
| 2248 | |
| 2249 | assert isinstance(pusher, triggers_module._ComposioPusher) |
| 2250 | assert pusher.host == f"ws-{cluster}.pusher.com" |
| 2251 | assert pusher.auth_endpoint_headers["x-api-key"] == "sk-secret-value" |
| 2252 | |
| 2253 | def test_user_only_client_authorizes_the_channel_with_the_user_key(self): |
| 2254 | client = Mock() |
| 2255 | client.base_url = "https://api.example.com" |
| 2256 | client.sdk_auth = UserAuth("uak_user_key") |
| 2257 | client.default_headers = {} |
| 2258 | |
| 2259 | pusher = _SubcriptionBuilder(client=client)._get_pusher_instance( |
| 2260 | key="app-key", cluster="mt1" |
| 2261 | ) |
| 2262 | |
| 2263 | assert "x-api-key" not in pusher.auth_endpoint_headers |
| 2264 | assert pusher.auth_endpoint_headers["x-user-api-key"] == "uak_user_key" |
| 2265 | |
| 2266 | def test_user_key_default_header_authorizes_the_channel_without_auth(self): |
| 2267 | """Under ``NoAuth`` a caller-placed user key header is the credential.""" |
| 2268 | client = Mock() |
| 2269 | client.base_url = "https://api.example.com" |
| 2270 | client.sdk_auth = NoAuth() |
| 2271 | client.default_headers = {"X-User-Api-Key": "uak_header_key"} |
| 2272 | |
| 2273 | pusher = _SubcriptionBuilder(client=client)._get_pusher_instance( |
| 2274 | key="app-key", cluster="mt1" |
| 2275 | ) |
| 2276 | |
| 2277 | assert "x-api-key" not in pusher.auth_endpoint_headers |
| 2278 | assert pusher.auth_endpoint_headers["x-user-api-key"] == "uak_header_key" |
| 2279 | |
| 2280 | @pytest.mark.parametrize( |
| 2281 | ("cluster", "reason"), |
| 2282 | [ |
| 2283 | ("", "did not include"), |
| 2284 | (None, "did not include"), |
| 2285 | ("MT1", "outside"), |
| 2286 | ("mt1.evil.example", "outside"), |
| 2287 | ("mt1/../evil", "outside"), |
| 2288 | ("mt1 ", "outside"), |
| 2289 | ("mt1:8080", "outside"), |
| 2290 | ("a" * 65, "longer than 64"), |
| 2291 | ], |
| 2292 | ) |
| 2293 | def test_invalid_cluster_is_rejected_before_building_pusher(self, cluster, reason): |
| 2294 | with ( |
| 2295 | patch.object(triggers_module, "_ComposioPusher") as pusher_cls, |
| 2296 | pytest.raises(exceptions.InvalidPusherClusterError, match=reason) as info, |
| 2297 | ): |
| 2298 | self._builder()._get_pusher_instance(key="app-key", cluster=cluster) |
| 2299 | |
| 2300 | pusher_cls.assert_not_called() |
| 2301 | assert isinstance(info.value, exceptions.TriggerSubscriptionError) |
| 2302 | assert isinstance(info.value, exceptions.ValidationError) |
| 2303 | # The offending value is never echoed; the response is untrusted. |
| 2304 | if cluster: |
| 2305 | assert cluster not in str(info.value) |
| 2306 | |
| 2307 | |
| 2308 | class TestPysherLogger: |
| 2309 | def test_module_does_not_import_unittest(self): |
| 2310 | """``unittest.mock`` used to stand in for a logger at runtime.""" |
| 2311 | source = pathlib.Path(triggers_module.__file__).read_text() |
| 2312 | |
| 2313 | assert "unittest" not in source |
| 2314 | assert not hasattr(triggers_module, "mock") |
| 2315 | |
| 2316 | def test_silent_logger_emits_nothing(self, caplog): |
| 2317 | logger = triggers_module._silent_pysher_logger() |
| 2318 | |
| 2319 | assert isinstance(logger, logging.Logger) |
| 2320 | assert logger.propagate is False |
| 2321 | assert any(isinstance(h, logging.NullHandler) for h in logger.handlers) |
| 2322 | with caplog.at_level(logging.DEBUG): |
| 2323 | logger.info("Connection: Message - %s", '{"data": "raw frame"}') |
| 2324 | logger.error("Connection: Error") |
| 2325 | assert caplog.records == [] |
| 2326 | |
| 2327 | def test_silent_logger_is_idempotent(self): |
| 2328 | first = triggers_module._silent_pysher_logger() |
| 2329 | second = triggers_module._silent_pysher_logger() |
| 2330 | |
| 2331 | assert first is second |
| 2332 | assert sum(isinstance(h, logging.NullHandler) for h in first.handlers) == 1 |
| 2333 | |
| 2334 | def test_connect_installs_the_silent_logger(self): |
| 2335 | client = Mock() |
| 2336 | client.base_url = "https://api.example.com" |
| 2337 | pusher = Mock() |
| 2338 | builder = _SubcriptionBuilder(client=client) |
| 2339 | builder.subscription = Mock() |
| 2340 | builder.subscription.is_alive.return_value = True |
| 2341 | builder.internal = Mock() |
| 2342 | builder.internal.get_sdk_realtime_credentials.return_value = Mock( |
| 2343 | project_id="p", pusher_key="k", pusher_cluster="mt1" |
| 2344 | ) |
| 2345 | |
| 2346 | with patch.object( |
| 2347 | _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher |
| 2348 | ): |
| 2349 | builder.connect(timeout=2.0) |
| 2350 | |
| 2351 | assert isinstance(pusher.connection.logger, logging.Logger) |
| 2352 | assert pusher.connection.logger.name == triggers_module._PYSHER_LOGGER_NAME |