1
+"""Security tests for the legacy ``CustomTool`` / ``CustomTools`` API.
2
+
3
+Regression tests for SEC-365 (CWE-639, cross-tenant credential access).
4
+
5
+Before the fix, ``CustomTool.__call__`` extracted ``user_id`` from the same
6
+``**kwargs`` dict that carried LLM-supplied tool arguments, and
7
+``CustomTools.execute`` happily forwarded that LLM-controlled dict via
8
+``custom_tool(**request, user_id=user_id)``. An LLM (or prompt-injection
9
+input) could therefore set ``user_id`` to another tenant's identifier —
10
+either getting it forwarded into ``CustomTool.__call__`` directly or
11
+relying on Python's duplicate-kwarg ``TypeError`` to leak whose tokens
12
+were nearly looked up.
13
+
14
+The fix:
15
+ * ``CustomTools.execute`` strips ``user_id`` from the LLM-supplied
16
+ ``request`` dict at the trust boundary, so only the trusted, explicit
17
+ ``user_id`` parameter reaches the credential lookup.
18
+ * ``CustomTool.__call__`` exposes ``user_id`` as a keyword-only
19
+ parameter and drops any ``user_id`` left in ``kwargs`` before the
20
+ request body is validated.
21
+"""
22
+
23
+from unittest.mock import MagicMock
24
+
25
+import pytest
26
+from pydantic import BaseModel, Field
27
+
28
+from composio.core.models.custom_tools import CustomTool, CustomTools
29
+from composio.exceptions import NotFoundError
30
+
31
+
32
+class _IssueInput(BaseModel):
33
+ issue_number: int = Field(description="GitHub issue number")
34
+
35
+
36
+def _make_mock_client() -> MagicMock:
37
+ """Build a mock HttpClient suitable for CustomTool.__get_auth_credentials."""
38
+
39
+ state = MagicMock()
40
+ state.val.model_dump.return_value = {"access_token": "trusted-token"}
41
+
42
+ account = MagicMock()
43
+ account.created_at = "2026-01-01T00:00:00Z"
44
+ account.state = state
45
+
46
+ response = MagicMock()
47
+ response.items = [account]
48
+
49
+ client = MagicMock()
50
+ client.connected_accounts.list.return_value = response
51
+ client.tools.proxy = MagicMock()
52
+ return client
53
+
54
+
55
+def test_execute_strips_user_id_from_llm_request() -> None:
56
+ """``CustomTools.execute`` MUST strip ``user_id`` from the request dict."""
57
+ client = _make_mock_client()
58
+ tools = CustomTools(client=client)
59
+
60
+ def github_tool(request: _IssueInput, execute_request, auth_credentials):
61
+ """Fetch issue info."""
62
+ return {"token": auth_credentials["access_token"]}
63
+
64
+ tools.register(toolkit="github")(github_tool)
65
+
66
+ result = tools.execute(
67
+ slug="GITHUB_GITHUB_TOOL",
68
+ request={"issue_number": 1, "user_id": "victim-user"},
69
+ user_id="trusted-user",
70
+ )
71
+
72
+ assert result == {"token": "trusted-token"}
73
+ # Only the trusted, explicit user_id reaches the credential lookup.
74
+ client.connected_accounts.list.assert_called_once_with(
75
+ toolkit_slugs=["github"],
76
+ user_ids=["trusted-user"],
77
+ )
78
+
79
+
80
+def test_execute_falls_back_to_default_when_user_id_missing() -> None:
81
+ """If the caller forgets a trusted ``user_id``, fall back to ``"default"``.
82
+
83
+ Specifically, ``execute`` must NOT silently use the LLM-supplied
84
+ ``user_id`` from ``request`` as a fallback — that would re-introduce
85
+ the SEC-365 vulnerability under a different code path.
86
+ """
87
+ client = _make_mock_client()
88
+ tools = CustomTools(client=client)
89
+
90
+ def github_tool(request: _IssueInput, execute_request, auth_credentials):
91
+ """Fetch issue info."""
92
+ return {"ok": True}
93
+
94
+ tools.register(toolkit="github")(github_tool)
95
+
96
+ tools.execute(
97
+ slug="GITHUB_GITHUB_TOOL",
98
+ request={"issue_number": 1, "user_id": "victim-user"},
99
+ user_id=None,
100
+ )
101
+
102
+ client.connected_accounts.list.assert_called_once_with(
103
+ toolkit_slugs=["github"],
104
+ user_ids=["default"],
105
+ )
106
+
107
+
108
+def test_execute_does_not_mutate_caller_request_dict() -> None:
109
+ """Sanitization MUST NOT mutate the caller's ``request`` dict in place."""
110
+ client = _make_mock_client()
111
+ tools = CustomTools(client=client)
112
+
113
+ def github_tool(request: _IssueInput, execute_request, auth_credentials):
114
+ """Fetch issue info."""
115
+ return {"ok": True}
116
+
117
+ tools.register(toolkit="github")(github_tool)
118
+
119
+ request_dict = {"issue_number": 1, "user_id": "victim-user"}
120
+ tools.execute(
121
+ slug="GITHUB_GITHUB_TOOL",
122
+ request=request_dict,
123
+ user_id="trusted-user",
124
+ )
125
+
126
+ # The original dict is untouched (the SDK should not surprise the caller).
127
+ assert request_dict == {"issue_number": 1, "user_id": "victim-user"}
128
+
129
+
130
+def test_call_drops_user_id_smuggled_in_kwargs_dict() -> None:
131
+ """``CustomTool.__call__`` MUST ignore any ``user_id`` smuggled in kwargs.
132
+
133
+ A caller might unpack a partially-trusted dict like ``tool(**llm_dict)``
134
+ without realizing that the LLM controls every key in it. Before the fix,
135
+ a ``user_id`` key in that dict was popped and used to look up OAuth
136
+ credentials — letting an LLM read another tenant's tokens. After the fix,
137
+ ``__call__`` always uses the safe ``"default"`` user_id and the smuggled
138
+ value is dropped before request validation.
139
+ """
140
+ client = _make_mock_client()
141
+
142
+ def github_tool(request: _IssueInput, execute_request, auth_credentials):
143
+ """Fetch issue info."""
144
+ return {"ok": True}
145
+
146
+ tool = CustomTool(f=github_tool, client=client, toolkit="github")
147
+
148
+ smuggled_kwargs = {"issue_number": 1, "user_id": "victim-user"}
149
+ tool(**smuggled_kwargs)
150
+
151
+ client.connected_accounts.list.assert_called_once_with(
152
+ toolkit_slugs=["github"],
153
+ user_ids=["default"],
154
+ )
155
+
156
+
157
+def test_invoke_uses_trusted_user_id_separate_from_request() -> None:
158
+ """``_invoke`` takes ``user_id`` separately from the request dict.
159
+
160
+ This is the trusted internal entry point used by ``CustomTools.execute``.
161
+ Even if the LLM-controlled ``request_kwargs`` happens to contain a
162
+ ``user_id`` key (and somehow gets past the sanitization in ``execute``),
163
+ the ``user_id`` argument here is structurally separate, so the trusted
164
+ value is what reaches the credential lookup.
165
+ """
166
+ client = _make_mock_client()
167
+
168
+ captured: dict = {}
169
+
170
+ def github_tool(request: _IssueInput, execute_request, auth_credentials):
171
+ """Fetch issue info."""
172
+ captured["request"] = request
173
+ return {"ok": True}
174
+
175
+ tool = CustomTool(f=github_tool, client=client, toolkit="github")
176
+ tool._invoke(user_id="trusted-user", request_kwargs={"issue_number": 7})
177
+
178
+ client.connected_accounts.list.assert_called_once_with(
179
+ toolkit_slugs=["github"],
180
+ user_ids=["trusted-user"],
181
+ )
182
+ assert captured["request"].issue_number == 7
183
+
184
+
185
+def test_execute_unknown_slug_raises() -> None:
186
+ """Sanity check: unknown slugs still surface ``NotFoundError``."""
187
+ client = _make_mock_client()
188
+ tools = CustomTools(client=client)
189
+
190
+ with pytest.raises(NotFoundError):
191
+ tools.execute(
192
+ slug="DOES_NOT_EXIST",
193
+ request={"foo": "bar"},
194
+ user_id="trusted-user",
195
+ )